diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
new file mode 100644
index 000000000..471c0f27a
--- /dev/null
+++ b/.github/FUNDING.yml
@@ -0,0 +1,15 @@
+# These are supported funding model platforms
+
+github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
+patreon: # Replace with a single Patreon username
+open_collective: # Replace with a single Open Collective username
+ko_fi: # Replace with a single Ko-fi username
+tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
+community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
+liberapay: # Replace with a single Liberapay username
+issuehunt: # Replace with a single IssueHunt username
+lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
+polar: # Replace with a single Polar username
+buy_me_a_coffee: gorkemcetin
+thanks_dev: # Replace with a single thanks.dev username
+custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 64d8d8ef1..26956309b 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -1,22 +1,26 @@
-**(when sending your PR, only remove this line. Do not remove any lines below. Check all the relevant items before sending your PR)**
+**(Please remove this line only before submitting your PR. Ensure that all relevant items are checked before submission.)**
## Describe your changes
Briefly describe the changes you made and their purpose.
-## Issue number
+## Write your issue number after "Fixes "
-Mention the issue number(s) this PR addresses (e.g., #123).
+Fixes #123
-## Please ensure all items are checked off before requesting a review:
+## Please ensure all items are checked off before requesting a review. "Checked off" means you need to add an "x" character between brackets so they turn into checkmarks.
-- [ ] I deployed the application locally.
-- [ ] I have performed a self-review and testing of my code.
+- [ ] (Do not skip this or your PR will be closed) I deployed the application locally.
+- [ ] (Do not skip this or your PR will be closed) I have performed a self-review and testing of my code.
- [ ] I have included the issue # in the PR.
-- [ ] I have labelled the PR correctly.
-- [ ] The issue I am working on is assigned to me.
+- [ ] I have added i18n support to visible strings (instead of `
Add
`, use):
+```Javascript
+const { t } = useTranslation();
+{t('add')}
+```
+- [ ] I have **not** included any files that are not related to my pull request, including package-lock and package-json if dependencies have not changed
- [ ] I didn't use any hardcoded values (otherwise it will not scale, and will make it difficult to maintain consistency across the application).
-- [ ] I made sure font sizes, color choices etc are all referenced from the theme.
+- [ ] I made sure font sizes, color choices etc are all referenced from the theme. I have no hardcoded dimensions.
- [ ] My PR is granular and targeted to one specific feature.
- [ ] I took a screenshot or a video and attached to this PR if there is a UI change.
diff --git a/.github/scripts/download-translations.js b/.github/scripts/download-translations.js
new file mode 100644
index 000000000..918be97d3
--- /dev/null
+++ b/.github/scripts/download-translations.js
@@ -0,0 +1,90 @@
+import axios from 'axios';
+import fs from 'fs-extra';
+import path from 'path';
+import { URLSearchParams } from 'url';
+
+// POEditor API information
+const API_TOKEN = process.env.POEDITOR_API;
+const PROJECT_ID = process.env.POEDITOR_PROJECT_ID;
+const LANGUAGES = (process.env.LANGUAGES || 'tr,en').split(',');
+const EXPORT_FORMAT = process.env.EXPORT_FORMAT || 'key_value_json';
+
+// POEditor API endpoint
+const API_URL = 'https://api.poeditor.com/v2';
+
+// Function to download translations
+async function downloadTranslations() {
+ try {
+ console.log('Downloading translations from POEditor...');
+ console.log(`Using export format: ${EXPORT_FORMAT}`);
+
+ for (const language of LANGUAGES) {
+ console.log(`Downloading translations for ${language} language...`);
+
+ // Get export URL from POEditor
+ const exportResponse = await axios.post(`${API_URL}/projects/export`,
+ new URLSearchParams({
+ api_token: API_TOKEN,
+ id: PROJECT_ID,
+ language: language,
+ type: EXPORT_FORMAT
+ })
+ );
+
+ if (exportResponse.data.response.status !== 'success') {
+ throw new Error(`Failed to get export URL for ${language} language: ${JSON.stringify(exportResponse.data)}`);
+ }
+
+ const fileUrl = exportResponse.data.result.url;
+ console.log(`Export URL obtained for ${language}`);
+
+ // Download translation file
+ const downloadResponse = await axios.get(fileUrl, { responseType: 'json' });
+ const translations = downloadResponse.data;
+ console.log(`Downloaded translations for ${language}`);
+
+ // Check the format of data returned from POEditor and convert if necessary
+ let formattedTranslations = translations;
+
+ // If data is in array format, convert it to key-value format
+ if (Array.isArray(translations)) {
+ console.log(`Converting array format to key-value format for ${language}`);
+ formattedTranslations = {};
+ translations.forEach(item => {
+ if (item.term && item.definition) {
+ formattedTranslations[item.term] = item.definition;
+ }
+ });
+ }
+
+ // Determine the output filename based on language
+ const filename = language === 'en' ? 'gb.json' : `${language}.json`;
+ const outputPath = path.join(process.cwd(), 'temp', filename);
+ await fs.writeJson(outputPath, formattedTranslations, { spaces: 2 });
+
+ console.log(`Translations for ${language} language successfully downloaded and saved as: ${filename}`);
+ }
+
+ console.log('All translations successfully downloaded!');
+ } catch (error) {
+ console.error('An error occurred while downloading translations:', error);
+ process.exit(1);
+ }
+}
+
+// Main function
+async function main() {
+ try {
+ // Clean temp folder
+ await fs.emptyDir(path.join(process.cwd(), 'temp'));
+
+ // Download translations
+ await downloadTranslations();
+ } catch (error) {
+ console.error('An error occurred during the process:', error);
+ process.exit(1);
+ }
+}
+
+// Run script
+main();
\ No newline at end of file
diff --git a/.github/scripts/upload-translations.js b/.github/scripts/upload-translations.js
new file mode 100644
index 000000000..aa23cf35f
--- /dev/null
+++ b/.github/scripts/upload-translations.js
@@ -0,0 +1,64 @@
+import axios from "axios";
+import FormData from "form-data";
+import fs from "fs-extra";
+
+// POEditor API information
+const API_TOKEN = process.env.POEDITOR_API;
+const PROJECT_ID = process.env.POEDITOR_PROJECT_ID;
+const FILE_PATH = process.env.FILE_PATH;
+const LANGUAGE = process.env.LANGUAGE;
+
+// POEditor API endpoint
+const API_URL = 'https://api.poeditor.com/v2';
+
+// Function to upload translations
+async function uploadTranslations() {
+ try {
+ console.log(`Uploading translations for ${LANGUAGE} language from ${FILE_PATH}... test1`);
+
+ // Check if file exists
+ if (!await fs.pathExists(FILE_PATH)) {
+ throw new Error(`File not found: ${FILE_PATH}`);
+ }
+
+ // Read file content
+ const fileContent = await fs.readFile(FILE_PATH, 'utf8');
+
+ // Validate JSON format
+ try {
+ JSON.parse(fileContent);
+ } catch (error) {
+ throw new Error(`Invalid JSON format in ${FILE_PATH}: ${error.message}`);
+ }
+
+ // Create form data for upload
+ const formData = new FormData();
+ formData.append('api_token', API_TOKEN);
+ formData.append('id', PROJECT_ID);
+ formData.append('language', LANGUAGE);
+ formData.append('updating', 'terms_translations');
+ formData.append('file', fs.createReadStream(FILE_PATH));
+ formData.append('overwrite', '1');
+ formData.append('sync_terms', '1');
+
+ // Upload to POEditor
+ const response = await axios.post(`${API_URL}/projects/upload`, formData, {
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ }
+ });
+
+ if (response.data.response.status !== 'success') {
+ throw new Error(`Failed to upload translations: ${JSON.stringify(response.data)}`);
+ }
+
+ console.log(`Successfully uploaded translations for ${LANGUAGE} language.`);
+ console.log(`Statistics: ${JSON.stringify(response.data.result)}`);
+ } catch (error) {
+ console.error('An error occurred while uploading translations:', error);
+ process.exit(1);
+ }
+}
+
+// Run script
+uploadTranslations();
diff --git a/.github/workflows/README.md b/.github/workflows/README.md
new file mode 100644
index 000000000..774a816b3
--- /dev/null
+++ b/.github/workflows/README.md
@@ -0,0 +1,69 @@
+# POEditor Translation Synchronization
+
+This GitHub Actions workflow automatically downloads translation files from POEditor and integrates them into the project.
+
+## How It Works
+
+The workflow can be triggered in two ways:
+
+1. **Manual Trigger**: You can manually run the "POEditor Translation Synchronization" workflow from the "Actions" tab in the GitHub interface.
+2. **Automatic Trigger**: The workflow runs automatically every day at midnight (UTC).
+
+## Required Settings
+
+For this workflow to function, you need to define the following secrets in your GitHub repository:
+
+1. `POEDITOR_API_TOKEN`: Your POEditor API token
+2. `POEDITOR_PROJECT_ID`: Your POEditor project ID
+
+You can add these secrets in the "Settings > Secrets and variables > Actions" section of your GitHub repository.
+
+## Manual Execution
+
+When running the workflow manually, you can specify which languages to download. Languages should be entered as comma-separated values (e.g., `tr,gb,es`).
+
+If you don't specify any languages, the default languages `tr` and `en` will be downloaded.
+
+## Output
+
+When the workflow completes successfully:
+
+1. Translation files for the specified languages are downloaded from POEditor
+2. These files are copied to the `src/locales/` directory
+3. Changes are automatically committed and pushed to the main branch
+
+## Troubleshooting
+
+If the workflow fails:
+
+1. Check the GitHub Actions logs
+2. Make sure your POEditor API token and project ID are correct
+3. Ensure that the languages you specified exist in your POEditor project
+
+# POEditor Upload Workflow
+
+## Summary of Implemented Translation Workflow
+
+We have successfully created a GitHub Actions workflow that automatically uploads translation files to POEditor when changes are merged to the develop branch. Here's a summary of what we've implemented:
+### Created Files
+
+1. .github/scripts/upload-translations.js
+
+- A Node.js script that handles the upload of translation files to POEditor
+- Uses the POEditor API to upload JSON translation files
+- Validates file existence and JSON format before uploading
+- Provides detailed logging of the upload process
+
+2. .github/workflows/poeditor-upload-on-merge.yml - A GitHub Actions workflow that triggers when PRs are merged to the develop branch - Only runs when changes are made to files in the src/locales directory - Detects which translation files were changed in the PR - Extracts language codes from filenames (e.g., tr.json → "tr") - Calls the upload script for each changed file
+ ### Workflow Process
+1. When a PR is merged to the develop branch, the workflow checks if any files in src/locales were modified.
+
+1. If translation files were changed, the workflow:
+
+- Sets up the necessary Node.js environment
+- Installs required dependencies
+- Identifies which specific translation files were changed
+- For each changed file, extracts the language code and uploads to POEditor
+- Provides status notifications about the upload process
+
+This automated workflow ensures that your translations are always in sync between your codebase and POEditor, eliminating the need for manual uploads and reducing the risk of translation inconsistencies.
diff --git a/.github/workflows/distribution-deploy.yml b/.github/workflows/distribution-deploy.yml
new file mode 100644
index 000000000..b96a0f3d7
--- /dev/null
+++ b/.github/workflows/distribution-deploy.yml
@@ -0,0 +1,77 @@
+name: Distribution deploy
+
+on:
+ push:
+ branches: ["master"]
+ workflow_dispatch:
+jobs:
+ docker-build-and-push-client:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Build Client Docker image
+ run: |
+ docker build \
+ -t ghcr.io/bluewave-labs/checkmate:frontend-dist \
+ -f ./docker/dist/client.Dockerfile \
+ --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate \
+ .
+
+ - name: Push Client Docker image
+ run: docker push ghcr.io/bluewave-labs/checkmate:frontend-dist
+
+ docker-build-and-push-server:
+ needs: docker-build-and-push-client
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Build Server Docker image
+ run: |
+ docker build \
+ -t ghcr.io/bluewave-labs/checkmate:backend-dist \
+ -f ./docker/dist/server.Dockerfile \
+ --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate \
+ .
+
+ - name: Push Server Docker image
+ run: docker push ghcr.io/bluewave-labs/checkmate:backend-dist
+
+ - name: Build Mongo Docker image
+ run: |
+ docker build \
+ -t ghcr.io/bluewave-labs/checkmate:mongo-dist \
+ -f ./docker/dist/mongoDB.Dockerfile \
+ --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate \
+ .
+
+ - name: Push MongoDB Docker image
+ run: docker push ghcr.io/bluewave-labs/checkmate:mongo-dist
+
+ - name: Build Redis Docker image
+ run: |
+ docker build \
+ -t ghcr.io/bluewave-labs/checkmate:redis-dist \
+ -f ./docker/dist/redis.Dockerfile \
+ --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate \
+ .
+
+ - name: Push Redis Docker image
+ run: docker push ghcr.io/bluewave-labs/checkmate:redis-dist
diff --git a/.github/workflows/poeditor-sync.yml b/.github/workflows/poeditor-sync.yml
new file mode 100644
index 000000000..8446745bc
--- /dev/null
+++ b/.github/workflows/poeditor-sync.yml
@@ -0,0 +1,115 @@
+name: POEditor Translation Synchronization
+
+on:
+ # For manual triggering
+ workflow_dispatch:
+ inputs:
+ languages:
+ description: "Languages to synchronize (comma separated, e.g.: tr,en,es)"
+ required: false
+ default: "tr,en"
+ format:
+ description: "Export format (key_value_json or json)"
+ required: false
+ default: "key_value_json"
+
+
+permissions:
+ contents: write
+ pull-requests: write
+
+jobs:
+ sync-translations:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ issues: write
+ pull-requests: write
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v3
+ with:
+ token: ${{ secrets.GITHUB_TOKEN }}
+ fetch-depth: 0
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v3
+ with:
+ node-version: "22"
+
+ - name: Create package.json for scripts
+ run: |
+ mkdir -p .github/scripts
+ cat > .github/scripts/package.json << EOF
+ {
+ "name": "poeditor-scripts",
+ "version": "1.0.0",
+ "private": true,
+ "type": "module",
+ "dependencies": {
+ "axios": "^1.6.0",
+ "fs-extra": "^11.1.1"
+ }
+ }
+ EOF
+
+ - name: Install dependencies
+ run: |
+ cd .github/scripts
+ npm install
+
+ - name: Download translations from POEditor
+ env:
+ POEDITOR_API: ${{ secrets.POEDITOR_API }}
+ POEDITOR_PROJECT_ID: ${{ secrets.POEDITOR_PROJECT_ID }}
+ LANGUAGES: ${{ github.event.inputs.languages || 'tr,en' }}
+ EXPORT_FORMAT: ${{ github.event.inputs.format || 'key_value_json' }}
+ run: |
+ mkdir -p temp
+ node .github/scripts/download-translations.js
+
+ - name: Verify translation files
+ run: |
+ echo "Verifying translation files..."
+ for file in temp/*.json; do
+ echo "Checking $file"
+ if [ ! -s "$file" ]; then
+ echo "Error: $file is empty or does not exist"
+ exit 1
+ fi
+ # Validate JSON format
+ cat "$file" | jq . > /dev/null || { echo "Error: $file is not valid JSON"; exit 1; }
+ done
+ echo "All translation files are valid"
+
+ - name: Copy translations to project
+ run: |
+ mkdir -p client/src/locales
+ cp -r temp/* client/src/locales/
+ echo "Translation files copied to client/src/locales/"
+
+ - name: Get current date
+ id: date
+ run: echo "date=$(date +'%Y-%m-%d %H:%M:%S')" >> $GITHUB_OUTPUT
+
+ - name: Create Pull Request
+ uses: peter-evans/create-pull-request@v7
+ with:
+ token: ${{ secrets.GITHUB_TOKEN }}
+ commit-message: "feat: translations updated from POEditor"
+ title: "🌐 Updated Translations from POEditor"
+ body: |
+ This PR contains the latest translations from POEditor.
+
+ 📅 Update Date: ${{ steps.date.outputs.date }}
+ 🔄 Updated Languages: ${{ github.event.inputs.languages || 'tr,en' }}
+
+ ⚠️ Please review the translations and approve the PR if everything looks correct.
+ branch: translation-update-${{ github.run_number }}
+ delete-branch: true
+ base: develop
+ add-paths: |
+ client/src/locales/*.json
+ committer: GitHub Action
+ author: GitHub Action
diff --git a/.github/workflows/production-deploy.yml b/.github/workflows/production-deploy.yml
new file mode 100644
index 000000000..6956f5caa
--- /dev/null
+++ b/.github/workflows/production-deploy.yml
@@ -0,0 +1,95 @@
+name: Demo deploy
+
+on:
+ push:
+ branches: ["demo"]
+ workflow_dispatch:
+jobs:
+ docker-build-and-push-client:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Build Client Docker image
+ run: |
+ docker build \
+ -t ghcr.io/bluewave-labs/checkmate:frontend-demo \
+ -f ./docker/prod/client.Dockerfile \
+ --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate \
+ .
+
+ - name: Push Client Docker image
+ run: docker push ghcr.io/bluewave-labs/checkmate:frontend-demo
+
+ docker-build-and-push-server:
+ needs: docker-build-and-push-client
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Build Server Docker image
+ run: |
+ docker build \
+ -t ghcr.io/bluewave-labs/checkmate:backend-demo \
+ -f ./docker/prod/server.Dockerfile \
+ --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate \
+ .
+
+ - name: Push Server Docker image
+ run: docker push ghcr.io/bluewave-labs/checkmate:backend-demo
+
+ - name: Build Mongo Docker image
+ run: |
+ docker build \
+ -t ghcr.io/bluewave-labs/checkmate:mongo-demo \
+ -f ./docker/prod/mongoDB.Dockerfile \
+ --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate \
+ .
+
+ - name: Push MongoDB Docker image
+ run: docker push ghcr.io/bluewave-labs/checkmate:mongo-demo
+
+ - name: Build Redis Docker image
+ run: |
+ docker build \
+ -t ghcr.io/bluewave-labs/checkmate:redis-demo \
+ -f ./docker/prod/redis.Dockerfile \
+ --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate \
+ .
+
+ - name: Push Redis Docker image
+ run: docker push ghcr.io/bluewave-labs/checkmate:redis-demo
+
+ deploy-to-demo:
+ needs: docker-build-and-push-server
+ runs-on: ubuntu-latest
+ steps:
+ - name: SSH into server and restart container using Docker Compose
+ uses: appleboy/ssh-action@v1.2.2
+ with:
+ host: ${{ secrets.DEMO_SERVER_HOST }}
+ username: ${{ secrets.DEMO_SERVER_USER }}
+ key: ${{ secrets.DEMO_SERVER_SSH_KEY }}
+ script: |
+ cd checkmate
+ git pull
+ cd docker/prod
+ docker compose down
+ docker compose pull
+ docker compose up -d
diff --git a/.github/workflows/staging-deploy.yml b/.github/workflows/staging-deploy.yml
new file mode 100644
index 000000000..34fa243c6
--- /dev/null
+++ b/.github/workflows/staging-deploy.yml
@@ -0,0 +1,95 @@
+name: Staging deploy
+
+on:
+ push:
+ branches: ["develop"]
+
+jobs:
+ docker-build-and-push-client:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Build Client Docker image
+ run: |
+ docker build \
+ -t ghcr.io/bluewave-labs/checkmate:frontend-staging \
+ -f ./docker/staging/client.Dockerfile \
+ --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate \
+ .
+
+ - name: Push Client Docker image
+ run: docker push ghcr.io/bluewave-labs/checkmate:frontend-staging
+
+ docker-build-and-push-server:
+ needs: docker-build-and-push-client
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Build Server Docker image
+ run: |
+ docker build \
+ -t ghcr.io/bluewave-labs/checkmate:backend-staging \
+ -f ./docker/staging/server.Dockerfile \
+ --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate \
+ .
+
+ - name: Push Server Docker image
+ run: docker push ghcr.io/bluewave-labs/checkmate:backend-staging
+
+ - name: Build Mongo Docker image
+ run: |
+ docker build \
+ -t ghcr.io/bluewave-labs/checkmate:mongo-staging \
+ -f ./docker/staging/mongoDB.Dockerfile \
+ --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate \
+ .
+
+ - name: Push MongoDB Docker image
+ run: docker push ghcr.io/bluewave-labs/checkmate:mongo-staging
+
+ - name: Build Redis Docker image
+ run: |
+ docker build \
+ -t ghcr.io/bluewave-labs/checkmate:redis-staging \
+ -f ./docker/staging/redis.Dockerfile \
+ --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate \
+ .
+
+ - name: Push Redis Docker image
+ run: docker push ghcr.io/bluewave-labs/checkmate:redis-staging
+
+ deploy-to-staging:
+ needs: docker-build-and-push-server
+ runs-on: ubuntu-latest
+ steps:
+ - name: SSH into server and restart container using Docker Compose
+ uses: appleboy/ssh-action@v1.2.2
+ with:
+ host: ${{ secrets.STAGING_SERVER_HOST }}
+ username: ${{ secrets.STAGING_SERVER_USER }}
+ key: ${{ secrets.STAGING_SERVER_SSH_KEY }}
+ script: |
+ cd checkmate
+ git pull
+ cd docker/staging
+ docker compose down
+ docker compose pull
+ docker compose up -d
diff --git a/.github/workflows/upload-poeditor.yml b/.github/workflows/upload-poeditor.yml
new file mode 100644
index 000000000..f695c8bbc
--- /dev/null
+++ b/.github/workflows/upload-poeditor.yml
@@ -0,0 +1,113 @@
+name: Upload Translations to POEditor on PR Merge
+
+on:
+ pull_request:
+ types: [closed]
+ branches:
+ - develop
+ paths:
+ - "client/src/locales/**"
+
+jobs:
+ upload-translations:
+ # Only run if the PR was merged (not just closed) or manually triggered
+ if: github.event.pull_request.merged == true
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 0 # Fetch all history to get changed files
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v3
+ with:
+ node-version: "22"
+
+ - name: Create package.json for scripts
+ run: |
+ mkdir -p .github/scripts
+ cat > .github/scripts/package.json << EOF
+ {
+ "name": "poeditor-scripts",
+ "version": "1.0.0",
+ "private": true,
+ "type": "module",
+ "dependencies": {
+ "axios": "^1.6.0",
+ "fs-extra": "^11.1.1",
+ "form-data": "^4.0.0"
+ }
+ }
+ EOF
+
+ - name: Install dependencies
+ run: |
+ cd .github/scripts
+ npm install
+
+ - name: Get changed locale files
+ id: changed-files
+ if: github.event_name == 'pull_request'
+ run: |
+ # Get base and head commits
+ BASE_SHA=${{ github.event.pull_request.base.sha }}
+ HEAD_SHA=${{ github.event.pull_request.head.sha }}
+
+ echo "Base SHA: $BASE_SHA"
+ echo "Head SHA: $HEAD_SHA"
+
+ # Get list of changed files in client/src/locales directory
+ CHANGED_FILES=$(git diff --name-only $BASE_SHA..$HEAD_SHA -- 'client/src/locales/*.json' || git ls-files 'client/src/locales/*.json')
+
+ if [ -z "$CHANGED_FILES" ]; then
+ echo "No changes detected in locale files"
+ echo "CHANGED_FILES=" >> $GITHUB_ENV
+ else
+ echo "Changed files:"
+ echo "$CHANGED_FILES"
+ echo "CHANGED_FILES<> $GITHUB_ENV
+ echo "$CHANGED_FILES" >> $GITHUB_ENV
+ echo "EOF" >> $GITHUB_ENV
+ fi
+
+ - name: Upload changed translations to POEditor
+ if: env.CHANGED_FILES != ''
+ env:
+ POEDITOR_API: ${{ secrets.POEDITOR_API }}
+ POEDITOR_PROJECT_ID: ${{ secrets.POEDITOR_PROJECT_ID }}
+ run: |
+ # Process each changed file
+ for FILE in $CHANGED_FILES; do
+ if [[ -f "$FILE" ]]; then
+ # Extract language code from filename (e.g., client/src/locales/en.json -> en)
+ FILENAME=$(basename "$FILE")
+
+ # Special case: map gb.json to en language code
+ if [ "$FILENAME" == "gb.json" ]; then
+ LANG="en"
+ echo "Found gb.json, mapping to language code 'en'"
+ else
+ LANG=$(basename "$FILE" .json)
+ fi
+
+ echo "Processing $FILE for language $LANG"
+
+ # Upload to POEditor
+ LANGUAGE=$LANG FILE_PATH=$FILE node .github/scripts/upload-translations.js
+ fi
+ done
+
+ - name: Notify on success
+ if: success() && env.CHANGED_FILES != ''
+ run: |
+ echo "Successfully uploaded translation files to POEditor."
+ if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
+ echo "Manual trigger comment: ${{ github.event.inputs.comment }}"
+ fi
+
+ - name: Notify on no changes
+ if: env.CHANGED_FILES == ''
+ run: |
+ echo "No translation files were found to upload."
diff --git a/.gitignore b/.gitignore
deleted file mode 100644
index a0420fec9..000000000
--- a/.gitignore
+++ /dev/null
@@ -1,5 +0,0 @@
-.vite
-.vscode
-*.sh
-!uptime.sh
-*.idea
\ No newline at end of file
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 8db035b8a..702436b38 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,98 +1,149 @@
-
# Contributing to Checkmate
-First off, thanks for taking the time to contribute! ❤️
+Thanks for your interest in contributing! Checkmate is an open-source, friendly project focused on learning and growth.
-All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how the Checkmate project handles them. Please make sure to read the relevant section before making your contribution. It will make it much easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉
+We truly appreciate all kinds of contributions — code, ideas, translations or documentation. Contributing helps you level up while making the project better for everyone.
-> And if you like the project, but don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about:
-> - Star the project
-> - Tweet about it
-> - Refer this project in your project's readme
-> - Mention the project at local meetups and tell your friends/colleagues
+Before you start, please take a moment to read the relevant section. It helps us review and accept contributions faster, and makes the whole process smoother for everyone. 💚
-## Table of Contents
+PS: **We work closely with contributors on our [Discord channel](https://discord.com/invite/NAb6H3UTjK)**. You’ll find community members, core maintainers, and first-timers helping each other out.
-- [I Have a Question](#i-have-a-question)
-- [I Want To Contribute](#i-want-to-contribute)
-- [Suggesting Enhancements](#suggesting-enhancements)
+---
-## I Have a Question
+## Table of contents
-If you'd like to ask a question, we assume that you have read the available readme.md files. In the near future we'll come up with a proper installation and usage document.
+- [How do I...?](#how-do-i)
+ - [Get help or ask a question?](#get-help-or-ask-a-question)
+ - [Report a bug?](#report-a-bug)
+ - [Suggest a new feature?](#suggest-a-new-feature)
+ - [Set up Checkmate locally?](#set-up-checkmate-locally)
+ - [Start contributing code?](#start-contributing-code)
+ - [Improve the documentation?](#improve-the-documentation)
+ - [Help with translations?](#help-with-translations)
+ - [Submit a pull request?](#submit-a-pull-request)
+- [Code guidelines](#code-guidelines)
+- [Pull request checklist](#pull-request-checklist)
+- [Branching model](#branching-model)
+- [Thank you](#thank-you)
-Before you ask a question, search for existing [Issues](/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first.
+---
-If you then still feel the need to ask a question and need clarification, we recommend the following:
+## How do I...
-- Open an [Issue](/issues/new).
-- Provide as much context as you can about what you're running into.
-- Provide project and platform versions (NodeJs, MongoDB, etc), depending on what seems relevant.
+### Get help or ask a question?
-We will then take care of the issue as soon as possible.
+Ask anything in our [Discord server](https://discord.com/invite/NAb6H3UTjK) — we’re friendly and happy to help. [Our core contributors](https://github.com/bluewave-labs/checkmate?tab=readme-ov-file#-contributing) are active and ready to support you. You can also use [GitHub Discussions](https://github.com/bluewave-labs/Checkmate/discussions) section to ask your questions.
+
+### Report a bug?
+
+1. Search [existing issues](https://github.com/bluewave-labs/checkmate/issues).
+2. If it’s not listed, open a **new issue**.
+3. Include as much detail as possible: what happened, what you expected, and steps to reproduce. Logs and screenshots help.
+
+### Suggest a new feature?
+
+1. Open a new issue with the **feature request** template.
+2. Share your use case and why it would help.
+3. You can discuss it in [Discord](https://discord.com/invite/NAb6H3UTjK) before you code.
+
+### Set up Checkmate locally?
+
+Frontend & backend:
+```bash
+npm install
+npm run dev
+```
+
+By default, the frontend expects the backend on `http://localhost:3001`. Update configs if needed.
+
+### Start contributing code?
+
+1. Pick or open an issue (check `good-first-issue`s first)
+2. (optional but highly suggested) Read a detailed structure of [Checkmate](https://deepwiki.com/bluewave-labs/Checkmate) if you would like to deep dive into the architecture.
+3. Ask to be assigned. If there is alrady someone assigned and it's been more than 7 days, you can raise the flag and ask to be assigned as well.
+4. Create a branch from `develop`.
+5. Write your code.
+6. Run and test locally.
+7. Open a PR to `develop`.
+
+Start with [good first issues](https://github.com/bluewave-labs/checkmate/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22).
+
+### Improve the documentation?
+
+Docs live in [checkmate-documentation](https://github.com/bluewave-labs/checkmate-documentation). You can fix typos, add guides, or explain features better.
+
+### Help with translations?
+
+We use [PoEditor](https://poeditor.com) for translations. You can:
+- [Sign up and join your language team](https://poeditor.com/join/project/lRUoGZFCsJ).
+- Translate UI strings.
+- Ask questions on Discord in the relevant #translations channel.
+
+Make sure all new UI strings in code use `t('key')`.
+
+### Submit a pull request?
+
+Follow the [pull request checklist](#pull-request-checklist). Your PR should:
+- Be focused on one issue.
+- Be tested locally.
+- Use our linting and translation rules.
+- Include the related issue (e.g. `Fixes #123`).
+- Be opened against the `develop` branch.
+
+---
+
+## Code guidelines
+
+- Use ESLint and Prettier (`npm run lint`).
+- Follow naming conventions: `camelCase` for variables, `PascalCase` for components, `UPPER_CASE` for constants.
+- No hard-coded strings — use `t('your.key')` for everything visible.
+- Use the shared theme and components. No magic numbers or hardcoded styles.
+- Follow structure and patterns already used in the codebase.
+
+---
+
+## Pull request checklist
+
+Before submitting your pull request, please confirm the following:
+
+- **You have tested the app locally and confirmed your changes work.**
+- You reviewed your code and removed debug logs or leftover code.
+- The GitHub issue is assigned to you.
+- You included the related issue number in the PR description (e.g. `Fixes #123`).
+- All user-facing text uses the translation function `t('key')`; no hardcoded strings.
+- You avoided hardcoded URLs, config values, or sensitive data.
+- You used the shared theme for any styling — no magic numbers or inline styles.
+- The pull request addresses only one issue or topic.
+- You added screenshots or a video for any UI-related changes.
+- Your code passes linting and has no TypeScript errors.
+
+If one or more of these are missing, we may ask you to update your pull request before we can merge it.
+
+---
+
+## Branching model
-## I Want To Contribute
-
-> ### Legal Notice
-> When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license.
-
-### Reporting Bugs
-
-#### Before Submitting a Bug Report
-
-A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible.
-
-- Make sure that you are using the latest version.
-- Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions. If you are looking for support, you might want to check [this section](#i-have-a-question)).
-- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](issues?q=label%3Abug).
-- Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue.
-- Collect information about the bug:
-- Stack trace (Traceback)
-- OS, Platform and Version (Windows, Linux, macOS, x86, ARM)
-- Version of the interpreter, compiler, SDK, runtime environment and package manager, depending on what seems relevant.
-- Possibly your input and the output
-- Can you reliably reproduce the issue? And can you also reproduce it with older versions?
-
-
-#### How Do I Submit a Good Bug Report?
-
-> You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to security@bluewavelabs.ca
-
-We use GitHub issues to track bugs and errors. If you run into an issue with the project:
-
-- Open an [Issue](/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.)
-- Explain the behaviour you would expect and the actual behaviour.
-- Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports, you should isolate the problem and create a reduced test case.
-- Provide the information you collected in the previous section.
-
-Once it's filed:
-
-- The project team will label the issue accordingly.
-- A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced.
-- If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be [implemented by someone](#your-first-code-contribution).
-
-## Suggesting Enhancements
-
-This section guides you through submitting an enhancement suggestion for the application, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community understand your enhancements and find related suggestions.
-
+- Code contributions should go to the `develop` branch.
+- `master` is used for stable releases.
+- Use descriptive branch names, like `fix/login-error` or `feat/add-alerts`.
- Make sure that you are using the latest version.
- Make sure you run the code locally. The Checkmate [documentation](https://docs.checkmate.so) covers it.
- Find out if the functionality is already covered, maybe by an individual configuration.
- Perform a [search](/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one.
- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library.
-#### How Do I Submit a Good Enhancement Suggestion?
+---
-Enhancement suggestions are tracked as [GitHub issues](/issues).
+## Thank you
-- Use a **clear and descriptive title** for the issue to identify the suggestion.
-- Provide a **step-by-step description of the suggested enhancement** in as many details as possible.
-- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you.
-- You may want to **include screenshots and animated GIFs** which help you demonstrate the steps or point out the part which the suggestion is related to.
-- **Explain why this enhancement would be useful** to most CONTRIBUTING.md users. You may also want to point out the other projects that solved it better and which could serve as inspiration.
+Thanks for making Checkmate better. We mean it. Whether it’s your first pull request or your 50th, we’re excited to build with you.
+
+
+PS: feel free to introduce yourself on [Discord](https://discord.gg/YOUR-DISCORD-LINK) and say hi.
+
+-- Checkmate team
Also make sure you read the [document about how to make a good pull request](/PULLREQUESTS.md).
-## Attribution
-This guide is based on the **contributing.md**. [Make your own](https://contributing.md/)!
+
diff --git a/Client/.env.production b/Client/.env.production
deleted file mode 100644
index a5bce84e1..000000000
--- a/Client/.env.production
+++ /dev/null
@@ -1 +0,0 @@
-VITE_APP_API_BASE_URL=UPTIME_APP_API_BASE_URL
diff --git a/Client/README.md b/Client/README.md
deleted file mode 100644
index f768e33fc..000000000
--- a/Client/README.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# React + Vite
-
-This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
-
-Currently, two official plugins are available:
-
-- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
-- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
diff --git a/Client/src/Components/BasicTable/index.jsx b/Client/src/Components/BasicTable/index.jsx
deleted file mode 100644
index b93c584da..000000000
--- a/Client/src/Components/BasicTable/index.jsx
+++ /dev/null
@@ -1,360 +0,0 @@
-/* TODO
-
-Should we delete this?
-*/
-
-import PropTypes from "prop-types";
-import { useState, useEffect } from "react";
-import { useTheme } from "@emotion/react";
-import {
- TableContainer,
- Paper,
- Table,
- TableHead,
- TableRow,
- TableCell,
- TableBody,
- TablePagination,
- Box,
- Typography,
- Stack,
- Button,
-} from "@mui/material";
-import { useDispatch, useSelector } from "react-redux";
-import { setRowsPerPage } from "../../Features/UI/uiSlice";
-import LeftArrowDouble from "../../assets/icons/left-arrow-double.svg?react";
-import RightArrowDouble from "../../assets/icons/right-arrow-double.svg?react";
-import LeftArrow from "../../assets/icons/left-arrow.svg?react";
-import RightArrow from "../../assets/icons/right-arrow.svg?react";
-import SelectorVertical from "../../assets/icons/selector-vertical.svg?react";
-import "./index.css";
-/**
- * Component for pagination actions (first, previous, next, last).
- *
- * @component
- * @param {Object} props
- * @param {number} props.count - Total number of items.
- * @param {number} props.page - Current page number.
- * @param {number} props.rowsPerPage - Number of rows per page.
- * @param {function} props.onPageChange - Callback function to handle page change.
- *
- * @returns {JSX.Element} Pagination actions component.
- */
-const TablePaginationActions = (props) => {
- const { count, page, rowsPerPage, onPageChange } = props;
-
- const handleFirstPageButtonClick = (event) => {
- onPageChange(event, 0);
- };
- const handleBackButtonClick = (event) => {
- onPageChange(event, page - 1);
- };
- const handleNextButtonClick = (event) => {
- onPageChange(event, page + 1);
- };
- const handleLastPageButtonClick = (event) => {
- onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1));
- };
-
- return (
-
-
-
-
-
-
-
- = Math.ceil(count / rowsPerPage) - 1}
- aria-label="next page"
- >
-
-
- = Math.ceil(count / rowsPerPage) - 1}
- aria-label="last page"
- >
-
-
-
- );
-};
-
-TablePaginationActions.propTypes = {
- count: PropTypes.number.isRequired,
- page: PropTypes.number.isRequired,
- rowsPerPage: PropTypes.number.isRequired,
- onPageChange: PropTypes.func.isRequired,
-};
-
-/**
- * BasicTable Component
- * Renders a table with optional pagination.
- *
- * @component
- * @param {Object} props - Component props.
- * @param {Object} props.data - Data for the table including columns and rows.
- * @param {Array} props.data.cols - Array of objects for column headers.
- * @param {number} props.data.cols[].id - Unique identifier for the column.
- * @param {string} props.data.cols[].name - Name of the column to display as header.
- * @param {Array} props.data.rows - Array of row objects.
- * @param {number} props.data.rows[].id - Unique identifier for the row.
- * @param {Array} props.data.rows[].data - Array of cell data objects for the row.
- * @param {number} props.data.rows[].data[].id - Unique identifier for the cell.
- * @param {JSX.Element} props.data.rows[].data[].data - The content to display in the cell.
- * @param {function} props.data.rows.data.handleClick - Function to call when the row is clicked.
- * @param {boolean} [props.paginated=false] - Flag to enable pagination.
- * @param {boolean} [props.reversed=false] - Flag to enable reverse order.
- * @param {number} props.rowsPerPage- Number of rows per page (table).
- * @param {string} props.emptyMessage - Message to display when there is no data.
- * @example
- * const data = {
- * cols: [
- * { id: 1, name: "First Col" },
- * { id: 2, name: "Second Col" },
- * { id: 3, name: "Third Col" },
- * { id: 4, name: "Fourth Col" },
- * ],
- * rows: [
- * {
- * id: 1,
- * data: [
- * { id: 1, data: Data for Row 1 Col 1
},
- * { id: 2, data: Data for Row 1 Col 2
},
- * { id: 3, data: Data for Row 1 Col 3
},
- * { id: 4, data: Data for Row 1 Col 4
},
- * ],
- * },
- * {
- * id: 2,
- * data: [
- * { id: 5, data: Data for Row 2 Col 1
},
- * { id: 6, data: Data for Row 2 Col 2
},
- * { id: 7, data: Data for Row 2 Col 3
},
- * { id: 8, data: Data for Row 2 Col 4
},
- * ],
- * },
- * ],
- * };
- *
- *
- */
-
-const BasicTable = ({ data, paginated, reversed, table, emptyMessage = "No data" }) => {
- const DEFAULT_ROWS_PER_PAGE = 5;
- const theme = useTheme();
- const dispatch = useDispatch();
- const uiState = useSelector((state) => state.ui);
- let rowsPerPage = uiState?.[table]?.rowsPerPage ?? DEFAULT_ROWS_PER_PAGE;
- const [page, setPage] = useState(0);
-
- useEffect(() => {
- setPage(0);
- }, [data]);
-
- const handleChangePage = (event, newPage) => {
- setPage(newPage);
- };
-
- const handleChangeRowsPerPage = (event) => {
- dispatch(
- setRowsPerPage({
- value: parseInt(event.target.value, 10),
- table: table,
- })
- );
- setPage(0);
- };
-
- let displayData = [];
-
- if (data && data.rows) {
- let rows = reversed ? [...data.rows].reverse() : data.rows;
- displayData = paginated
- ? rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
- : rows;
- }
-
- if (!data || !data.cols || !data.rows) {
- return No data
;
- }
-
- /**
- * Helper function to calculate the range of displayed rows.
- * @returns {string}
- */
- const getRange = () => {
- let start = page * rowsPerPage + 1;
- let end = Math.min(page * rowsPerPage + rowsPerPage, data.rows.length);
- return `${start} - ${end}`;
- };
-
- return (
- <>
-
-
-
-
- {data.cols.map((col) => (
- {col.name}
- ))}
-
-
-
- {displayData.map((row) => {
- return (
-
- {row.data.map((cell) => {
- return {cell.data} ;
- })}
-
- );
- })}
- {displayData.length === 0 && (
-
-
- {emptyMessage}
-
-
- )}
-
-
-
- {paginated && (
-
-
- Showing {getRange()} of {data.rows.length} monitor(s)
-
-
- `Page ${page + 1} of ${Math.max(0, Math.ceil(count / rowsPerPage))}`
- }
- slotProps={{
- select: {
- MenuProps: {
- keepMounted: true,
- PaperProps: {
- className: "pagination-dropdown",
- sx: {
- mt: 0,
- mb: theme.spacing(2),
- },
- },
- transformOrigin: { vertical: "bottom", horizontal: "left" },
- anchorOrigin: { vertical: "top", horizontal: "left" },
- sx: { mt: theme.spacing(-2) },
- },
- inputProps: { id: "pagination-dropdown" },
- IconComponent: SelectorVertical,
- sx: {
- ml: theme.spacing(4),
- mr: theme.spacing(12),
- minWidth: theme.spacing(20),
- textAlign: "left",
- "&.Mui-focused > div": {
- backgroundColor: theme.palette.primary.main,
- },
- },
- },
- }}
- sx={{
- mt: theme.spacing(6),
- color: theme.palette.primary.contrastTextSecondary,
- "& svg path": {
- stroke: theme.palette.primary.contrastTextTertiary,
- strokeWidth: 1.3,
- },
- "& .MuiSelect-select": {
- border: 1,
- borderColor: theme.palette.primary.lowContrast,
- borderRadius: theme.shape.borderRadius,
- },
- }}
- />
-
- )}
- >
- );
-};
-
-BasicTable.propTypes = {
- data: PropTypes.object.isRequired,
- paginated: PropTypes.bool,
- reversed: PropTypes.bool,
- rowPerPage: PropTypes.number,
- table: PropTypes.string,
- emptyMessage: PropTypes.string,
-};
-
-export default BasicTable;
diff --git a/Client/src/Components/Fallback/index.jsx b/Client/src/Components/Fallback/index.jsx
deleted file mode 100644
index 61840452f..000000000
--- a/Client/src/Components/Fallback/index.jsx
+++ /dev/null
@@ -1,92 +0,0 @@
-import PropTypes from "prop-types";
-import { useTheme } from "@emotion/react";
-import { Box, Button, Stack, Typography } from "@mui/material";
-import Skeleton from "../../assets/Images/create-placeholder.svg?react";
-import SkeletonDark from "../../assets/Images/create-placeholder-dark.svg?react";
-import Background from "../../assets/Images/background-grid.svg?react";
-import Check from "../Check/Check";
-import { useNavigate } from "react-router-dom";
-import { useSelector } from "react-redux";
-import "./index.css";
-
-/**
- * Fallback component to display a fallback UI with a title, a list of checks, and a navigation button.
- *
- * @param {Object} props - The component props.
- * @param {string} props.title - The title to be displayed in the fallback UI.
- * @param {Array} props.checks - An array of strings representing the checks to display.
- * @param {string} [props.link="/"] - The link to navigate to.
- * @param {boolean} [props.vowelStart=false] - Whether the title starts with a vowel.
- * @returns {JSX.Element} The rendered fallback UI.
- */
-
-const Fallback = ({ title, checks, link = "/", isAdmin, vowelStart = false }) => {
- const theme = useTheme();
- const navigate = useNavigate();
- const mode = useSelector((state) => state.ui.mode);
-
- return (
-
- {mode === "light" ? (
-
- ) : (
-
- )}
-
-
-
-
-
- {vowelStart ? "An" : "A"} {title} is used to:
-
- {checks.map((check, index) => (
-
- ))}
-
- {/* TODO - display a different fallback if user is not an admin*/}
- {isAdmin && (
- navigate(link)}
- >
- Let's create your {title}
-
- )}
-
- );
-};
-
-Fallback.propTypes = {
- title: PropTypes.string.isRequired,
- checks: PropTypes.arrayOf(PropTypes.string).isRequired,
- link: PropTypes.string,
- isAdmin: PropTypes.bool,
- vowelStart: PropTypes.bool,
-};
-
-export default Fallback;
diff --git a/Client/src/Components/Inputs/Image/index.css b/Client/src/Components/Inputs/Image/index.css
deleted file mode 100644
index 7492f8636..000000000
--- a/Client/src/Components/Inputs/Image/index.css
+++ /dev/null
@@ -1,18 +0,0 @@
-.MuiStack-root:has(#modal-update-picture) h1.MuiTypography-root {
- font-weight: 600;
-}
-.image-field-wrapper h2.MuiTypography-root,
-.MuiStack-root:has(#modal-update-picture) button,
-.MuiStack-root:has(#modal-update-picture) h1.MuiTypography-root {
- font-size: var(--env-var-font-size-medium);
-}
-.image-field-wrapper h2.MuiTypography-root {
- margin-top: 10px;
-}
-.image-field-wrapper + p.MuiTypography-root {
- margin-top: 8px;
-}
-.image-field-wrapper + p.MuiTypography-root,
-.image-field-wrapper p.MuiTypography-root {
- font-size: var(--env-var-font-size-small-plus);
-}
diff --git a/Client/src/Components/Inputs/Image/index.jsx b/Client/src/Components/Inputs/Image/index.jsx
deleted file mode 100644
index a955a8ad6..000000000
--- a/Client/src/Components/Inputs/Image/index.jsx
+++ /dev/null
@@ -1,153 +0,0 @@
-import React, { useState } from "react";
-import PropTypes from "prop-types";
-import { Box, IconButton, Stack, TextField, Typography } from "@mui/material";
-import { useTheme } from "@emotion/react";
-import CloudUploadIcon from "@mui/icons-material/CloudUpload";
-import "./index.css";
-import { checkImage } from "../../../Utils/fileUtils";
-
-/**
- * @param {Object} props - The component props.
- * @param {string} props.id - The unique identifier for the input field.
- * @param {string} props.src - The URL of the image to display.
- * @param {function} props.onChange - The function to handle file input change.
- * @returns {JSX.Element} The rendered component.
- */
-
-const ImageField = ({ id, src, loading, onChange }) => {
- const theme = useTheme();
-
- const [isDragging, setIsDragging] = useState(false);
- const handleDragEnter = () => {
- setIsDragging(true);
- };
- const handleDragLeave = () => {
- setIsDragging(false);
- };
-
- return (
- <>
- {!checkImage(src) || loading ? (
- <>
-
-
-
-
-
-
-
-
- Click to upload
- {" "}
- or drag and drop
-
-
- (maximum size: 3MB)
-
-
-
-
- Supported formats: JPG, PNG
-
- >
- ) : (
-
-
-
- )}
- >
- );
-};
-
-ImageField.propTypes = {
- id: PropTypes.string.isRequired,
- src: PropTypes.string,
- onChange: PropTypes.func.isRequired,
-};
-
-export default ImageField;
diff --git a/Client/src/Pages/Account/index.jsx b/Client/src/Pages/Account/index.jsx
deleted file mode 100644
index 9fd38b5ef..000000000
--- a/Client/src/Pages/Account/index.jsx
+++ /dev/null
@@ -1,133 +0,0 @@
-import { useState } from "react";
-import PropTypes from "prop-types";
-import { useNavigate } from "react-router";
-import { useSelector } from "react-redux";
-import { Box, Tab, useTheme } from "@mui/material";
-import TabContext from "@mui/lab/TabContext";
-import TabList from "@mui/lab/TabList";
-import ProfilePanel from "../../Components/TabPanels/Account/ProfilePanel";
-import PasswordPanel from "../../Components/TabPanels/Account/PasswordPanel";
-import TeamPanel from "../../Components/TabPanels/Account/TeamPanel";
-import "./index.css";
-
-/**
- * Account component renders a settings page with tabs for Profile, Password, and Team settings.
- * @param {string} [props.open] - Specifies the initially open tab: 'profile', 'password', or 'team'.
- * @returns {JSX.Element}
- */
-const Account = ({ open = "profile" }) => {
- const theme = useTheme();
- const navigate = useNavigate();
- const [focusedTab, setFocusedTab] = useState(null); // Track focused tab
- const tab = open;
- const handleTabChange = (event, newTab) => {
- navigate(`/account/${newTab}`);
- };
- const { user } = useSelector((state) => state.auth);
-
- const requiredRoles = ["superadmin", "admin"];
- let tabList = ["Profile", "Password", "Team"];
- const hideTeams = !requiredRoles.some((role) => user.role.includes(role));
- if (hideTeams) {
- tabList = ["Profile", "Password"];
- }
-
- // Remove password for demo
- if (user.role.includes("demo")) {
- tabList = ["Profile"];
- }
-
- const handleKeyDown = (event) => {
- const currentIndex = tabList.findIndex((label) => label.toLowerCase() === tab);
- if (event.key === "Tab") {
- const nextIndex = (currentIndex + 1) % tabList.length;
- setFocusedTab(tabList[nextIndex].toLowerCase());
- } else if (event.key === "Enter") {
- event.preventDefault();
- navigate(`/account/${focusedTab}`);
- }
- };
-
- const handleFocus = (tabName) => {
- setFocusedTab(tabName);
- };
-
- return (
-
-
-
-
- {tabList.map((label, index) => (
- handleFocus(label.toLowerCase())}
- tabIndex={index}
- sx={{
- fontSize: 13,
- color: theme.palette.tertiary.contrastText,
- backgroundColor: theme.palette.tertiary.main,
- textTransform: "none",
- minWidth: "fit-content",
- paddingY: theme.spacing(6),
- fontWeight: 400,
- borderBottom: "2px solid transparent",
- borderRight: `1px solid ${theme.palette.primary.lowContrast}`,
- "&:first-child": { borderTopLeftRadius: "8px" },
- "&:last-child": { borderTopRightRadius: "8px", borderRight: 0 },
- "&:focus-visible": {
- color: theme.palette.primary.contrastText,
- borderColor: theme.palette.tertiary.contrastText,
- borderRightColor: theme.palette.primary.lowContrast,
- },
- "&.Mui-selected": {
- backgroundColor: theme.palette.secondary.main,
- color: theme.palette.secondary.contrastText,
- borderColor: theme.palette.secondary.contrastText,
- borderRightColor: theme.palette.primary.lowContrast,
- },
- "&:hover": {
- borderColor: theme.palette.primary.lowContrast,
- },
- }}
- />
- ))}
-
-
-
- {user.role.includes("superadmin") && }
- {!hideTeams && }
-
-
- );
-};
-
-Account.propTypes = {
- open: PropTypes.oneOf(["profile", "password", "team"]),
-};
-
-export default Account;
diff --git a/Client/src/Pages/Incidents/IncidentTable/Empty/Empty.jsx b/Client/src/Pages/Incidents/IncidentTable/Empty/Empty.jsx
deleted file mode 100644
index 78b7e8d6d..000000000
--- a/Client/src/Pages/Incidents/IncidentTable/Empty/Empty.jsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import { useTheme } from "@emotion/react";
-import PlaceholderLight from "../../../../assets/Images/data_placeholder.svg?react";
-import PlaceholderDark from "../../../../assets/Images/data_placeholder_dark.svg?react";
-import { Box, Typography } from "@mui/material";
-import PropTypes from "prop-types";
-
-const Empty = ({ styles, mode }) => {
- const theme = useTheme();
- return (
-
-
- {mode === "light" ? : }
-
-
- No incidents recorded yet.
-
-
- );
-};
-
-Empty.propTypes = {
- styles: PropTypes.object,
- mode: PropTypes.string,
-};
-
-export { Empty };
diff --git a/Client/src/Pages/Incidents/IncidentTable/Skeleton/Skeleton.jsx b/Client/src/Pages/Incidents/IncidentTable/Skeleton/Skeleton.jsx
deleted file mode 100644
index a3a23c14c..000000000
--- a/Client/src/Pages/Incidents/IncidentTable/Skeleton/Skeleton.jsx
+++ /dev/null
@@ -1,21 +0,0 @@
-import { Skeleton /* , Stack */ } from "@mui/material";
-const IncidentSkeleton = () => {
- return (
- <>
-
-
- >
- );
-};
-
-export { IncidentSkeleton };
diff --git a/Client/src/Pages/Incidents/IncidentTable/index.jsx b/Client/src/Pages/Incidents/IncidentTable/index.jsx
deleted file mode 100644
index ae9a3ae2a..000000000
--- a/Client/src/Pages/Incidents/IncidentTable/index.jsx
+++ /dev/null
@@ -1,185 +0,0 @@
-import PropTypes from "prop-types";
-import { Typography, Box } from "@mui/material";
-
-import { useState, useEffect } from "react";
-import { useSelector } from "react-redux";
-import { networkService } from "../../../main";
-import { StatusLabel } from "../../../Components/Label";
-import { logger } from "../../../Utils/Logger";
-import { useTheme } from "@emotion/react";
-import { formatDateWithTz } from "../../../Utils/timeUtils";
-import PlaceholderLight from "../../../assets/Images/data_placeholder.svg?react";
-import PlaceholderDark from "../../../assets/Images/data_placeholder_dark.svg?react";
-import { HttpStatusLabel } from "../../../Components/HttpStatusLabel";
-import { Empty } from "./Empty/Empty";
-import { IncidentSkeleton } from "./Skeleton/Skeleton";
-import DataTable from "../../../Components/Table";
-import Pagination from "../../../Components/Table/TablePagination";
-
-const IncidentTable = ({ monitors, selectedMonitor, filter, dateRange }) => {
- const uiTimezone = useSelector((state) => state.ui.timezone);
-
- const theme = useTheme();
- const { authToken, user } = useSelector((state) => state.auth);
- const mode = useSelector((state) => state.ui.mode);
- const [checks, setChecks] = useState([]);
- const [checksCount, setChecksCount] = useState(0);
- const [page, setPage] = useState(0);
- const [rowsPerPage, setRowsPerPage] = useState(10);
- const [isLoading, setIsLoading] = useState(false);
-
- useEffect(() => {
- const fetchPage = async () => {
- if (!monitors || Object.keys(monitors).length === 0) {
- return;
- }
- try {
- setIsLoading(true);
- let res;
- if (selectedMonitor === "0") {
- res = await networkService.getChecksByTeam({
- authToken: authToken,
- teamId: user.teamId,
- sortOrder: "desc",
- limit: null,
- dateRange,
- filter: filter,
- page: page,
- rowsPerPage: rowsPerPage,
- });
- } else {
- res = await networkService.getChecksByMonitor({
- authToken: authToken,
- monitorId: selectedMonitor,
- sortOrder: "desc",
- limit: null,
- dateRange,
- filter: filter,
- page,
- rowsPerPage,
- });
- }
-
- setChecks(res.data.data.checks);
- setChecksCount(res.data.data.checksCount);
- } catch (error) {
- logger.error(error);
- } finally {
- setIsLoading(false);
- }
- };
- fetchPage();
- }, [authToken, user, monitors, selectedMonitor, filter, page, rowsPerPage, dateRange]);
-
- const handlePageChange = (_, newPage) => {
- setPage(newPage);
- };
-
- const handleChangeRowsPerPage = (event) => {
- setRowsPerPage(event.target.value);
- };
-
- const headers = [
- {
- id: "monitorName",
- content: "Monitor Name",
- render: (row) => monitors[row.monitorId]?.name ?? "N/A",
- },
- {
- id: "status",
- content: "Status",
- render: (row) => {
- const status = row.status === true ? "up" : "down";
- return (
-
- );
- },
- },
- {
- id: "dateTime",
- content: "Date & Time",
- render: (row) => {
- const formattedDate = formatDateWithTz(
- row.createdAt,
- "YYYY-MM-DD HH:mm:ss A",
- uiTimezone
- );
- return formattedDate;
- },
- },
- {
- id: "statusCode",
- content: "Status Code",
- render: (row) => ,
- },
- { id: "message", content: "Message", render: (row) => row.message },
- ];
-
- let sharedStyles = {
- border: 1,
- borderColor: theme.palette.primary.lowContrast,
- borderRadius: theme.shape.borderRadius,
- backgroundColor: theme.palette.primary.main,
- p: theme.spacing(30),
- };
-
- const hasChecks = checks?.length === 0;
- const noIncidentsRecordedYet = hasChecks && selectedMonitor === "0";
- const noIncidentsForThatMonitor = hasChecks && selectedMonitor !== "0";
-
- return (
- <>
- {isLoading ? (
-
- ) : noIncidentsRecordedYet ? (
-
- ) : noIncidentsForThatMonitor ? (
-
-
- {mode === "light" ? : }
-
-
- The monitor you have selected has no recorded incidents yet.
-
-
- ) : (
- <>
-
-
- >
- )}
- >
- );
-};
-
-IncidentTable.propTypes = {
- monitors: PropTypes.object.isRequired,
- selectedMonitor: PropTypes.string.isRequired,
- filter: PropTypes.string.isRequired,
- dateRange: PropTypes.string.isRequired,
-};
-
-export default IncidentTable;
diff --git a/Client/src/Pages/Incidents/index.jsx b/Client/src/Pages/Incidents/index.jsx
deleted file mode 100644
index 8305ec672..000000000
--- a/Client/src/Pages/Incidents/index.jsx
+++ /dev/null
@@ -1,213 +0,0 @@
-import { useState, useEffect } from "react";
-import { useSelector } from "react-redux";
-import { ButtonGroup, Stack, Typography, Button } from "@mui/material";
-import { useParams } from "react-router-dom";
-
-import { networkService } from "../../main";
-import { useTheme } from "@emotion/react";
-import Select from "../../Components/Inputs/Select";
-import IncidentTable from "./IncidentTable";
-import SkeletonLayout from "./skeleton";
-
-const Incidents = () => {
- const theme = useTheme();
- const authState = useSelector((state) => state.auth);
- const { monitorId } = useParams();
-
- const [monitors, setMonitors] = useState({});
- const [selectedMonitor, setSelectedMonitor] = useState("0");
- const [isLoading, setIsLoading] = useState(true);
-
- // TODO do something with these filters
- const [filter, setFilter] = useState("all");
- const [dateRange, setDateRange] = useState("hour");
-
- useEffect(() => {
- const fetchMonitors = async () => {
- try {
- setIsLoading(true);
- const res = await networkService.getMonitorsByTeamId({
- authToken: authState.authToken,
- teamId: authState.user.teamId,
- limit: null,
- types: null,
- status: null,
- checkOrder: null,
- normalize: null,
- page: null,
- rowsPerPage: null,
- filter: null,
- field: null,
- order: null,
- });
- if (res?.data?.data?.monitors?.length > 0) {
- const monitorLookup = res.data.data.monitors.reduce((acc, monitor) => {
- acc[monitor._id] = monitor;
- return acc;
- }, {});
- setMonitors(monitorLookup);
- monitorId !== undefined && setSelectedMonitor(monitorId);
- }
- } catch (error) {
- console.info(error);
- } finally {
- setIsLoading(false);
- }
- };
- fetchMonitors();
- }, [authState, monitorId]);
-
- useEffect(() => {}, [monitors]);
-
- const handleSelect = (event) => {
- setSelectedMonitor(event.target.value);
- };
-
- const isActuallyLoading = isLoading && Object.keys(monitors)?.length === 0;
-
- return (
-
- {isActuallyLoading ? (
-
- ) : (
- <>
-
-
-
- Incidents for
-
-
-
-
-
- Filter by:
-
-
- setFilter("all")}
- >
- All
-
- setFilter("down")}
- >
- Down
-
- setFilter("resolve")}
- >
- Cannot resolve
-
-
-
-
-
- Show:
-
-
- setDateRange("hour")}
- >
- Last hour
-
- setDateRange("day")}
- >
- Last day
-
- setDateRange("week")}
- >
- Last week
-
- setDateRange("all")}
- >
- All
-
-
-
-
-
- >
- )}
-
- );
-};
-
-export default Incidents;
diff --git a/Client/src/Pages/Incidents/skeleton.jsx b/Client/src/Pages/Incidents/skeleton.jsx
deleted file mode 100644
index 51848a108..000000000
--- a/Client/src/Pages/Incidents/skeleton.jsx
+++ /dev/null
@@ -1,50 +0,0 @@
-import { Stack, Skeleton } from "@mui/material";
-import { useTheme } from "@emotion/react";
-
-/**
- * Renders a skeleton layout.
- *
- * @returns {JSX.Element}
- */
-const SkeletonLayout = () => {
- const theme = useTheme();
-
- return (
- <>
-
-
-
-
-
-
-
- >
- );
-};
-
-export default SkeletonLayout;
diff --git a/Client/src/Pages/Infrastructure/Details/empty.jsx b/Client/src/Pages/Infrastructure/Details/empty.jsx
deleted file mode 100644
index ee3cdb4df..000000000
--- a/Client/src/Pages/Infrastructure/Details/empty.jsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { useTheme } from "@emotion/react";
-import PlaceholderLight from "../../../assets/Images/data_placeholder.svg?react";
-import PlaceholderDark from "../../../assets/Images/data_placeholder_dark.svg?react";
-import { Box, Typography, Stack } from "@mui/material";
-import PropTypes from "prop-types";
-import { useSelector } from "react-redux";
-const Empty = ({ styles }) => {
- const theme = useTheme();
- const mode = useSelector((state) => state.ui.mode);
- return (
-
-
- {mode === "light" ? : }
-
- Your infrastructure dashboard will show here
-
- Hang tight! Data is loading
-
-
-
- );
-};
-
-Empty.propTypes = {
- styles: PropTypes.object,
- mode: PropTypes.string,
-};
-
-export default Empty;
diff --git a/Client/src/Pages/Infrastructure/Details/index.jsx b/Client/src/Pages/Infrastructure/Details/index.jsx
deleted file mode 100644
index acd1bafb1..000000000
--- a/Client/src/Pages/Infrastructure/Details/index.jsx
+++ /dev/null
@@ -1,682 +0,0 @@
-import { useParams } from "react-router-dom";
-import { useEffect, useState } from "react";
-import Breadcrumbs from "../../../Components/Breadcrumbs";
-import { Button, ButtonGroup, Stack, Box, Typography } from "@mui/material";
-import { useTheme } from "@emotion/react";
-import CustomGauge from "../../../Components/Charts/CustomGauge";
-import AreaChart from "../../../Components/Charts/AreaChart";
-import { useSelector } from "react-redux";
-import { networkService } from "../../../main";
-import PulseDot from "../../../Components/Animated/PulseDot";
-import useUtils from "../../Uptime/utils";
-import { useNavigate } from "react-router-dom";
-import Empty from "./empty";
-import { logger } from "../../../Utils/Logger";
-import { formatDurationRounded, formatDurationSplit } from "../../../Utils/timeUtils";
-import { TzTick, PercentTick } from "../../../Components/Charts/Utils/chartUtils";
-import {
- InfrastructureTooltip,
- TemperatureTooltip,
-} from "../../../Components/Charts/Utils/chartUtils";
-import PropTypes from "prop-types";
-import StatBox from "../../../Components/StatBox";
-
-const BASE_BOX_PADDING_VERTICAL = 4;
-const BASE_BOX_PADDING_HORIZONTAL = 8;
-const TYPOGRAPHY_PADDING = 8;
-/**
- * Converts bytes to gigabytes
- * @param {number} bytes - Number of bytes to convert
- * @returns {number} Converted value in gigabytes
- */
-const formatBytes = (bytes, space = false) => {
- if (bytes === undefined || bytes === null)
- return (
- <>
- {0}
- {space ? " " : ""}
- GB
- >
- );
- if (typeof bytes !== "number")
- return (
- <>
- {0}
- {space ? " " : ""}
- GB
- >
- );
- if (bytes === 0)
- return (
- <>
- {0}
- {space ? " " : ""}
- GB
- >
- );
-
- const GB = bytes / (1024 * 1024 * 1024);
- const MB = bytes / (1024 * 1024);
-
- if (GB >= 1) {
- return (
- <>
- {Number(GB.toFixed(0))}
- {space ? " " : ""}
- GB
- >
- );
- } else {
- return (
- <>
- {Number(MB.toFixed(0))}
- MB
- >
- );
- }
-};
-
-/**
- * Converts a decimal value to a percentage
- *
- * @function decimalToPercentage
- * @param {number} value - Decimal value to convert
- * @returns {number} Percentage representation
- *
- * @example
- * decimalToPercentage(0.75) // Returns 75
- * decimalToPercentage(null) // Returns 0
- */
-const decimalToPercentage = (value) => {
- if (value === null || value === undefined) return 0;
- return value * 100;
-};
-
-/**
- * Renders a base box with consistent styling
- * @param {Object} props - Component properties
- * @param {React.ReactNode} props.children - Child components to render inside the box
- * @param {Object} props.sx - Additional styling for the box
- * @returns {React.ReactElement} Styled box component
- */
-const BaseBox = ({ children, sx = {} }) => {
- const theme = useTheme();
- return (
-
- {children}
-
- );
-};
-
-BaseBox.propTypes = {
- children: PropTypes.node.isRequired,
- sx: PropTypes.object,
-};
-
-/**
- * Renders a gauge box with usage visualization
- * @param {Object} props - Component properties
- * @param {number} props.value - Percentage value for gauge
- * @param {string} props.heading - Box heading
- * @param {string} props.metricOne - First metric label
- * @param {string} props.valueOne - First metric value
- * @param {string} props.metricTwo - Second metric label
- * @param {string} props.valueTwo - Second metric value
- * @returns {React.ReactElement} Gauge box component
- */
-const GaugeBox = ({ value, heading, metricOne, valueOne, metricTwo, valueTwo }) => {
- const theme = useTheme();
-
- return (
-
-
-
- {heading}
-
-
- {metricOne}
- {valueOne}
-
-
- {metricTwo}
- {valueTwo}
-
-
-
-
- );
-};
-
-GaugeBox.propTypes = {
- value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
- heading: PropTypes.string.isRequired,
- metricOne: PropTypes.string.isRequired,
- valueOne: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.element])
- .isRequired,
- metricTwo: PropTypes.string.isRequired,
- valueTwo: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.element])
- .isRequired,
-};
-
-/**
- * Renders the infrastructure details page
- * @returns {React.ReactElement} Infrastructure details page component
- */
-const InfrastructureDetails = () => {
- const navigate = useNavigate();
- const theme = useTheme();
- const { monitorId } = useParams();
- const navList = [
- { name: "infrastructure monitors", path: "/infrastructure" },
- { name: "details", path: `/infrastructure/${monitorId}` },
- ];
- const [monitor, setMonitor] = useState(null);
- const { authToken } = useSelector((state) => state.auth);
- const [dateRange, setDateRange] = useState("day");
- const { statusColor, statusStyles, determineState } = useUtils();
- // These calculations are needed because ResponsiveContainer
- // doesn't take padding of parent/siblings into account
- // when calculating height.
- const chartContainerHeight = 300;
- const totalChartContainerPadding =
- parseInt(theme.spacing(BASE_BOX_PADDING_VERTICAL), 10) * 2;
- const totalTypographyPadding = parseInt(theme.spacing(TYPOGRAPHY_PADDING), 10) * 2;
- const areaChartHeight =
- (chartContainerHeight - totalChartContainerPadding - totalTypographyPadding) * 0.95;
- // end height calculations
-
- const buildStatBoxes = (stats, uptime) => {
- if (Object.keys(stats).length === 0) return [];
- let latestCheck = stats?.aggregateData?.latestCheck ?? null;
- if (latestCheck === null) return [];
-
- // Extract values from latest check
- const physicalCores = latestCheck?.cpu?.physical_core ?? 0;
- const logicalCores = latestCheck?.cpu?.logical_core ?? 0;
- const cpuFrequency = latestCheck?.cpu?.frequency ?? 0;
- const cpuTemperature =
- latestCheck?.cpu?.temperature?.length > 0
- ? latestCheck.cpu.temperature.reduce((acc, curr) => acc + curr, 0) /
- latestCheck.cpu.temperature.length
- : 0;
- const memoryTotalBytes = latestCheck?.memory?.total_bytes ?? 0;
- const diskTotalBytes = latestCheck?.disk[0]?.total_bytes ?? 0;
- const os = latestCheck?.host?.os ?? null;
- const platform = latestCheck?.host?.platform ?? null;
- const osPlatform = os === null && platform === null ? null : `${os} ${platform}`;
- return [
- {
- id: 7,
- sx: statusStyles[determineState(monitor)],
- heading: "Status",
- subHeading: monitor?.status === true ? "Active" : "Inactive",
- },
- {
- id: 0,
- heading: "CPU (Physical)",
- subHeading: (
- <>
- {physicalCores}
- cores
- >
- ),
- },
- {
- id: 1,
- heading: "CPU (Logical)",
- subHeading: (
- <>
- {logicalCores}
- cores
- >
- ),
- },
- {
- id: 2,
- heading: "CPU Frequency",
- subHeading: (
- <>
- {(cpuFrequency / 1000).toFixed(2)}
- Ghz
- >
- ),
- },
- {
- id: 3,
- heading: "Average CPU Temperature",
- subHeading: (
- <>
- {cpuTemperature.toFixed(2)}
- C
- >
- ),
- },
- {
- id: 4,
- heading: "Memory",
- subHeading: formatBytes(memoryTotalBytes),
- },
- {
- id: 5,
- heading: "Disk",
- subHeading: formatBytes(diskTotalBytes),
- },
- {
- id: 6,
- heading: "Uptime",
- subHeading: (
- <>
- {(uptime * 100).toFixed(2)}
- %
- >
- ),
- },
-
- {
- id: 8,
- heading: "OS",
- subHeading: osPlatform,
- },
- ];
- };
-
- const buildGaugeBoxConfigs = (stats) => {
- if (Object.keys(stats).length === 0) return [];
-
- let latestCheck = stats?.aggregateData?.latestCheck ?? null;
- if (latestCheck === null) return [];
-
- // Extract values from latest check
- const memoryUsagePercent = latestCheck?.memory?.usage_percent ?? 0;
- const memoryUsedBytes = latestCheck?.memory?.used_bytes ?? 0;
- const memoryTotalBytes = latestCheck?.memory?.total_bytes ?? 0;
- const cpuUsagePercent = latestCheck?.cpu?.usage_percent ?? 0;
- const cpuPhysicalCores = latestCheck?.cpu?.physical_core ?? 0;
- const cpuFrequency = latestCheck?.cpu?.frequency ?? 0;
- return [
- {
- type: "memory",
- value: decimalToPercentage(memoryUsagePercent),
- heading: "Memory usage",
- metricOne: "Used",
- valueOne: formatBytes(memoryUsedBytes, true),
- metricTwo: "Total",
- valueTwo: formatBytes(memoryTotalBytes, true),
- },
- {
- type: "cpu",
- value: decimalToPercentage(cpuUsagePercent),
- heading: "CPU usage",
- metricOne: "Cores",
- valueOne: cpuPhysicalCores ?? 0,
- metricTwo: "Frequency",
- valueTwo: `${(cpuFrequency / 1000).toFixed(2)} Ghz`,
- },
- ...(latestCheck?.disk ?? []).map((disk, idx) => ({
- type: "disk",
- diskIndex: idx,
- value: decimalToPercentage(disk.usage_percent),
- heading: `Disk${idx} usage`,
- metricOne: "Used",
- valueOne: formatBytes(disk.total_bytes - disk.free_bytes, true),
- metricTwo: "Total",
- valueTwo: formatBytes(disk.total_bytes, true),
- })),
- ];
- };
-
- const buildTemps = (checks) => {
- let numCores = 1;
- if (checks === null) return { temps: [], tempKeys: [] };
-
- for (const check of checks) {
- if (check?.avgTemperature?.length > numCores) {
- numCores = check.avgTemperature.length;
- break;
- }
- }
- const temps = checks.map((check) => {
- // If there's no data, set the temperature to 0
- if (
- check?.avgTemperature?.length === 0 ||
- check?.avgTemperature === undefined ||
- check?.avgTemperature === null
- ) {
- check.avgTemperature = Array(numCores).fill(0);
- }
- const res = check?.avgTemperature?.reduce(
- (acc, cur, idx) => {
- acc[`core${idx + 1}`] = cur;
- return acc;
- },
- {
- _id: check._id,
- }
- );
- return res;
- });
- if (temps.length === 0 || !temps[0]) {
- return { temps: [], tempKeys: [] };
- }
-
- return {
- tempKeys: Object.keys(temps[0] || {}).filter((key) => key !== "_id"),
- temps,
- };
- };
-
- const buildAreaChartConfigs = (checks) => {
- let latestCheck = checks[0] ?? null;
- if (latestCheck === null) return [];
- const { temps, tempKeys } = buildTemps(checks);
- return [
- {
- type: "memory",
- data: checks,
- dataKeys: ["avgMemoryUsage"],
- heading: "Memory usage",
- strokeColor: theme.palette.accent.main, // CAIO_REVIEW
- gradientStartColor: theme.palette.accent.main, // CAIO_REVIEW
- yLabel: "Memory usage",
- yDomain: [0, 1],
- yTick: ,
- xTick: ,
- toolTip: (
-
- ),
- },
- {
- type: "cpu",
- data: checks,
- dataKeys: ["avgCpuUsage"],
- heading: "CPU usage",
- strokeColor: theme.palette.success.main,
- gradientStartColor: theme.palette.success.main,
- yLabel: "CPU usage",
- yDomain: [0, 1],
- yTick: ,
- xTick: ,
- toolTip: (
-
- ),
- },
- {
- type: "temperature",
- data: temps,
- dataKeys: tempKeys,
- strokeColor: theme.palette.error.main,
- gradientStartColor: theme.palette.error.main,
- heading: "CPU Temperature",
- yLabel: "Temperature",
- xTick: ,
- yDomain: [
- 0,
- Math.max(
- Math.max(...temps.flatMap((t) => tempKeys.map((k) => t[k]))) * 1.1,
- 200
- ),
- ],
- toolTip: (
-
- ),
- },
- ...(latestCheck?.disks?.map((disk, idx) => ({
- type: "disk",
- data: checks,
- diskIndex: idx,
- dataKeys: [`disks[${idx}].usagePercent`],
- heading: `Disk${idx} usage`,
- strokeColor: theme.palette.warning.main,
- gradientStartColor: theme.palette.warning.main,
- yLabel: "Disk Usage",
- yDomain: [0, 1],
- yTick: ,
- xTick: ,
- toolTip: (
-
- ),
- })) || []),
- ];
- };
-
- // Fetch data
- useEffect(() => {
- const fetchData = async () => {
- try {
- const response = await networkService.getHardwareDetailsByMonitorId({
- authToken: authToken,
- monitorId: monitorId,
- dateRange: dateRange,
- });
- response.data.data;
- setMonitor(response.data.data);
- } catch (error) {
- navigate("/not-found", { replace: true });
- logger.error(error);
- }
- };
- fetchData();
- }, [authToken, monitorId, dateRange, navigate]);
-
- const statBoxConfigs = buildStatBoxes(
- monitor?.stats ?? {},
- monitor?.uptimePercentage ?? "Unknown"
- );
- const gaugeBoxConfigs = buildGaugeBoxConfigs(monitor?.stats ?? {});
- const areaChartConfigs = buildAreaChartConfigs(monitor?.stats?.checks ?? []);
- const lastChecked =
- Date.now() - new Date(monitor?.stats?.aggregateData?.latestCheck?.createdAt);
- return (
-
-
- {monitor?.stats.checks?.length > 0 ? (
-
-
-
-
-
-
- {monitor.name}
-
- {monitor.url || "..."}
-
-
- Checking every {formatDurationRounded(monitor?.interval)}
-
-
- Last checked {formatDurationSplit(lastChecked).time}{" "}
- {formatDurationSplit(lastChecked).format} ago
-
-
-
-
- {statBoxConfigs.map((statBox) => (
-
- ))}
-
-
-
- {gaugeBoxConfigs.map((config) => {
- return (
-
- );
- })}
-
-
-
- Showing statistics for past{" "}
- {dateRange === "day"
- ? "24 hours"
- : dateRange === "week"
- ? "7 days"
- : "30 days"}
- .
-
-
- setDateRange("day")}
- >
- Day
-
- setDateRange("week")}
- >
- Week
-
- setDateRange("month")}
- >
- Month
-
-
-
- *": {
- flexBasis: `calc(50% - ${theme.spacing(8)})`,
- maxWidth: `calc(50% - ${theme.spacing(8)})`,
- },
- }}
- >
- {areaChartConfigs.map((config) => {
- return (
-
-
- {config.heading}
-
-
-
- );
- })}
-
-
- ) : (
-
- )}
-
- );
-};
-
-export default InfrastructureDetails;
diff --git a/Client/src/Pages/Infrastructure/index.jsx b/Client/src/Pages/Infrastructure/index.jsx
deleted file mode 100644
index fbfae6a3c..000000000
--- a/Client/src/Pages/Infrastructure/index.jsx
+++ /dev/null
@@ -1,298 +0,0 @@
-import { useEffect, useState, useCallback } from "react";
-import { useNavigate } from "react-router-dom";
-import { /* useDispatch, */ useSelector } from "react-redux";
-import { useTheme } from "@emotion/react";
-import useUtils from "../Uptime/utils.jsx";
-import { jwtDecode } from "jwt-decode";
-import SkeletonLayout from "./skeleton";
-import Fallback from "../../Components/Fallback";
-// import GearIcon from "../../Assets/icons/settings-bold.svg?react";
-import CPUChipIcon from "../../assets/icons/cpu-chip.svg?react";
-import DataTable from "../../Components/Table";
-import { Box, Button, IconButton, Stack } from "@mui/material";
-import Breadcrumbs from "../../Components/Breadcrumbs";
-import { StatusLabel } from "../../Components/Label";
-import { Heading } from "../../Components/Heading";
-import Pagination from "../../Components/Table/TablePagination/index.jsx";
-// import { getInfrastructureMonitorsByTeamId } from "../../Features/InfrastructureMonitors/infrastructureMonitorsSlice";
-import { networkService } from "../../Utils/NetworkService.js";
-import CustomGauge from "../../Components/Charts/CustomGauge/index.jsx";
-import Host from "../Uptime/Home/host.jsx";
-import { useIsAdmin } from "../../Hooks/useIsAdmin.js";
-import { InfrastructureMenu } from "./components/Menu";
-
-const BREADCRUMBS = [{ name: `infrastructure`, path: "/infrastructure" }];
-
-/**
- * This is the Infrastructure monitoring page. This is a work in progress
- *
- * @param - Define params.
- * @returns {JSX.Element} The infrastructure monitoring page.
- */
-
-function Infrastructure() {
- /* Adding this custom hook so we can avoid using the HOC approach that can lower performance (we are calling the admin logic N times on initializing the project. using a custom hook will cal it ass needed ) */
- const isAdmin = useIsAdmin();
- const theme = useTheme();
- const [isLoading, setIsLoading] = useState(true);
-
- const navigate = useNavigate();
- const navigateToCreate = () => navigate("/infrastructure/create");
-
- const [page, setPage] = useState(0);
- /* TODO refactor this, so it is not aware of the MUI implementation. First argument only exists because of MUI. This should require onlu the new page. Adapting for MUI should happen inside of table pagination component */
- const handleChangePage = (_, newPage) => {
- setPage(newPage);
- };
-
- const [rowsPerPage, setRowsPerPage] = useState(5);
- const handleChangeRowsPerPage = (event) => {
- setRowsPerPage(parseInt(event.target.value));
- setPage(0);
- };
- const [monitors, setMonitors] = useState([]);
- const [summary, setSummary] = useState({});
-
- const { authToken } = useSelector((state) => state.auth);
- const user = jwtDecode(authToken);
-
- const fetchMonitors = useCallback(async () => {
- try {
- setIsLoading(true);
- const response = await networkService.getMonitorsByTeamId({
- authToken,
- teamId: user.teamId,
- limit: 1,
- types: ["hardware"],
- page: page,
- rowsPerPage: rowsPerPage,
- });
- setMonitors(response?.data?.data?.filteredMonitors ?? []);
- setSummary(response?.data?.data?.summary ?? {});
- } catch (error) {
- console.error(error);
- } finally {
- setIsLoading(false);
- }
- }, [page, rowsPerPage, authToken, user.teamId]);
-
- useEffect(() => {
- fetchMonitors();
- }, [fetchMonitors]);
-
- const { determineState } = useUtils();
- // do it here
- function openDetails(id) {
- navigate(`/infrastructure/${id}`);
- }
- function handleActionMenuDelete() {
- fetchMonitors();
- }
-
- const headers = [
- {
- id: "host",
- content: "Host",
- render: (row) => (
-
- ),
- },
- {
- id: "status",
- content: "Status",
- render: (row) => (
-
- ),
- },
- {
- id: "frequency",
- content: "Frequency",
- render: (row) => (
-
-
- {row.processor}
-
- ),
- },
- { id: "cpu", content: "CPU", render: (row) => },
- { id: "mem", content: "Mem", render: (row) => },
- { id: "disk", content: "Disk", render: (row) => },
- {
- id: "actions",
- content: "Actions",
- render: (row) => (
-
-
-
- ),
- },
- ];
-
- const monitorsAsRows = monitors.map((monitor) => {
- const processor =
- ((monitor.checks[0]?.cpu?.frequency ?? 0) / 1000).toFixed(2) + " GHz";
- const cpu = (monitor?.checks[0]?.cpu.usage_percent ?? 0) * 100;
- const mem = (monitor?.checks[0]?.memory.usage_percent ?? 0) * 100;
- const disk = (monitor?.checks[0]?.disk[0]?.usage_percent ?? 0) * 100;
- const status = determineState(monitor);
- const uptimePercentage = ((monitor?.uptimePercentage ?? 0) * 100)
- .toFixed(2)
- .toString();
- const percentageColor =
- monitor.uptimePercentage < 0.25
- ? theme.palette.error.main
- : monitor.uptimePercentage < 0.5
- ? theme.palette.percentage.uptimeFair
- : monitor.uptimePercentage < 0.75
- ? theme.palette.percentage.uptimeGood
- : theme.palette.success.lowContrast;
- return {
- id: monitor._id,
- name: monitor.name,
- url: monitor.url,
- processor,
- cpu,
- mem,
- disk,
- status,
- uptimePercentage,
- percentageColor,
- };
- });
-
- let isActuallyLoading = isLoading && monitors?.length === 0;
- return (
- [class*="fallback__"])': {
- position: "relative",
- border: 1,
- borderColor: theme.palette.primary.lowContrast,
- borderRadius: theme.shape.borderRadius,
- borderStyle: "dashed",
- backgroundColor: theme.palette.primary.main,
- overflow: "hidden",
- },
- }}
- >
- {isActuallyLoading ? (
-
- ) : monitors?.length !== 0 ? (
-
-
-
-
- {isAdmin && (
-
- Create new
-
- )}
-
-
-
-
- Infrastructure monitors
- {/* TODO Same as the one in UptimaDataTable. Create component */}
-
- {summary?.totalMonitors ?? 0}
-
-
-
- openDetails(row.id),
- }}
- headers={headers}
- data={monitorsAsRows}
- />
-
-
-
-
- ) : (
-
- )}
-
- );
-}
-
-export { Infrastructure };
diff --git a/Client/src/Pages/Infrastructure/skeleton.jsx b/Client/src/Pages/Infrastructure/skeleton.jsx
deleted file mode 100644
index b6d29dc38..000000000
--- a/Client/src/Pages/Infrastructure/skeleton.jsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import { Box, Skeleton, Stack } from "@mui/material";
-import { useTheme } from "@emotion/react";
-
-/**
- * Renders a skeleton layout.
- *
- * @returns {JSX.Element}
- */
-const SkeletonLayout = () => {
- const theme = useTheme();
-
- return (
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- );
-};
-
-export default SkeletonLayout;
diff --git a/Client/src/Pages/Maintenance/index.jsx b/Client/src/Pages/Maintenance/index.jsx
deleted file mode 100644
index f077f25b6..000000000
--- a/Client/src/Pages/Maintenance/index.jsx
+++ /dev/null
@@ -1,110 +0,0 @@
-import { Box, Stack, Button } from "@mui/material";
-import { useTheme } from "@emotion/react";
-import Fallback from "../../Components/Fallback";
-import { useState, useEffect } from "react";
-import "./index.css";
-import MaintenanceTable from "./MaintenanceTable";
-import { useSelector } from "react-redux";
-import { networkService } from "../../main";
-import Breadcrumbs from "../../Components/Breadcrumbs";
-import { useNavigate } from "react-router-dom";
-import { useIsAdmin } from "../../Hooks/useIsAdmin";
-
-const Maintenance = () => {
- const theme = useTheme();
- const navigate = useNavigate();
- const { authToken } = useSelector((state) => state.auth);
- const { rowsPerPage } = useSelector((state) => state.ui.maintenance);
- const isAdmin = useIsAdmin();
- const [maintenanceWindows, setMaintenanceWindows] = useState([]);
- const [maintenanceWindowCount, setMaintenanceWindowCount] = useState(0);
- const [page, setPage] = useState(0);
- const [sort, setSort] = useState({});
- const [updateTrigger, setUpdateTrigger] = useState(false);
-
- const handleActionMenuDelete = () => {
- setUpdateTrigger((prev) => !prev);
- };
-
- useEffect(() => {
- const fetchMaintenanceWindows = async () => {
- try {
- const response = await networkService.getMaintenanceWindowsByTeamId({
- authToken: authToken,
- page: page,
- rowsPerPage: rowsPerPage,
- });
- const { maintenanceWindows, maintenanceWindowCount } = response.data.data;
- setMaintenanceWindows(maintenanceWindows);
- setMaintenanceWindowCount(maintenanceWindowCount);
- } catch (error) {
- console.log(error);
- }
- };
- fetchMaintenanceWindows();
- }, [authToken, page, rowsPerPage, updateTrigger]);
-
- return (
- [class*="fallback__"])': {
- position: "relative",
- border: 1,
- borderColor: theme.palette.primary.lowContrast,
- borderRadius: theme.shape.borderRadius,
- borderStyle: "dashed",
- backgroundColor: theme.palette.primary.main,
- overflow: "hidden",
- },
- }}
- >
- {maintenanceWindows.length > 0 && (
-
-
-
- {
- navigate("/maintenance/create");
- }}
- sx={{ fontWeight: 500 }}
- >
- Create maintenance window
-
-
-
-
- )}
- {maintenanceWindows.length === 0 && (
-
- )}
-
- );
-};
-
-export default Maintenance;
diff --git a/Client/src/Pages/PageSpeed/Details/index.css b/Client/src/Pages/PageSpeed/Details/index.css
deleted file mode 100644
index 0d0699b3d..000000000
--- a/Client/src/Pages/PageSpeed/Details/index.css
+++ /dev/null
@@ -1,18 +0,0 @@
-.page-speed-details button.MuiButtonBase-root {
- min-height: 34px;
-}
-
-.page-speed-details .MuiPieArcLabel-root {
- font-size: var(--env-var-font-size-small-plus);
- transition: fill 300ms ease;
-}
-.page-speed-details .MuiPieArcLabel-faded {
- fill: rgba(0, 0, 0, 0.3);
-}
-.page-speed-details .pie-label,
-.page-speed-details .pie-value-label {
- transition: all 400ms ease;
-}
-.page-speed-details .MuiPieArc-root {
- stroke: inherit;
-}
diff --git a/Client/src/Pages/PageSpeed/Details/index.jsx b/Client/src/Pages/PageSpeed/Details/index.jsx
deleted file mode 100644
index c5badbab8..000000000
--- a/Client/src/Pages/PageSpeed/Details/index.jsx
+++ /dev/null
@@ -1,447 +0,0 @@
-import PropTypes from "prop-types";
-import { Box, Button, Divider, Stack, Tooltip, Typography } from "@mui/material";
-import { useEffect, useState } from "react";
-import { useTheme } from "@emotion/react";
-import { useNavigate, useParams } from "react-router-dom";
-import { useSelector } from "react-redux";
-import { formatDurationRounded, formatDurationSplit } from "../../../Utils/timeUtils";
-import { ChartBox } from "./styled";
-import { logger } from "../../../Utils/Logger";
-import { networkService } from "../../../main";
-import SkeletonLayout from "./skeleton";
-import SettingsIcon from "../../../assets/icons/settings-bold.svg?react";
-import SpedometerIcon from "../../../assets/icons/spedometer-icon.svg?react";
-import MetricsIcon from "../../../assets/icons/ruler-icon.svg?react";
-import ScoreIcon from "../../../assets/icons/monitor-graph-line.svg?react";
-import PerformanceIcon from "../../../assets/icons/performance-report.svg?react";
-import Breadcrumbs from "../../../Components/Breadcrumbs";
-import PulseDot from "../../../Components/Animated/PulseDot";
-import PagespeedDetailsAreaChart from "./Charts/AreaChart";
-import Checkbox from "../../../Components/Inputs/Checkbox";
-import PieChart from "./Charts/PieChart";
-import useUtils from "../../Uptime/utils";
-import "./index.css";
-import { useIsAdmin } from "../../../Hooks/useIsAdmin";
-import StatBox from "../../../Components/StatBox";
-import IconBox from "../../../Components/IconBox";
-
-const PageSpeedDetails = () => {
- const theme = useTheme();
- const navigate = useNavigate();
- const isAdmin = useIsAdmin();
- const { statusColor, pagespeedStatusMsg, determineState } = useUtils();
- const [monitor, setMonitor] = useState({});
- const [audits, setAudits] = useState({});
- const { monitorId } = useParams();
- const { authToken } = useSelector((state) => state.auth);
-
- useEffect(() => {
- const fetchMonitor = async () => {
- try {
- const res = await networkService.getStatsByMonitorId({
- authToken: authToken,
- monitorId: monitorId,
- sortOrder: "desc",
- limit: 50,
- dateRange: "day",
- numToDisplay: null,
- normalize: null,
- });
- setMonitor(res?.data?.data ?? {});
- setAudits(res?.data?.data?.checks?.[0]?.audits ?? {});
- } catch (error) {
- logger.error(logger);
- navigate("/not-found", { replace: true });
- }
- };
-
- fetchMonitor();
- }, [monitorId, authToken, navigate]);
-
- let loading = Object.keys(monitor).length === 0;
- const data = monitor?.checks ? [...monitor.checks].reverse() : [];
-
- const splitDuration = (duration) => {
- const { time, format } = formatDurationSplit(duration);
- return (
- <>
- {time}
- {format}
- >
- );
- };
-
- const [metrics, setMetrics] = useState({
- accessibility: true,
- bestPractices: true,
- performance: true,
- seo: true,
- });
- const handleMetrics = (id) => {
- setMetrics((prev) => ({ ...prev, [id]: !prev[id] }));
- };
-
- return (
-
- {loading ? (
-
- ) : (
- <>
-
-
-
-
- {monitor.name}
-
-
-
-
-
-
-
-
- {monitor?.url}
-
-
- Checking every {formatDurationRounded(monitor?.interval)}.
-
-
-
- {isAdmin && (
- navigate(`/pagespeed/configure/${monitorId}`)}
- sx={{
- ml: "auto",
- alignSelf: "flex-end",
- px: theme.spacing(5),
- "& svg": {
- mr: theme.spacing(3),
- "& path": {
- stroke: theme.palette.primary.contrastTextTertiary,
- },
- },
- }}
- >
-
- Configure
-
- )}
-
-
-
- {splitDuration(monitor?.uptimeDuration)}
- ago
- >
- }
- />
-
- {splitDuration(monitor?.lastChecked)}
- ago
- >
- }
- />
-
-
-
- Showing statistics for past 24 hours.
-
-
-
-
-
-
- Score history
-
-
-
-
-
-
-
-
-
- Metrics
-
-
-
-
- Shown
-
-
-
- handleMetrics("accessibility")}
- />
-
- handleMetrics("bestPractices")}
- />
-
- handleMetrics("performance")}
- />
-
- handleMetrics("seo")}
- />
-
-
-
-
-
-
-
-
-
-
- Performance report
-
-
-
-
- Values are estimated and may vary.{" "}
-
- See calculator
-
-
-
-
-
-
-
-
- Performance Metrics
-
-
- {Object.keys(audits).map((key) => {
- if (key === "_id") return;
-
- let audit = audits[key];
- let score = audit.score * 100;
- let bg =
- score >= 90
- ? theme.palette.success.main
- : score >= 50
- ? theme.palette.warning.main
- : score >= 0
- ? theme.palette.error.contrastText
- : theme.palette.tertiary.main;
-
- // Find the position where the number ends and the unit begins
- const match = audit.displayValue.match(/(\d+\.?\d*)\s*([a-zA-Z]+)/);
- let value;
- let unit;
- if (match) {
- value = match[1];
- match[2] === "s" ? (unit = "seconds") : (unit = match[2]);
- } else {
- value = audit.displayValue;
- }
-
- return (
-
-
-
- {audit.title}
-
-
- {value}
-
- {unit}
-
-
-
-
-
- );
- })}
-
-
-
- >
- )}
-
- );
-};
-
-PageSpeedDetails.propTypes = {
- isAdmin: PropTypes.bool,
- push: PropTypes.func,
-};
-
-export default PageSpeedDetails;
diff --git a/Client/src/Pages/PageSpeed/Details/skeleton.jsx b/Client/src/Pages/PageSpeed/Details/skeleton.jsx
deleted file mode 100644
index 1d55a5039..000000000
--- a/Client/src/Pages/PageSpeed/Details/skeleton.jsx
+++ /dev/null
@@ -1,93 +0,0 @@
-import { Box, Skeleton, Stack } from "@mui/material";
-
-/**
- * Renders a skeleton layout.
- *
- * @returns {JSX.Element}
- */
-const SkeletonLayout = () => {
- return (
- <>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- >
- );
-};
-
-export default SkeletonLayout;
diff --git a/Client/src/Pages/PageSpeed/Details/styled.jsx b/Client/src/Pages/PageSpeed/Details/styled.jsx
deleted file mode 100644
index 291d0c6f2..000000000
--- a/Client/src/Pages/PageSpeed/Details/styled.jsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { Stack, styled } from "@mui/material";
-
-export const ChartBox = styled(Stack)(({ theme }) => ({
- display: "grid",
- minHeight: 300,
- minWidth: 250,
- border: 1,
- borderStyle: "solid",
- borderColor: theme.palette.primary.lowContrast,
- borderRadius: 4,
- borderTopRightRadius: 16,
- borderBottomRightRadius: 16,
- backgroundColor: theme.palette.primary.main,
- "& h2": {
- color: theme.palette.primary.contrastTextSecondary,
- fontSize: 15,
- fontWeight: 500,
- },
- "& p": { color: theme.palette.primary.contrastTextTertiary },
- "& > :nth-of-type(1)": {
- gridColumn: 1,
- gridRow: 1,
- height: "fit-content",
- paddingTop: theme.spacing(8),
- paddingLeft: theme.spacing(8),
- },
- "& > :nth-of-type(2)": { gridColumn: 1, gridRow: 2 },
- "& > :nth-of-type(3)": {
- gridColumn: 2,
- gridRow: "span 2",
- padding: theme.spacing(8),
- borderLeft: 1,
- borderLeftStyle: "solid",
- borderLeftColor: theme.palette.primary.lowContrast,
- borderRadius: 16,
- backgroundColor: theme.palette.primary.main,
- background: `linear-gradient(325deg, ${theme.palette.tertiary.main} 20%, ${theme.palette.primary.main} 45%)`,
- },
- "& path": {
- transition: "stroke-width 400ms ease",
- },
-}));
diff --git a/Client/src/Pages/PageSpeed/index.css b/Client/src/Pages/PageSpeed/index.css
deleted file mode 100644
index 3741a6f0f..000000000
--- a/Client/src/Pages/PageSpeed/index.css
+++ /dev/null
@@ -1,8 +0,0 @@
-.page-speed .label {
- padding: 7px;
- height: 24px;
- font-size: var(--env-var-font-size-small);
-}
-.page-speed:not(:has([class*="fallback__"])) button {
- min-height: 34px;
-}
diff --git a/Client/src/Pages/PageSpeed/index.jsx b/Client/src/Pages/PageSpeed/index.jsx
deleted file mode 100644
index c15ed5296..000000000
--- a/Client/src/Pages/PageSpeed/index.jsx
+++ /dev/null
@@ -1,147 +0,0 @@
-import { Box, Button, Grid, Stack } from "@mui/material";
-import { useEffect, useState } from "react";
-import { useTheme } from "@emotion/react";
-import { useSelector } from "react-redux";
-import Fallback from "../../Components/Fallback";
-import "./index.css";
-import { useNavigate } from "react-router";
-import PropTypes from "prop-types";
-import Breadcrumbs from "../../Components/Breadcrumbs";
-import SkeletonLayout from "./skeleton";
-import Card from "./card";
-import { networkService } from "../../main";
-import { Heading } from "../../Components/Heading";
-import { useIsAdmin } from "../../Hooks/useIsAdmin";
-const PageSpeed = () => {
- const theme = useTheme();
- const navigate = useNavigate();
- const isAdmin = useIsAdmin();
- const { user, authToken } = useSelector((state) => state.auth);
- const [isLoading, setIsLoading] = useState(true);
- const [monitors, setMonitors] = useState([]);
- const [summary, setSummary] = useState({});
-
- useEffect(() => {
- const fetchMonitors = async () => {
- try {
- setIsLoading(true);
- const res = await networkService.getMonitorsByTeamId({
- authToken: authToken,
- teamId: user.teamId,
- limit: 10,
- types: ["pagespeed"],
- page: null,
- rowsPerPage: null,
- filter: null,
- field: null,
- order: null,
- });
- if (res?.data?.data?.filteredMonitors) {
- setMonitors(res.data.data.filteredMonitors);
- setSummary(res.data.data.summary);
- }
- } catch (error) {
- console.log(error);
- } finally {
- setIsLoading(false);
- }
- };
-
- fetchMonitors();
- }, [authToken, user.teamId]);
-
- // will show skeletons only on initial load
- // since monitor state is being added to redux persist, there's no reason to display skeletons on every render
- let isActuallyLoading = isLoading && monitors?.length === 0;
- return (
- [class*="fallback__"])': {
- position: "relative",
- border: 1,
- borderColor: theme.palette.primary.lowContrast,
- borderRadius: theme.shape.borderRadius,
- borderStyle: "dashed",
- backgroundColor: theme.palette.primary.main,
- overflow: "hidden",
- },
- }}
- >
- {isActuallyLoading ? (
-
- ) : monitors?.length !== 0 ? (
-
-
-
-
- {isAdmin && (
- navigate("/pagespeed/create")}
- sx={{ fontWeight: 500, whiteSpace: "nowrap" }}
- >
- Create new
-
- )}
-
-
-
- PageSpeed monitors
- {/* TODO Correct the class current-monitors-counter, there are some unnecessary things there */}
-
- {summary?.totalMonitors ?? 0}
-
-
-
- {monitors?.map((monitor) => (
-
- ))}
-
-
- ) : (
-
- )}
-
- );
-};
-PageSpeed.propTypes = {
- isAdmin: PropTypes.bool,
-};
-
-export default PageSpeed;
diff --git a/Client/src/Pages/PageSpeed/skeleton.jsx b/Client/src/Pages/PageSpeed/skeleton.jsx
deleted file mode 100644
index b6d29dc38..000000000
--- a/Client/src/Pages/PageSpeed/skeleton.jsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import { Box, Skeleton, Stack } from "@mui/material";
-import { useTheme } from "@emotion/react";
-
-/**
- * Renders a skeleton layout.
- *
- * @returns {JSX.Element}
- */
-const SkeletonLayout = () => {
- const theme = useTheme();
-
- return (
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- );
-};
-
-export default SkeletonLayout;
diff --git a/Client/src/Pages/Settings/index.css b/Client/src/Pages/Settings/index.css
deleted file mode 100644
index 52bccab5e..000000000
--- a/Client/src/Pages/Settings/index.css
+++ /dev/null
@@ -1,21 +0,0 @@
-.settings a.MuiTypography-root,
-.settings h2.MuiTypography-root,
-.settings span.MuiTypography-root,
-.settings button,
-.settings p.MuiTypography-root {
- font-size: var(--env-var-font-size-medium);
-}
-.settings h1.MuiTypography-root {
- font-size: var(--env-var-font-size-large);
-}
-.settings h1.MuiTypography-root,
-.settings h2.MuiTypography-root {
- font-weight: 600;
-}
-.settings button {
- min-height: 34px;
-}
-.settings span.MuiTypography-root {
- opacity: 0.6;
- margin-right: 4px;
-}
diff --git a/Client/src/Pages/Settings/index.jsx b/Client/src/Pages/Settings/index.jsx
deleted file mode 100644
index 3cabac713..000000000
--- a/Client/src/Pages/Settings/index.jsx
+++ /dev/null
@@ -1,364 +0,0 @@
-import { useTheme } from "@emotion/react";
-import { Box, Stack, Typography, Button } from "@mui/material";
-import TextInput from "../../Components/Inputs/TextInput";
-import Link from "../../Components/Link";
-import Select from "../../Components/Inputs/Select";
-import { logger } from "../../Utils/Logger";
-import "./index.css";
-import { useDispatch, useSelector } from "react-redux";
-import { createToast } from "../../Utils/toastUtils";
-import {
- deleteMonitorChecksByTeamId,
- addDemoMonitors,
- deleteAllMonitors,
-} from "../../Features/UptimeMonitors/uptimeMonitorsSlice";
-import { update } from "../../Features/Auth/authSlice";
-import PropTypes from "prop-types";
-import LoadingButton from "@mui/lab/LoadingButton";
-import { setTimezone, setMode } from "../../Features/UI/uiSlice";
-import timezones from "../../Utils/timezones.json";
-import { useState, useEffect } from "react";
-import { networkService } from "../../main";
-import { settingsValidation } from "../../Validation/validation";
-import Dialog from "../../Components/Dialog";
-import { useIsAdmin } from "../../Hooks/useIsAdmin";
-import ConfigBox from "../../Components/ConfigBox";
-const SECONDS_PER_DAY = 86400;
-
-const Settings = () => {
- const theme = useTheme();
- const isAdmin = useIsAdmin();
- const { user, authToken } = useSelector((state) => state.auth);
- const { checkTTL } = user;
- const { isLoading } = useSelector((state) => state.uptimeMonitors);
- const { isLoading: authIsLoading } = useSelector((state) => state.auth);
- const { timezone } = useSelector((state) => state.ui);
- const { mode } = useSelector((state) => state.ui);
- const [checksIsLoading, setChecksIsLoading] = useState(false);
- const [form, setForm] = useState({
- ttl: checkTTL ? (checkTTL / SECONDS_PER_DAY).toString() : 0,
- });
- const [version, setVersion] = useState("unknown");
- const [errors, setErrors] = useState({});
- const deleteStatsMonitorsInitState = { deleteMonitors: false, deleteStats: false };
- const [isOpen, setIsOpen] = useState(deleteStatsMonitorsInitState);
- const dispatch = useDispatch();
-
- //Fetching latest release version from github
- useEffect(() => {
- const fetchLatestVersion = async () => {
- let version = "unknown";
- try {
- const response = await networkService.fetchGithubLatestRelease();
- if (!response.status === 200) {
- throw new Error("Failed to fetch latest version");
- }
- version = response.data.tag_name;
- } catch (error) {
- createToast({ body: error.message || "Error fetching latest version" }); // Set error message
- } finally {
- setVersion(version);
- }
- };
- fetchLatestVersion();
- }, []);
-
- const handleChange = (event) => {
- const { value, id } = event.target;
- const { error } = settingsValidation.validate(
- { [id]: value },
- {
- abortEarly: false,
- }
- );
- if (!error || error.details.length === 0) {
- setErrors({});
- } else {
- const newErrors = {};
- error.details.forEach((err) => {
- newErrors[err.path[0]] = err.message;
- });
- setErrors(newErrors);
- console.log(newErrors);
- logger.error("Validation errors:", error.details);
- }
- let inputValue = value;
- id === "ttl" && (inputValue = value.replace(/[^0-9]/g, ""));
- setForm((prev) => ({
- ...prev,
- [id]: inputValue,
- }));
- };
-
- // TODO Handle saving
- const handleSave = async () => {
- try {
- setChecksIsLoading(true);
- await networkService.updateChecksTTL({
- authToken: authToken,
- ttl: form.ttl,
- });
- const updatedUser = { ...user, checkTTL: form.ttl };
- const action = await dispatch(update({ authToken, localData: updatedUser }));
- if (action.payload.success) {
- createToast({
- body: "Settings saved successfully",
- });
- } else {
- if (action.payload) {
- // dispatch errors
- createToast({
- body: action.payload.msg,
- });
- } else {
- // unknown errors
- createToast({
- body: "Unknown error.",
- });
- }
- }
- } catch (error) {
- console.log(error);
- createToast({ body: "Failed to save settings" });
- } finally {
- setChecksIsLoading(false);
- }
- };
-
- const handleClearStats = async () => {
- try {
- const action = await dispatch(
- deleteMonitorChecksByTeamId({ teamId: user.teamId, authToken })
- );
-
- if (deleteMonitorChecksByTeamId.fulfilled.match(action)) {
- createToast({ body: "Stats cleared successfully" });
- } else {
- createToast({ body: "Failed to clear stats" });
- }
- } catch (error) {
- logger.error(error);
- createToast({ body: "Failed to clear stats" });
- } finally {
- setIsOpen(deleteStatsMonitorsInitState);
- }
- };
-
- const handleInsertDemoMonitors = async () => {
- try {
- const action = await dispatch(addDemoMonitors({ authToken }));
- if (addDemoMonitors.fulfilled.match(action)) {
- createToast({ body: "Successfully added demo monitors" });
- } else {
- createToast({ body: "Failed to add demo monitors" });
- }
- } catch (error) {
- logger.error(error);
- createToast({ Body: "Failed to add demo monitors" });
- }
- };
-
- const handleDeleteAllMonitors = async () => {
- try {
- const action = await dispatch(deleteAllMonitors({ authToken }));
- if (deleteAllMonitors.fulfilled.match(action)) {
- createToast({ body: "Successfully deleted all monitors" });
- } else {
- createToast({ body: "Failed to add demo monitors" });
- }
- } catch (error) {
- logger.error(error);
- createToast({ Body: "Failed to delete all monitors" });
- } finally {
- setIsOpen(deleteStatsMonitorsInitState);
- }
- };
-
- return (
-
-
-
-
- General settings
-
- Display timezone - The timezone of
- the dashboard you publicly display.
-
-
-
- {
- dispatch(setTimezone({ timezone: e.target.value }));
- }}
- items={timezones}
- />
-
-
-
-
- Appearance
-
- Switch between light and dark mode.
-
-
-
- {
- dispatch(setMode(e.target.value));
- }}
- items={[
- { _id: "light", name: "Light" },
- { _id: "dark", name: "Dark" },
- ]}
- >
-
-
- {isAdmin && (
-
-
- History and monitoring
-
- Define here for how long you want to keep the data. You can also remove
- all past data.
-
-
-
-
-
- Clear all stats. This is irreversible.
-
- setIsOpen({ ...deleteStatsMonitorsInitState, deleteStats: true })
- }
- sx={{ mt: theme.spacing(4) }}
- >
- Clear all stats
-
-
-
- setIsOpen(deleteStatsMonitorsInitState)}
- confirmationButtonLabel="Yes, clear all stats"
- onConfirm={handleClearStats}
- isLoading={isLoading || authIsLoading || checksIsLoading}
- />
-
- )}
- {isAdmin && (
-
-
- Demo monitors
-
- Here you can add and remove demo monitors.
-
-
-
-
- Add demo monitors
-
- Add demo monitors
-
-
-
- Remove all monitors
-
- setIsOpen({ ...deleteStatsMonitorsInitState, deleteMonitors: true })
- }
- sx={{ mt: theme.spacing(4) }}
- >
- Remove all monitors
-
-
-
- setIsOpen(deleteStatsMonitorsInitState)}
- confirmationButtonLabel="Yes, clear all monitors"
- onConfirm={handleDeleteAllMonitors}
- isLoading={isLoading || authIsLoading || checksIsLoading}
- />
-
- )}
-
-
-
- About
-
-
- Checkmate {version}
-
- Developed by Bluewave Labs.
-
-
-
-
-
- 0}
- variant="contained"
- color="accent"
- sx={{ px: theme.spacing(12), mt: theme.spacing(20) }}
- onClick={handleSave}
- >
- Save
-
-
-
-
- );
-};
-
-Settings.propTypes = {
- isAdmin: PropTypes.bool,
-};
-export default Settings;
diff --git a/Client/src/Pages/Status/index.jsx b/Client/src/Pages/Status/index.jsx
deleted file mode 100644
index 7ba2c0a8d..000000000
--- a/Client/src/Pages/Status/index.jsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { Box } from "@mui/material";
-import { useTheme } from "@emotion/react";
-import Fallback from "../../Components/Fallback";
-
-const Status = () => {
- const theme = useTheme();
-
- return (
- [class*="fallback__"])': {
- position: "relative",
- border: 1,
- borderColor: theme.palette.primary.lowContrast,
- borderRadius: theme.shape.borderRadius,
- borderStyle: "dashed",
- backgroundColor: theme.palette.primary.main,
- overflow: "hidden",
- },
- }}
- >
-
-
- );
-};
-
-export default Status;
diff --git a/Client/src/Pages/Uptime/CreateUptime/index.css b/Client/src/Pages/Uptime/CreateUptime/index.css
deleted file mode 100644
index e69de29bb..000000000
diff --git a/Client/src/Pages/Uptime/Details/PaginationTable/index.jsx b/Client/src/Pages/Uptime/Details/PaginationTable/index.jsx
deleted file mode 100644
index 93e9532c5..000000000
--- a/Client/src/Pages/Uptime/Details/PaginationTable/index.jsx
+++ /dev/null
@@ -1,163 +0,0 @@
-import PropTypes from "prop-types";
-import {
- TableContainer,
- Table,
- TableHead,
- TableRow,
- TableCell,
- TableBody,
- PaginationItem,
- Pagination,
- Paper,
-} from "@mui/material";
-
-import { useState, useEffect } from "react";
-import { useSelector } from "react-redux";
-import { networkService } from "../../../../main";
-import { StatusLabel } from "../../../../Components/Label";
-import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";
-import ArrowForwardRoundedIcon from "@mui/icons-material/ArrowForwardRounded";
-import { logger } from "../../../../Utils/Logger";
-import { formatDateWithTz } from "../../../../Utils/timeUtils";
-import { useTheme } from "@emotion/react";
-const PaginationTable = ({ monitorId, dateRange }) => {
- const theme = useTheme();
- const { authToken } = useSelector((state) => state.auth);
- const [checks, setChecks] = useState([]);
- const [checksCount, setChecksCount] = useState(0);
- const [paginationController, setPaginationController] = useState({
- page: 0,
- rowsPerPage: 5,
- });
- const uiTimezone = useSelector((state) => state.ui.timezone);
-
- useEffect(() => {
- setPaginationController((prevPaginationController) => ({
- ...prevPaginationController,
- page: 0,
- }));
- }, [dateRange]);
-
- useEffect(() => {
- const fetchPage = async () => {
- try {
- const res = await networkService.getChecksByMonitor({
- authToken: authToken,
- monitorId: monitorId,
- sortOrder: "desc",
- limit: null,
- dateRange: dateRange,
- filter: null,
- page: paginationController.page,
- rowsPerPage: paginationController.rowsPerPage,
- });
- setChecks(res.data.data.checks);
- setChecksCount(res.data.data.checksCount);
- } catch (error) {
- logger.error(error);
- }
- };
- fetchPage();
- }, [
- authToken,
- monitorId,
- dateRange,
- paginationController.page,
- paginationController.rowsPerPage,
- ]);
-
- const handlePageChange = (_, newPage) => {
- setPaginationController({
- ...paginationController,
- page: newPage - 1, // 0-indexed
- });
- };
-
- let paginationComponent = <>>;
- if (checksCount > paginationController.rowsPerPage) {
- paginationComponent = (
- (
-
- )}
- />
- );
- }
-
- return (
- <>
-
-
-
-
- Status
- Date & Time
- Status Code
- Message
-
-
-
- {checks.map((check) => {
- const status = check.status === true ? "up" : "down";
-
- return (
-
-
-
-
-
- {formatDateWithTz(
- check.createdAt,
- "ddd, MMMM D, YYYY, HH:mm A",
- uiTimezone
- )}
-
- {check.statusCode ? check.statusCode : "N/A"}
- {check.message}
-
- );
- })}
-
-
-
- {paginationComponent}
- >
- );
-};
-
-PaginationTable.propTypes = {
- monitorId: PropTypes.string.isRequired,
- dateRange: PropTypes.string.isRequired,
-};
-
-export default PaginationTable;
diff --git a/Client/src/Pages/Uptime/Details/index.css b/Client/src/Pages/Uptime/Details/index.css
deleted file mode 100644
index e69de29bb..000000000
diff --git a/Client/src/Pages/Uptime/Details/index.jsx b/Client/src/Pages/Uptime/Details/index.jsx
deleted file mode 100644
index d5be671d3..000000000
--- a/Client/src/Pages/Uptime/Details/index.jsx
+++ /dev/null
@@ -1,476 +0,0 @@
-import PropTypes from "prop-types";
-import { useEffect, useState, useCallback } from "react";
-import { Box, Button, Stack, Tooltip, Typography, useTheme } from "@mui/material";
-import { useSelector } from "react-redux";
-import { useNavigate, useParams } from "react-router-dom";
-import { networkService } from "../../../main";
-import { logger } from "../../../Utils/Logger";
-import MonitorDetailsAreaChart from "../../../Components/Charts/MonitorDetailsAreaChart";
-import ButtonGroup from "@mui/material/ButtonGroup";
-import SettingsIcon from "../../../assets/icons/settings-bold.svg?react";
-import UptimeIcon from "../../../assets/icons/uptime-icon.svg?react";
-import ResponseTimeIcon from "../../../assets/icons/response-time-icon.svg?react";
-import AverageResponseIcon from "../../../assets/icons/average-response-icon.svg?react";
-import IncidentsIcon from "../../../assets/icons/incidents.svg?react";
-import HistoryIcon from "../../../assets/icons/history-icon.svg?react";
-import PaginationTable from "./PaginationTable";
-import Breadcrumbs from "../../../Components/Breadcrumbs";
-import PulseDot from "../../../Components/Animated/PulseDot";
-import { ChartBox } from "./styled";
-import SkeletonLayout from "./skeleton";
-import "./index.css";
-import useUtils from "../utils";
-import { formatDateWithTz, formatDurationSplit } from "../../../Utils/timeUtils";
-import { useIsAdmin } from "../../../Hooks/useIsAdmin";
-import IconBox from "../../../Components/IconBox";
-import StatBox from "../../../Components/StatBox";
-import UpBarChart from "./Charts/UpBarChart";
-import DownBarChart from "./Charts/DownBarChart";
-import ResponseGaugeChart from "./Charts/ResponseGaugeChart";
-/**
- * Details page component displaying monitor details and related information.
- * @component
- */
-const DetailsPage = () => {
- const theme = useTheme();
- const { statusColor, statusMsg, determineState } = useUtils();
- const isAdmin = useIsAdmin();
- const [monitor, setMonitor] = useState({});
- const { monitorId } = useParams();
- const { authToken } = useSelector((state) => state.auth);
- const [dateRange, setDateRange] = useState("day");
- const [certificateExpiry, setCertificateExpiry] = useState("N/A");
- const navigate = useNavigate();
-
- const certificateDateFormat = "MMM D, YYYY h A";
- const dateFormat = dateRange === "day" ? "MMM D, h A" : "MMM D";
- const uiTimezone = useSelector((state) => state.ui.timezone);
-
- const fetchMonitor = useCallback(async () => {
- try {
- const res = await networkService.getUptimeDetailsById({
- authToken: authToken,
- monitorId: monitorId,
- dateRange: dateRange,
- normalize: true,
- });
- setMonitor(res?.data?.data ?? {});
- } catch (error) {
- logger.error(error);
- navigate("/not-found", { replace: true });
- }
- }, [authToken, monitorId, navigate, dateRange]);
-
- useEffect(() => {
- fetchMonitor();
- }, [fetchMonitor]);
-
- useEffect(() => {
- const fetchCertificate = async () => {
- if (monitor?.type !== "http") {
- return;
- }
- try {
- const res = await networkService.getCertificateExpiry({
- authToken: authToken,
- monitorId: monitorId,
- });
- if (res?.data?.data?.certificateDate) {
- const date = res.data.data.certificateDate;
- setCertificateExpiry(
- formatDateWithTz(date, certificateDateFormat, uiTimezone) ?? "N/A"
- );
- }
- } catch (error) {
- setCertificateExpiry("N/A");
- console.error(error);
- }
- };
- fetchCertificate();
- }, [authToken, monitorId, monitor, uiTimezone, dateFormat]);
-
- const splitDuration = (duration) => {
- const { time, format } = formatDurationSplit(duration);
- return (
- <>
- {time}
- {format}
- >
- );
- };
-
- let loading = Object.keys(monitor).length === 0;
-
- const [hoveredUptimeData, setHoveredUptimeData] = useState(null);
- const [hoveredIncidentsData, setHoveredIncidentsData] = useState(null);
-
- const BREADCRUMBS = [
- { name: "uptime", path: "/uptime" },
- { name: "details", path: `/uptime/${monitorId}` },
- ];
- return (
-
- {loading ? (
-
- ) : (
- <>
-
-
-
-
-
- {monitor.name}
-
-
- {/* TODO there is a tooltip at BarChart component. Wrap the Tooltip on our own component */}
-
-
-
-
-
-
- {monitor.url?.replace(/^https?:\/\//, "") || "..."}
-
-
- {/* Checking every {formatDurationRounded(monitor?.interval)}. */}
-
-
-
-
- {isAdmin && (
- navigate(`/uptime/configure/${monitorId}`)}
- sx={{
- px: theme.spacing(5),
- "& svg": {
- mr: theme.spacing(3),
- "& path": {
- /* Should always be contrastText for the button color */
- stroke: theme.palette.secondary.contrastText,
- },
- },
- }}
- >
- Configure
-
- )}
-
-
-
-
-
-
- {monitor?.latestResponseTime}
- {"ms"}
- >
- }
- />
-
- {certificateExpiry}
-
- }
- />
-
-
-
-
- Showing statistics for past{" "}
- {dateRange === "day"
- ? "24 hours"
- : dateRange === "week"
- ? "7 days"
- : "30 days"}
- .
-
-
- setDateRange("day")}
- >
- Day
-
- setDateRange("week")}
- >
- Week
-
- setDateRange("month")}
- >
- Month
-
-
-
-
-
-
-
-
-
- Uptime
-
-
-
- Total Checks
-
- {hoveredUptimeData !== null
- ? hoveredUptimeData.totalChecks
- : (monitor?.groupedUpChecks?.reduce((count, checkGroup) => {
- return count + checkGroup.totalChecks;
- }, 0) ?? 0)}
-
- {hoveredUptimeData !== null && hoveredUptimeData.time !== null && (
-
- {formatDateWithTz(
- hoveredUptimeData._id,
- dateFormat,
- uiTimezone
- )}
-
- )}
-
-
-
- {hoveredUptimeData !== null
- ? "Avg Response Time"
- : "Uptime Percentage"}
-
-
- {hoveredUptimeData !== null
- ? Math.floor(hoveredUptimeData?.avgResponseTime ?? 0)
- : Math.floor(
- ((monitor?.upChecks?.totalChecks ?? 0) /
- (monitor?.totalChecks ?? 1)) *
- 100
- )}
-
- {hoveredUptimeData !== null ? " ms" : " %"}
-
-
-
-
-
-
-
-
-
-
-
- Incidents
-
-
- Total Incidents
-
- {hoveredIncidentsData !== null
- ? hoveredIncidentsData.totalChecks
- : (monitor?.groupedDownChecks?.reduce((count, checkGroup) => {
- return count + checkGroup.totalChecks;
- }, 0) ?? 0)}
-
- {hoveredIncidentsData !== null &&
- hoveredIncidentsData.time !== null && (
-
- {formatDateWithTz(
- hoveredIncidentsData._id,
- dateFormat,
- uiTimezone
- )}
-
- )}
-
-
-
-
-
-
-
-
- Average Response Time
-
-
-
-
-
-
-
-
- Response Times
-
-
-
-
-
-
-
-
-
- History
-
-
-
-
-
-
-
- >
- )}
-
- );
-};
-
-DetailsPage.propTypes = {
- isAdmin: PropTypes.bool,
-};
-export default DetailsPage;
diff --git a/Client/src/Pages/Uptime/Details/skeleton.jsx b/Client/src/Pages/Uptime/Details/skeleton.jsx
deleted file mode 100644
index 0bdc03ca8..000000000
--- a/Client/src/Pages/Uptime/Details/skeleton.jsx
+++ /dev/null
@@ -1,120 +0,0 @@
-import { Box, Skeleton, Stack, useTheme } from "@mui/material";
-
-/**
- * Renders a skeleton layout.
- *
- * @returns {JSX.Element}
- */
-const SkeletonLayout = () => {
- const theme = useTheme();
-
- return (
- <>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- >
- );
-};
-
-export default SkeletonLayout;
diff --git a/Client/src/Pages/Uptime/Details/styled.jsx b/Client/src/Pages/Uptime/Details/styled.jsx
deleted file mode 100644
index 164fee457..000000000
--- a/Client/src/Pages/Uptime/Details/styled.jsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { Stack, styled } from "@mui/material";
-
-export const ChartBox = styled(Stack)(({ theme }) => ({
- flex: "1 30%",
- gap: theme.spacing(8),
- height: 300,
- minWidth: 250,
- padding: theme.spacing(8),
- border: 1,
- borderStyle: "solid",
- borderColor: theme.palette.primary.lowContrast,
- borderRadius: 4,
- backgroundColor: theme.palette.primary.main,
- "& h2": {
- color: theme.palette.primary.contrastTextSecondary,
- fontSize: 15,
- fontWeight: 500,
- },
- "& .MuiBox-root:not(.area-tooltip) p": {
- color: theme.palette.primary.contrastTextTertiary,
- fontSize: 13,
- },
- "& .MuiBox-root > span": {
- color: theme.palette.primary.contrastText,
- fontSize: 20,
- "& span": {
- opacity: 0.8,
- marginLeft: 2,
- fontSize: 15,
- },
- },
- "& .MuiStack-root": {
- flexDirection: "row",
- gap: theme.spacing(6),
- },
- "& .MuiStack-root:first-of-type": {
- alignItems: "center",
- },
- "& tspan, & text": {
- fill: theme.palette.primary.contrastTextTertiary,
- },
- "& path": {
- transition: "fill 300ms ease, stroke-width 400ms ease",
- },
-}));
diff --git a/Client/src/Pages/Uptime/Home/UptimeDataTable/Skeleton/index.jsx b/Client/src/Pages/Uptime/Home/UptimeDataTable/Skeleton/index.jsx
deleted file mode 100644
index c17f6d74b..000000000
--- a/Client/src/Pages/Uptime/Home/UptimeDataTable/Skeleton/index.jsx
+++ /dev/null
@@ -1,47 +0,0 @@
-import { Skeleton } from "@mui/material";
-import DataTable from "../../../../../Components/Table";
-const ROWS_NUMBER = 7;
-const ROWS_ARRAY = Array.from({ length: ROWS_NUMBER }, (_, i) => i);
-
-const TableSkeleton = () => {
- /* TODO Skeleton does not follow light and dark theme */
-
- const headers = [
- {
- id: "name",
-
- content: "Host",
-
- render: () => ,
- },
- {
- id: "status",
- content: "Status",
- render: () => ,
- },
- {
- id: "responseTime",
- content: "Response Time",
- render: () => ,
- },
- {
- id: "type",
- content: "Type",
- render: () => ,
- },
- {
- id: "actions",
- content: "Actions",
- render: () => ,
- },
- ];
-
- return (
-
- );
-};
-
-export { TableSkeleton };
diff --git a/Client/src/Pages/Uptime/Home/UptimeDataTable/index.jsx b/Client/src/Pages/Uptime/Home/UptimeDataTable/index.jsx
deleted file mode 100644
index 6961c6d5c..000000000
--- a/Client/src/Pages/Uptime/Home/UptimeDataTable/index.jsx
+++ /dev/null
@@ -1,325 +0,0 @@
-// Components
-import { Box, Stack, CircularProgress } from "@mui/material";
-import Search from "../../../../Components/Inputs/Search";
-import { Heading } from "../../../../Components/Heading";
-import DataTable from "../../../../Components/Table";
-import ArrowDownwardRoundedIcon from "@mui/icons-material/ArrowDownwardRounded";
-import ArrowUpwardRoundedIcon from "@mui/icons-material/ArrowUpwardRounded";
-import Host from "../host";
-import { StatusLabel } from "../../../../Components/Label";
-import BarChart from "../../../../Components/Charts/BarChart";
-import ActionsMenu from "../actionsMenu";
-
-// Utils
-import { useTheme } from "@emotion/react";
-import useUtils from "../../utils";
-import { useState, memo, useCallback } from "react";
-import { useNavigate } from "react-router-dom";
-import "../index.css";
-import PropTypes from "prop-types";
-
-const SearchComponent = memo(
- ({ monitors, debouncedSearch, onSearchChange, setIsSearching }) => {
- const [localSearch, setLocalSearch] = useState(debouncedSearch);
- const handleSearch = useCallback(
- (value) => {
- setIsSearching(true);
- setLocalSearch(value);
- onSearchChange(value);
- },
- [onSearchChange, setIsSearching]
- );
-
- return (
-
-
-
- );
- }
-);
-SearchComponent.displayName = "SearchComponent";
-SearchComponent.propTypes = {
- monitors: PropTypes.array,
- debouncedSearch: PropTypes.string,
- onSearchChange: PropTypes.func,
- setIsSearching: PropTypes.func,
-};
-
-/**
- * UptimeDataTable displays a table of uptime monitors with sorting, searching, and action capabilities
- * @param {Object} props - Component props
- * @param {boolean} props.isAdmin - Whether the current user has admin privileges
- * @param {boolean} props.isLoading - Loading state of the table
- * @param {Array<{
- * _id: string,
- * url: string,
- * title: string,
- * percentage: number,
- * percentageColor: string,
- * monitor: {
- * _id: string,
- * type: string,
- * checks: Array
- * }
- * }>} props.monitors - Array of monitor objects to display
- * @param {number} props.monitorCount - Total count of monitors
- * @param {Object} props.sort - Current sort configuration
- * @param {string} props.sort.field - Field to sort by
- * @param {'asc'|'desc'} props.sort.order - Sort direction
- * @param {Function} props.setSort - Callback to update sort configuration
- * @param {string} props.search - Current search query
- * @param {Function} props.setSearch - Callback to update search query
- * @param {boolean} props.isSearching - Whether a search is in progress
- * @param {Function} props.setIsSearching - Callback to update search state
- * @param {Function} props.setIsLoading - Callback to update loading state
- * @param {Function} props.triggerUpdate - Callback to trigger a data refresh
- * @returns {JSX.Element} Rendered component
- */
-const UptimeDataTable = ({
- isAdmin,
- isLoading,
- monitors,
- filteredMonitors,
- monitorCount,
- sort,
- setSort,
- debouncedSearch,
- setSearch,
- isSearching,
- setIsSearching,
- setIsLoading,
- triggerUpdate,
-}) => {
- const { determineState } = useUtils();
-
- const theme = useTheme();
- const navigate = useNavigate();
-
- const handleSort = (field) => {
- let order = "";
- if (sort.field !== field) {
- order = "desc";
- } else {
- order = sort.order === "asc" ? "desc" : "asc";
- }
- setSort({ field, order });
- };
-
- const headers = [
- {
- id: "name",
- content: (
- handleSort("name")}
- >
- Host
-
- {sort.order === "asc" ? (
-
- ) : (
-
- )}
-
-
- ),
- render: (row) => (
-
- ),
- },
- {
- id: "status",
- content: (
- handleSort("status")}
- >
- {" "}
- Status
-
- {sort.order === "asc" ? (
-
- ) : (
-
- )}
-
-
- ),
- render: (row) => {
- const status = determineState(row.monitor);
- return (
-
- );
- },
- },
- {
- id: "responseTime",
- content: "Response Time",
- render: (row) => ,
- },
- {
- id: "type",
- content: "Type",
- render: (row) => (
- {row.monitor.type}
- ),
- },
- {
- id: "actions",
- content: "Actions",
- render: (row) => (
-
- ),
- },
- ];
-
- return (
-
-
- Uptime monitors
- {/* TODO Same as the one in Infrastructure. Create component */}
-
- {monitorCount}
-
-
-
-
-
- {(isSearching || isLoading) && (
- <>
-
-
-
-
- >
- )}
- {
- navigate(`/uptime/${row.id}`);
- },
- emptyView: "No monitors found",
- }}
- />
-
-
- );
-};
-
-const MemoizedUptimeDataTable = memo(UptimeDataTable);
-export default MemoizedUptimeDataTable;
-
-UptimeDataTable.propTypes = {
- isAdmin: PropTypes.bool,
- isLoading: PropTypes.bool,
- monitors: PropTypes.array,
- filteredMonitors: PropTypes.array,
- monitorCount: PropTypes.number,
- sort: PropTypes.shape({
- field: PropTypes.string,
- order: PropTypes.oneOf(["asc", "desc"]),
- }),
- setSort: PropTypes.func,
- debouncedSearch: PropTypes.string,
- setSearch: PropTypes.func,
- isSearching: PropTypes.bool,
- setIsSearching: PropTypes.func,
- setIsLoading: PropTypes.func,
- triggerUpdate: PropTypes.func,
-};
diff --git a/Client/src/Pages/Uptime/Home/fallback.jsx b/Client/src/Pages/Uptime/Home/fallback.jsx
deleted file mode 100644
index 2606ca95f..000000000
--- a/Client/src/Pages/Uptime/Home/fallback.jsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import { Box, Button, Stack, Typography } from "@mui/material";
-import { useTheme } from "@emotion/react";
-import { useNavigate } from "react-router-dom";
-import { useSelector } from "react-redux";
-import PlaceholderLight from "../../../assets/Images/data_placeholder.svg?react";
-import PlaceholderDark from "../../../assets/Images/data_placeholder_dark.svg?react";
-import PropTypes from "prop-types";
-
-const Fallback = ({ isAdmin }) => {
- const theme = useTheme();
- const navigate = useNavigate();
- const mode = useSelector((state) => state.ui.mode);
-
- return (
-
-
- {mode === "light" ? : }
-
-
- No monitors found to display
-
-
- It looks like you don’t have any monitors set up yet.
-
- {isAdmin && (
- {
- navigate("/uptime/create");
- }}
- sx={{ mt: theme.spacing(12) }}
- >
- Create your first monitor
-
- )}
-
- );
-};
-
-Fallback.propTypes = {
- isAdmin: PropTypes.bool,
-};
-
-export default Fallback;
diff --git a/Client/src/Pages/Uptime/Home/index.css b/Client/src/Pages/Uptime/Home/index.css
deleted file mode 100644
index adb1d8674..000000000
--- a/Client/src/Pages/Uptime/Home/index.css
+++ /dev/null
@@ -1,6 +0,0 @@
-/* TODO take these from here and declare using emotion. Plus, the values should live in the theme */
-.monitors .MuiStack-root > button:not(.MuiIconButton-root) {
- font-size: var(--env-var-font-size-medium);
- height: var(--env-var-height-2);
- min-width: fit-content;
-}
diff --git a/Client/src/Pages/Uptime/Home/index.jsx b/Client/src/Pages/Uptime/Home/index.jsx
deleted file mode 100644
index 446702ebb..000000000
--- a/Client/src/Pages/Uptime/Home/index.jsx
+++ /dev/null
@@ -1,244 +0,0 @@
-// Components
-import { Box, Stack, Button } from "@mui/material";
-import Greeting from "../../../Utils/greeting";
-import SkeletonLayout from "./skeleton";
-import Fallback from "./fallback";
-import StatusBox from "./StatusBox";
-import UptimeDataTable from "./UptimeDataTable";
-import Pagination from "../../../Components/Table/TablePagination";
-
-// Utils
-import { useTheme } from "@emotion/react";
-import { useEffect, useState, useCallback, useMemo } from "react";
-import { setRowsPerPage } from "../../../Features/UI/uiSlice";
-import { useIsAdmin } from "../../../Hooks/useIsAdmin";
-import { useSelector, useDispatch } from "react-redux";
-import { useNavigate } from "react-router-dom";
-import { createToast } from "../../../Utils/toastUtils";
-import Breadcrumbs from "../../../Components/Breadcrumbs";
-import useDebounce from "../../../Utils/debounce";
-import { networkService } from "../../../main";
-
-const BREADCRUMBS = [{ name: `Uptime`, path: "/uptime" }];
-
-const UptimeMonitors = () => {
- // Redux state
- const rowsPerPage = useSelector((state) => state.ui.monitors.rowsPerPage);
- // Local state
- const [sort, setSort] = useState({});
- const [search, setSearch] = useState("");
- const [page, setPage] = useState(0);
- const [isSearching, setIsSearching] = useState(false);
- const [isLoading, setIsLoading] = useState(false);
- const [monitorUpdateTrigger, setMonitorUpdateTrigger] = useState(false);
- const [monitors, setMonitors] = useState([]);
- const [filteredMonitors, setFilteredMonitors] = useState([]);
- const [monitorsSummary, setMonitorsSummary] = useState({});
-
- // Utils
- const debouncedFilter = useDebounce(search, 500);
- const dispatch = useDispatch();
- const theme = useTheme();
- const navigate = useNavigate();
- const isAdmin = useIsAdmin();
-
- const authState = useSelector((state) => state.auth);
-
- const fetchParams = useMemo(
- () => ({
- authToken: authState.authToken,
- teamId: authState.user.teamId,
- sort: { field: sort.field, order: sort.order },
- filter: debouncedFilter,
- page,
- rowsPerPage,
- }),
- [authState.authToken, authState.user.teamId, sort, debouncedFilter, page, rowsPerPage]
- );
-
- const getMonitorWithPercentage = useCallback((monitor, theme) => {
- let uptimePercentage = "";
- let percentageColor = "";
-
- if (monitor.uptimePercentage !== undefined) {
- uptimePercentage =
- monitor.uptimePercentage === 0
- ? "0"
- : (monitor.uptimePercentage * 100).toFixed(2);
-
- percentageColor =
- monitor.uptimePercentage < 0.25
- ? theme.palette.error.main
- : monitor.uptimePercentage < 0.5
- ? theme.palette.warning.main
- : monitor.uptimePercentage < 0.75
- ? theme.palette.success.main
- : theme.palette.success.main;
- }
-
- return {
- id: monitor._id,
- name: monitor.name,
- url: monitor.url,
- title: monitor.name,
- percentage: uptimePercentage,
- percentageColor,
- monitor: monitor,
- };
- }, []);
-
- const fetchMonitors = useCallback(async () => {
- try {
- setIsLoading(true);
- const config = fetchParams;
- const res = await networkService.getMonitorsByTeamId({
- authToken: config.authToken,
- teamId: config.teamId,
- limit: 25,
- types: ["http", "ping", "docker", "port"],
- page: config.page,
- rowsPerPage: config.rowsPerPage,
- filter: config.filter,
- field: config.sort.field,
- order: config.sort.order,
- });
- const { monitors, filteredMonitors, summary } = res.data.data;
- const mappedMonitors = filteredMonitors.map((monitor) =>
- getMonitorWithPercentage(monitor, theme)
- );
- setMonitors(monitors);
- setFilteredMonitors(mappedMonitors);
- setMonitorsSummary(summary);
- } catch (error) {
- createToast({
- body: error.message,
- });
- } finally {
- setIsLoading(false);
- setIsSearching(false);
- }
- }, [fetchParams, getMonitorWithPercentage, theme]);
-
- useEffect(() => {
- fetchMonitors();
- }, [fetchMonitors, monitorUpdateTrigger]);
-
- const handleChangePage = (event, newPage) => {
- setPage(newPage);
- };
-
- const handleChangeRowsPerPage = (event) => {
- dispatch(
- setRowsPerPage({
- value: parseInt(event.target.value, 10),
- table: "monitors",
- })
- );
- setPage(0);
- };
-
- const triggerUpdate = useCallback(() => {
- setMonitorUpdateTrigger((prev) => !prev);
- }, []);
- const totalMonitors = monitorsSummary?.totalMonitors ?? 0;
- const hasMonitors = totalMonitors > 0;
- const canAddMonitor = isAdmin && hasMonitors;
-
- return (
-
-
-
-
- {canAddMonitor && (
- <>
- {
- navigate("/uptime/create");
- }}
- sx={{
- fontWeight: 500,
- whiteSpace: "nowrap",
- /* TODO IMPORTANT this should be applied to all buttons */
- "&:focus-visible": {
- outline: `2px solid ${theme.palette.primary.contrastText}`,
- outlineOffset: 4,
- },
- }}
- >
- Create new
-
- >
- )}
-
-
-
- {
- <>
- {!isLoading && !hasMonitors && }
- {isLoading ? (
-
- ) : (
- hasMonitors && (
- <>
-
-
-
-
-
-
-
- >
- )
- )}
- >
- }
-
- );
-};
-
-export default UptimeMonitors;
diff --git a/Client/src/Routes/index.jsx b/Client/src/Routes/index.jsx
deleted file mode 100644
index b5f4dd376..000000000
--- a/Client/src/Routes/index.jsx
+++ /dev/null
@@ -1,172 +0,0 @@
-import { Navigate, Route, Routes as LibRoutes } from "react-router";
-import HomeLayout from "../Components/Layouts/HomeLayout";
-import { Infrastructure } from "../Pages/Infrastructure";
-import InfrastructureDetails from "../Pages/Infrastructure/Details";
-import NotFound from "../Pages/NotFound";
-import Login from "../Pages/Auth/Login/Login";
-import Register from "../Pages/Auth/Register/Register";
-import Account from "../Pages/Account";
-import Monitors from "../Pages/Uptime/Home";
-import CreateMonitor from "../Pages/Uptime/CreateUptime";
-import CreateInfrastructureMonitor from "../Pages/Infrastructure/CreateMonitor";
-import Incidents from "../Pages/Incidents";
-import Status from "../Pages/Status";
-import Integrations from "../Pages/Integrations";
-import Settings from "../Pages/Settings";
-import ForgotPassword from "../Pages/Auth/ForgotPassword";
-import CheckEmail from "../Pages/Auth/CheckEmail";
-import SetNewPassword from "../Pages/Auth/SetNewPassword";
-import NewPasswordConfirmed from "../Pages/Auth/NewPasswordConfirmed";
-import ProtectedRoute from "../Components/ProtectedRoute";
-import Details from "../Pages/Uptime/Details";
-import Maintenance from "../Pages/Maintenance";
-import Configure from "../Pages/Uptime/Configure";
-import PageSpeed from "../Pages/PageSpeed";
-import CreatePageSpeed from "../Pages/PageSpeed/CreatePageSpeed";
-import CreateNewMaintenanceWindow from "../Pages/Maintenance/CreateMaintenance";
-import PageSpeedDetails from "../Pages/PageSpeed/Details";
-import PageSpeedConfigure from "../Pages/PageSpeed/Configure";
-import withAdminCheck from "../Components/HOC/withAdminCheck";
-
-const Routes = () => {
- const AdminCheckedRegister = withAdminCheck(Register);
- return (
-
-
-
-
- }
- >
- }
- />
- }
- />
-
- }
- />
- }
- />
- }
- />
- }
- />
- }
- />
- }
- />
- }
- />
- }
- />
- }
- />
- }
- />
- }
- />
-
- }
- />
- }
- />
- }
- />
- }
- />
- }
- />
- }
- />
- }
- />
- }
- />
-
-
- }
- />
-
- }
- />
-
- }
- />
-
- }
- />
- }
- />
- }
- />
- }
- />
-
- }
- />
-
- );
-};
-
-export { Routes };
diff --git a/Client/src/Utils/Theme/globalTheme.js b/Client/src/Utils/Theme/globalTheme.js
deleted file mode 100644
index 12c377b3e..000000000
--- a/Client/src/Utils/Theme/globalTheme.js
+++ /dev/null
@@ -1,313 +0,0 @@
-import { typographyLevels } from "./constants";
-
-const fontFamilyPrimary = '"Inter" , sans-serif';
-// const fontFamilySecondary = '"Avenir", sans-serif';
-
-/* TODO take the color out from here */
-const shadow =
- "0px 4px 24px -4px rgba(16, 24, 40, 0.08), 0px 3px 3px -3px rgba(16, 24, 40, 0.03)";
-
-const baseTheme = (palette) => ({
- typography: {
- fontFamily: fontFamilyPrimary,
- fontSize: 14,
- h1: {
- fontSize: typographyLevels.xl,
- color: palette.primary.contrastText,
- fontWeight: 500,
- },
- h2: {
- fontSize: typographyLevels.l,
- color: palette.primary.contrastTextSecondary,
- fontWeight: 400,
- },
- body1: {
- fontSize: typographyLevels.m,
- color: palette.primary.contrastTextTertiary,
- fontWeight: 400,
- },
- body2: {
- fontSize: typographyLevels.s,
- color: palette.primary.contrastTextTertiary,
- fontWeight: 400,
- },
- },
- /* TODO change to 4 */
- spacing: 2,
- /* TODO we can skip using the callback functions on the next lines since we are already accessing it on line 10. That was the last thing I managed to do, so we are sort of doing it twice*/
- /* TODO All these should live inside of a component*/
- components: {
- MuiButton: {
- defaultProps: {
- disableRipple: true,
- },
-
- styleOverrides: {
- root: ({ theme }) => ({
- variants: [
- {
- props: (props) => props.color === "accent",
- style: {
- "&:hover": {
- backgroundColor: theme.palette.accent.darker,
- },
- },
- },
- {
- props: (props) => props.variant === "group",
- style: {
- /* color: theme.palette.secondary.contrastText, */
- color: theme.palette.primary.contrastText,
- backgroundColor: theme.palette.primary.main,
- border: 1,
- borderStyle: "solid",
- borderColor: theme.palette.primary.lowContrast,
- },
- },
- {
- props: (props) => props.variant === "group" && props.filled === "true",
- style: {
- backgroundColor: theme.palette.secondary.main,
- },
- },
- /* {
- props: (props) => props.variant === "contained",
- style: {
- backgroundColor: `${theme.palette.accent.main} !important`,
- },
- }, */
-
- {
- props: (props) =>
- props.variant === "contained" && props.color === "secondary",
- style: {
- border: 1,
- borderStyle: "solid",
- borderColor: theme.palette.primary.lowContrast,
- },
- },
- {
- props: (props) => {
- return (
- props.variant === "contained" &&
- props.disabled &&
- props.classes.loadingIndicator === undefined // Do not apply to loading button
- );
- },
- style: {
- backgroundColor: `${theme.palette.secondary.main} !important`,
- color: `${theme.palette.secondary.contrastText} !important`,
- },
- },
- ],
- fontWeight: 400,
- borderRadius: 4,
- boxShadow: "none",
- textTransform: "none",
- "&:focus": {
- outline: "none",
- },
- "&:hover": {
- boxShadow: "none",
- },
- "&.MuiLoadingButton-root": {
- "&:disabled": {
- backgroundColor: theme.palette.secondary.main,
- color: theme.palette.primary.contrastText,
- },
- "&.MuiButton-colorAccent:hover": {
- boxShadow: `0 0 0 1px ${theme.palette.accent.main}`, // CAIO_REVIEW, this should really have a solid BG color
- },
- },
- "&.MuiLoadingButton-loading": {
- "& .MuiLoadingButton-label": {
- color: "transparent",
- },
- "& .MuiLoadingButton-loadingIndicator": {
- color: "inherit",
- },
- },
- }),
- },
- },
-
- MuiIconButton: {
- styleOverrides: {
- root: ({ theme }) => ({
- padding: 4,
- transition: "none",
- "&:hover": {
- backgroundColor: theme.palette.primary.lowContrast,
- },
- }),
- },
- },
- MuiPaper: {
- styleOverrides: {
- root: ({ theme }) => {
- return {
- marginTop: 4,
- padding: 0,
- border: 1,
- borderStyle: "solid",
- borderColor: theme.palette.primary.lowContrast,
- borderRadius: 4,
- boxShadow: shadow,
- backgroundColor: theme.palette.primary.main,
- backgroundImage: "none",
- };
- },
- },
- },
- MuiList: {
- styleOverrides: {
- root: {
- padding: 0,
- },
- },
- },
- MuiListItemButton: {
- styleOverrides: {
- root: {
- transition: "none",
- },
- },
- },
- MuiMenuItem: {
- styleOverrides: {
- root: ({ theme }) => ({
- borderRadius: 4,
- backgroundColor: "inherit",
- padding: "4px 6px",
- color: theme.palette.primary.contrastTextSecondary,
- fontSize: 13,
- margin: 2,
- minWidth: 100,
- "&:hover, &.Mui-selected, &.Mui-selected:hover, &.Mui-selected.Mui-focusVisible":
- {
- backgroundColor: theme.palette.primary.lowContrast,
- },
- }),
- },
- },
- MuiTableCell: {
- styleOverrides: {
- root: ({ theme }) => ({
- borderBottomColor: theme.palette.primary.lowContrast,
- }),
- },
- },
- MuiTableHead: {
- styleOverrides: {
- root: ({ theme }) => ({
- backgroundColor: theme.palette.tertiary.main,
- }),
- },
- },
- MuiPagination: {
- styleOverrides: {
- root: ({ theme }) => ({
- backgroundColor: theme.palette.primary.main,
- border: 1,
- borderStyle: "solid",
- borderColor: theme.palette.primary.lowContrast,
- "& button": {
- color: theme.palette.primary.contrastTextTertiary,
- borderRadius: 4,
- },
- "& li:first-of-type button, & li:last-of-type button": {
- border: 1,
- borderStyle: "solid",
- borderColor: theme.palette.primary.lowContrast,
- },
- }),
- },
- },
- MuiPaginationItem: {
- styleOverrides: {
- root: ({ theme }) => ({
- "&:not(.MuiPaginationItem-ellipsis):hover, &.Mui-selected": {
- backgroundColor: theme.palette.primary.lowContrast,
- },
- }),
- },
- },
- MuiSkeleton: {
- styleOverrides: {
- root: ({ theme }) => ({
- backgroundColor: theme.palette.primary.lowContrast,
- }),
- },
- },
- MuiTextField: {
- styleOverrides: {
- root: ({ theme }) => ({
- "& fieldset": {
- borderColor: theme.palette.primary.lowContrast,
- borderRadius: theme.shape.borderRadius,
- },
- "& .MuiInputBase-input": {
- padding: ".75em",
- minHeight: "var(--env-var-height-2)",
- fontSize: "var(--env-var-font-size-medium)",
- fontWeight: 400,
- color: palette.primary.contrastTextSecondary,
- "&.Mui-disabled": {
- opacity: 0.3,
- WebkitTextFillColor: "unset",
- },
- "& .Mui-focused": {
- /* color: "#ff0000", */
- /* borderColor: theme.palette.primary.contrastText, */
- },
- },
- "& .MuiInputBase-input:-webkit-autofill": {
- transition: "background-color 5000s ease-in-out 0s",
- WebkitBoxShadow: `0 0 0px 1000px ${theme.palette.primary.main} inset`,
- WebkitTextFillColor: theme.palette.primary.contrastText,
- },
- "& .MuiInputBase-input.MuiOutlinedInput-input": {
- padding: "0 var(--env-var-spacing-1-minus) !important",
- },
- "& .MuiOutlinedInput-root": {
- color: theme.palette.primary.contrastTextSecondary,
- borderRadius: 4,
- },
- "& .MuiOutlinedInput-notchedOutline": {
- borderRadius: 4,
- },
-
- "& .MuiFormHelperText-root": {
- color: palette.error.main,
- opacity: 0.8,
- fontSize: "var(--env-var-font-size-medium)",
-
- marginLeft: 0,
- },
- "& .MuiFormHelperText-root.Mui-error": {
- opacity: 0.8,
- fontSize: "var(--env-var-font-size-medium)",
- color: palette.error.main,
- },
- }),
- },
- },
- MuiOutlinedInput: {
- styleOverrides: {
- root: {
- color: palette.primary.contrastTextTertiary,
- "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
- borderColor: palette.primary.contrastTextTertiary,
- },
- },
- },
- },
- },
- shape: {
- borderRadius: 2,
- borderThick: 2,
- boxShadow: shadow,
- },
-});
-
-export { baseTheme };
diff --git a/Client/src/Utils/stringUtils.js b/Client/src/Utils/stringUtils.js
deleted file mode 100644
index 43ae5ed54..000000000
--- a/Client/src/Utils/stringUtils.js
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * Helper function to get first letter capitalized string
- * @param {string} str String whose first letter is to be capitalized
- * @returns A string with first letter capitalized
- */
-export const capitalizeFirstLetter = (str) => {
- if (str === null || str === undefined) {
- return "";
- }
- if (typeof str !== "string") {
- throw new TypeError("Input must be a string");
- }
- if (str.length === 0) {
- return "";
- }
- return str.charAt(0).toUpperCase() + str.slice(1);
-};
diff --git a/Docker/dev/client.Dockerfile b/Docker/dev/client.Dockerfile
deleted file mode 100644
index 37b2bae74..000000000
--- a/Docker/dev/client.Dockerfile
+++ /dev/null
@@ -1,15 +0,0 @@
-FROM node:20-alpine AS build
-
-WORKDIR /app
-
-COPY ../../Client/package*.json ./
-
-RUN npm install
-
-COPY ../../Client .
-
-RUN npm run build-dev
-
-RUN npm install -g serve
-
-CMD ["serve","-s", "dist", "-l", "5173"]
diff --git a/Docker/dev/docker-compose.yaml b/Docker/dev/docker-compose.yaml
deleted file mode 100644
index f8b2c6936..000000000
--- a/Docker/dev/docker-compose.yaml
+++ /dev/null
@@ -1,40 +0,0 @@
-services:
- client:
- image: uptime_client:latest
- restart: always
- ports:
- - "5173:5173"
-
- depends_on:
- - server
- server:
- image: uptime_server:latest
- restart: always
- ports:
- - "5000:5000"
- env_file:
- - server.env
- depends_on:
- - redis
- - mongodb
- redis:
- image: uptime_redis:latest
- restart: always
- ports:
- - "6379:6379"
- volumes:
- - ./redis/data:/data
- healthcheck:
- test: ["CMD", "redis-cli", "ping"]
- interval: 30s
- timeout: 10s
- retries: 5
- start_period: 5s
- mongodb:
- image: uptime_database_mongo:latest
- restart: always
- command: ["mongod", "--quiet"]
- ports:
- - "27017:27017"
- volumes:
- - ./mongo/data:/data/db
diff --git a/Docker/dist/docker-compose.yaml b/Docker/dist/docker-compose.yaml
deleted file mode 100644
index a73b75dc6..000000000
--- a/Docker/dist/docker-compose.yaml
+++ /dev/null
@@ -1,45 +0,0 @@
-services:
- client:
- image: bluewaveuptime/uptime_client:latest
- restart: always
- environment:
- UPTIME_APP_API_BASE_URL: "http://localhost:5000/api/v1"
- ports:
- - "80:80"
- - "443:443"
- depends_on:
- - server
- server:
- image: bluewaveuptime/uptime_server:latest
- restart: always
- ports:
- - "5000:5000"
- depends_on:
- - redis
- - mongodb
- environment:
- - DB_CONNECTION_STRING=mongodb://mongodb:27017/uptime_db
- - REDIS_HOST=redis
- # volumes:
- # - /var/run/docker.sock:/var/run/docker.sock:ro
- redis:
- image: bluewaveuptime/uptime_redis:latest
- restart: always
- ports:
- - "6379:6379"
- volumes:
- - ./redis/data:/data
- healthcheck:
- test: ["CMD", "redis-cli", "ping"]
- interval: 30s
- timeout: 10s
- retries: 5
- start_period: 5s
- mongodb:
- image: bluewaveuptime/uptime_database_mongo:latest
- restart: always
- volumes:
- - ./mongo/data:/data/db
- command: ["mongod", "--quiet"]
- ports:
- - "27017:27017"
diff --git a/Docker/dist/server.Dockerfile b/Docker/dist/server.Dockerfile
deleted file mode 100644
index 3a9ed5907..000000000
--- a/Docker/dist/server.Dockerfile
+++ /dev/null
@@ -1,13 +0,0 @@
-FROM node:20-alpine
-
-WORKDIR /app
-
-COPY ../../Server/package*.json ./
-
-RUN npm install
-
-COPY ../../Server/ ./
-
-EXPOSE 5000
-
-CMD ["node", "index.js"]
\ No newline at end of file
diff --git a/Docker/prod/mongoDB.Dockerfile b/Docker/prod/mongoDB.Dockerfile
deleted file mode 100644
index 80c8b9c8f..000000000
--- a/Docker/prod/mongoDB.Dockerfile
+++ /dev/null
@@ -1,4 +0,0 @@
-FROM mongo
-COPY ./Docker/prod/mongo/init/create_users.js /docker-entrypoint-initdb.d/
-EXPOSE 27017
-CMD ["mongod"]
diff --git a/Docker/test/build_images.sh b/Docker/test/build_images.sh
deleted file mode 100755
index c879190bc..000000000
--- a/Docker/test/build_images.sh
+++ /dev/null
@@ -1,26 +0,0 @@
-#!/bin/bash
-
-# Change directory to root directory for correct Docker Context
-cd "$(dirname "$0")"
-cd ../..
-
-# Define an array of services and their Dockerfiles
-declare -A services=(
- ["uptime_client"]="./Docker/prod/client.Dockerfile"
- ["uptime_database_mongo"]="./Docker/prod/mongoDB.Dockerfile"
- ["uptime_redis"]="./Docker/prod/redis.Dockerfile"
- ["uptime_server"]="./Docker/prod/server.Dockerfile"
-)
-
-# Loop through each service and build the corresponding image
-for service in "${!services[@]}"; do
- docker build -f "${services[$service]}" -t "$service" .
-
- # Check if the build succeeded
- if [ $? -ne 0 ]; then
- echo "Error building $service image. Exiting..."
- exit 1
- fi
-done
-
-echo "All images built successfully"
\ No newline at end of file
diff --git a/Docker/test/mongo/init/create_users.js b/Docker/test/mongo/init/create_users.js
deleted file mode 100644
index 67a21f910..000000000
--- a/Docker/test/mongo/init/create_users.js
+++ /dev/null
@@ -1,16 +0,0 @@
-var username = process.env.USERNAME_ENV_VAR;
-var password = process.env.PASSWORD_ENV_VAR;
-
-db = db.getSiblingDB("uptime_db");
-
-db.createUser({
- user: username,
- pwd: password,
- roles: [
- {
- role: "readWrite",
- db: "uptime_db",
- },
- ],
-});
-print("User uptime_user created successfully");
diff --git a/Docker/test/mongoDB.Dockerfile b/Docker/test/mongoDB.Dockerfile
deleted file mode 100644
index 80c8b9c8f..000000000
--- a/Docker/test/mongoDB.Dockerfile
+++ /dev/null
@@ -1,4 +0,0 @@
-FROM mongo
-COPY ./Docker/prod/mongo/init/create_users.js /docker-entrypoint-initdb.d/
-EXPOSE 27017
-CMD ["mongod"]
diff --git a/Docker/test/prod/client.Dockerfile b/Docker/test/prod/client.Dockerfile
deleted file mode 100644
index 1619b5e41..000000000
--- a/Docker/test/prod/client.Dockerfile
+++ /dev/null
@@ -1,18 +0,0 @@
-FROM node:20-alpine AS build
-
-WORKDIR /app
-
-COPY ../../Client/package*.json ./
-
-RUN npm install
-
-COPY ../../Client .
-
-RUN npm run build
-
-FROM nginx:1.27.1-alpine
-
-COPY --from=build /app/dist /usr/share/nginx/html
-COPY --from=build /app/env.sh /docker-entrypoint.d/env.sh
-RUN chmod +x /docker-entrypoint.d/env.sh
-CMD ["nginx", "-g", "daemon off;"]
\ No newline at end of file
diff --git a/Docker/test/prod/docker-compose.yaml b/Docker/test/prod/docker-compose.yaml
deleted file mode 100644
index e262ef1a2..000000000
--- a/Docker/test/prod/docker-compose.yaml
+++ /dev/null
@@ -1,45 +0,0 @@
-services:
- client:
- image: uptime_client:latest
- environment:
- UPTIME_APP_API_BASE_URL: "https://checkmate-demo.bluewavelabs.ca/api/v1"
- ports:
- - "80:80"
- - "443:443"
- depends_on:
- - server
- volumes:
- - ./nginx/conf.d:/etc/nginx/conf.d/:ro
- - ./certbot/www:/var/www/certbot/:ro
- - ./certbot/conf/:/etc/nginx/ssl/:ro
-
- certbot:
- image: certbot/certbot:latest
- volumes:
- - ./certbot/www/:/var/www/certbot/:rw
- - ./certbot/conf/:/etc/letsencrypt/:rw
- server:
- image: uptime_server:latest
- ports:
- - "5000:5000"
- env_file:
- - server.env
- depends_on:
- - redis
- - mongodb
- redis:
- image: uptime_redis:latest
- ports:
- - "6379:6379"
- volumes:
- - ./redis/data:/data
- mongodb:
- image: uptime_database_mongo:latest
- command: ["mongod", "--quiet", "--auth"]
- ports:
- - "27017:27017"
- volumes:
- - ./mongo/data:/data/db
- - ./mongo/init/create_users.js:/docker-entrypoint-initdb.d/create_users.js
- env_file:
- - mongo.env
diff --git a/Docker/test/prod/mongo/init/create_users.js b/Docker/test/prod/mongo/init/create_users.js
deleted file mode 100644
index 67a21f910..000000000
--- a/Docker/test/prod/mongo/init/create_users.js
+++ /dev/null
@@ -1,16 +0,0 @@
-var username = process.env.USERNAME_ENV_VAR;
-var password = process.env.PASSWORD_ENV_VAR;
-
-db = db.getSiblingDB("uptime_db");
-
-db.createUser({
- user: username,
- pwd: password,
- roles: [
- {
- role: "readWrite",
- db: "uptime_db",
- },
- ],
-});
-print("User uptime_user created successfully");
diff --git a/Docker/test/prod/mongoDB.Dockerfile b/Docker/test/prod/mongoDB.Dockerfile
deleted file mode 100644
index 80c8b9c8f..000000000
--- a/Docker/test/prod/mongoDB.Dockerfile
+++ /dev/null
@@ -1,4 +0,0 @@
-FROM mongo
-COPY ./Docker/prod/mongo/init/create_users.js /docker-entrypoint-initdb.d/
-EXPOSE 27017
-CMD ["mongod"]
diff --git a/Docker/test/prod/nginx/conf.d/default.conf b/Docker/test/prod/nginx/conf.d/default.conf
deleted file mode 100644
index 98e1bd97d..000000000
--- a/Docker/test/prod/nginx/conf.d/default.conf
+++ /dev/null
@@ -1,69 +0,0 @@
-server {
- listen 80;
- listen [::]:80;
-
- server_name checkmate-demo.bluewavelabs.ca;
- server_tokens off;
-
- location /.well-known/acme-challenge/ {
- root /var/www/certbot;
- }
-
- location / {
- root /usr/share/nginx/html;
- index index.html index.htm;
- try_files $uri $uri/ /index.html;
- }
-
- location /api/ {
- proxy_pass http://server:5000/api/;
- proxy_http_version 1.1;
- proxy_set_header Host $host;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header X-Forwarded-Proto $scheme;
- }
-
- location /api-docs/ {
- proxy_pass http://server:5000/api-docs/;
- proxy_http_version 1.1;
- proxy_set_header Host $host;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header X-Forwarded-Proto $scheme;
- }
-}
-
-server {
- listen 443 default_server ssl http2;
- listen [::]:443 ssl http2;
-
- server_name checkmate-demo.bluewavelabs.ca;
-
- ssl_certificate /etc/nginx/ssl/live/checkmate-demo.bluewavelabs.ca/fullchain.pem;
- ssl_certificate_key /etc/nginx/ssl/live/checkmate-demo.bluewavelabs.ca/privkey.pem;
-
- location / {
- root /usr/share/nginx/html;
- index index.html index.htm;
- try_files $uri $uri/ /index.html;
- }
-
- location /api/ {
- proxy_pass http://server:5000/api/;
- proxy_http_version 1.1;
- proxy_set_header Host $host;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header X-Forwarded-Proto $scheme;
- }
-
- location /api-docs/ {
- proxy_pass http://server:5000/api-docs/;
- proxy_http_version 1.1;
- proxy_set_header Host $host;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header X-Forwarded-Proto $scheme;
- }
-}
diff --git a/README.md b/README.md
index c37adfc6a..0830cc3b7 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,3 @@
-
-

@@ -10,7 +8,7 @@


[](https://www.bestpractices.dev/projects/9901)
-
+[](https://deepwiki.com/bluewave-labs/checkmate)
@@ -18,27 +16,41 @@

-Checkmate is an open source monitoring tool used to track the operational status and performance of servers and websites. It regularly checks whether a server/website is accessible and performs optimally, providing real-time alerts and reports on the monitored services' availability, downtime, and response time.
+This repository contains both the frontend and the backend of Checkmate, an open-source, self-hosted monitoring tool for tracking server hardware, uptime, response times, and incidents in real-time with beautiful visualizations. Checkmate regularly checks whether a server/website is accessible and performs optimally, providing real-time alerts and reports on the monitored services' availability, downtime, and response time.
-Checkmate also has an agent, called [Capture](https://github.com/bluewave-labs/capture), to retrieve data from remote servers. While Capture is not required to run Checkmate, it provides additional insigths about your servers' CPU, RAM, disk and temperature status.
+Checkmate also has an agent, called [Capture](https://github.com/bluewave-labs/capture), to retrieve data from remote servers. While Capture is not required to run Checkmate, it provides additional insights about your servers' CPU, RAM, disk, and temperature status.
-Checkmate has ben stress tested with 1000+ active monitors without any particular issues or performance bottlenecks.
+Checkmate has been stress-tested with 1000+ active monitors without any particular issues or performance bottlenecks.
-We **love** what we are building here, and we contibuously learn a few things about Reactjs, Nodejs, MongoDB and Docker while building Checkmate.
+We **love** what we are building here, and we continuously learn a few things about Reactjs, Nodejs, MongoDB, and Docker while building Checkmate.
## 📦 Demo
-See [Checkmate](https://checkmate-demo.bluewavelabs.ca/) in action. The username is uptimedemo@demo.com and the password is Demouser1! (just a note that we update the demo server from time to time, so if it doesn't work for you, please ping us on Discussions channel).
+You can see the latest build of [Checkmate](https://checkmate-demo.bluewavelabs.ca/) in action. The username is uptimedemo@demo.com and the password is Demouser1! (just a note that we update the demo server from time to time, so if it doesn't work for you, please ping us on the Discussions channel).
## 🔗 User's guide
-Usage instructions can be found [here](https://bluewavelabs.gitbook.io/checkmate). It's still WIP and some of the information there might be outdated. Rest assured, we are doing our best! :)
+Usage instructions can be found [here](https://docs.checkmate.so/). It's still WIP and some of the information there might be outdated as we continuously add features weekly. Rest assured, we are doing our best! :)
## 🛠️ Installation
-See installation instructions in [Checkmate documentation portal](https://bluewavelabs.gitbook.io/checkmate/quickstart). Alternatively, you can also use [Coolify](https://coolify.io/) for a one click Docker deployment. If you would like to monitor your server infrastructure, you'll need [Capture agent](https://github.com/bluewave-labs/capture). Capture repository also contains the installation instructions.
+See installation instructions in [Checkmate documentation portal](https://docs.checkmate.so/quickstart). Alternatively, you can also use [Coolify](https://coolify.io/) or [Elestio](https://elest.io/open-source/checkmate) for a one-click Docker deployment. If you would like to monitor your server infrastructure, you'll need [Capture agent](https://github.com/bluewave-labs/capture). Capture repository also contains the installation instructions.
-## 💚 Questions & ideas
+## 🏁 Translations
+
+If you would like to use Checkmate in your language, please [go to this page](https://poeditor.com/join/project/lRUoGZFCsJ) and register for the language you would like to translate Checkmate to.
+
+## 🚀 Performance
+
+Thanks to extensive optimizations, Checkmate operates with an exceptionally small memory footprint, requiring minimal memory and CPU resources. Here’s the memory usage of a Node.js instance running on a server that monitors 323 servers every minute:
+
+
+
+You can see the memory footprint of MongoDB and Redis on the same server (398Mb and 15Mb) for the same amount of servers:
+
+
+
+## 💚 Questions & Ideas
If you have any questions, suggestions or comments, please use our [Discord channel](https://discord.gg/NAb6H3UTjK). We've also launched our [Discussions](https://github.com/bluewave-labs/bluewave-uptime/discussions) page! Feel free to ask questions or share your ideas—we'd love to hear from you!
@@ -51,24 +63,23 @@ If you have any questions, suggestions or comments, please use our [Discord chan
- Docker monitoring
- Ping monitoring
- SSL monitoring
+- Port monitoring
- Incidents at a glance
- E-mail notifications
- Scheduled maintenance
**Short term roadmap:**
-- Port monitoring (**complete**, waiting to be deployed to stable version) https://github.com/bluewave-labs/Checkmate/issues/1476
-- Global (distributed) uptime checking on Solana network (**in progress**) https://github.com/bluewave-labs/Checkmate/issues/1593
-- Status pages (**in progress**) https://github.com/bluewave-labs/Checkmate/issues/1131
+- Status pages (**in progress**) https://github.com/bluewave-labs/Checkmate/issues/1131
- Translations (i18n) (**in progress**)
- Better notification options (Webhooks, Discord, Telegram, Slack) (**in progress**) https://github.com/bluewave-labs/Checkmate/issues/1545
-- Command line interface (CLI) (**in progress**) https://github.com/bluewave-labs/Checkmate/issues/1558
-- JSON query monitoring https://github.com/bluewave-labs/Checkmate/issues/1573
+- JSON query monitoring (**in progress**) https://github.com/bluewave-labs/Checkmate/issues/1573
- Tagging/grouping monitors https://github.com/bluewave-labs/Checkmate/issues/1546
- More configuration options
- DNS monitoring
## 🏗️ Screenshots
+
@@ -88,23 +99,27 @@ If you have any questions, suggestions or comments, please use our [Discord chan
- [Recharts](https://recharts.org)
- Lots of other open source components!
-## A few links
+## A few links
-- If you would like to support us, please consider giving it a ⭐ and click on "watch".
+- If you would like to support us, please consider giving it a ⭐ and click on "watch".
- Have a question or suggestion for the roadmap/featureset? Check our [Discord channel](https://discord.gg/NAb6H3UTjK) or [Discussions](https://github.com/bluewave-labs/checkmate/discussions) forum.
- Need a ping when there's a new release? Use [Newreleases](https://newreleases.io/), a free service to track releases.
- Watch a Checkmate [installation and usage video](https://www.youtube.com/watch?v=GfFOc0xHIwY)
## 🤝 Contributing
-We pride ourselves on building strong connections with contributors at every level. Despite being a young project, Checkmate has already earned 3300 stars and attracted 40+ contributors from around the globe. So, don’t hold back — jump in, contribute and learn with us!
+We are [Alex](http://github.com/ajhollid) (team lead), [Vishnu](http://github.com/vishnusn77), [Mohadeseh](http://github.com/mohicody), [Gorkem](http://github.com/gorkem-bwl/), [Owaise](http://github.com/Owaiseimdad), [Aryaman](https://github.com/Br0wnHammer) and [Mert](https://github/com/mertssmnoglu) helping individuals and businesses monitor their infra and servers.
+
+We pride ourselves on building strong connections with contributors at every level. Despite being a young project, Checkmate has already earned 5000+ stars and attracted 60 contributors from around the globe.
+
+Our repo is starred by employees from **Google, Microsoft, Intel, Cisco, Tencent, Electronic Arts, ByteDance, JP Morgan Chase, Deloitte, Accenture, Foxconn, Broadcom, China Telecom, Barclays, Capgemini, Wipro, Cloudflare, Dassault Systèmes and NEC**, so don’t hold back — jump in, contribute and learn with us!
Here's how you can contribute:
0. Star this repo :)
-1. Check [Contributor's guideline](https://github.com/bluewave-labs/bluewave-uptime/blob/master/CONTRIBUTING.md). First timers are encouraged to check `good-first-issue` tag.
-2. Optionally, read [project structure](https://bluewavelabs.gitbook.io/checkmate/developers-guide/general-project-structure) and [high level overview](https://bluewavelabs.gitbook.io/checkmate/developers-guide/high-level-overview).
-3. Have a look at our Figma designs [here](https://www.figma.com/design/RPSfaw66HjzSwzntKcgDUV/Uptime-Genie?node-id=0-1&t=WqOFv9jqNTFGItpL-1) if you are going to use one of our designs. We encourage you to copy to your own Figma page, then work on it as it is read-only.
+1. Check [Contributor's guideline](https://github.com/bluewave-labs/Checkmate/blob/develop/CONTRIBUTING.md). First timers are encouraged to check `good-first-issue` tag.
+2. Check [project structure](https://docs.checkmate.so/developers-guide/general-project-structure) and [high level overview](https://bluewavelabs.gitbook.io/checkmate/developers-guide/high-level-overview).
+3. Read a detailed structure of [Checkmate](https://deepwiki.com/bluewave-labs/Checkmate) if you would like to deep dive into the architecture.
4. Open an issue if you believe you've encountered a bug.
5. Check for good-first-issue's if you are a newcomer.
6. Make a pull request to add new features/make quality-of-life improvements/fix bugs.
@@ -113,19 +128,14 @@ Here's how you can contribute:
-
+Thanks to [Gitbook](https://gitbook.io/) for giving us a free tier for their documentation platform, and [Poeditor](https://poeditor.com/) providing us a free account to use their i18n services. If you would like to sponsor Checkmate, please send an email to hello@bluewavelabs.ca
[](https://star-history.com/#bluewave-labs/bluewave-uptime&Date)
Also check other developer and contributor-friendly projects of BlueWave:
-- [DataRoom](https://github.com/bluewave-labs/bluewave-dataroom), an secure file sharing application, aka dataroom.
-- [BlueWave HRM](https://github.com/bluewave-labs/bluewave-hrm), a complete Human Resource Management platform.
-- [Guidefox](https://github.com/bluewave-labs/guidefox), an application that helps new users learn how to use your product via hints, tours, popups and banners.
- [VerifyWise](https://github.com/bluewave-labs/verifywise), the first open source AI governance platform.
-
- since 14 Jan, 2025
+- [DataRoom](https://github.com/bluewave-labs/bluewave-dataroom), an secure file sharing application, aka dataroom.
+- [Guidefox](https://github.com/bluewave-labs/guidefox), an application that helps new users learn how to use your product via hints, tours, popups and banners.
diff --git a/SECURITY.md b/SECURITY.md
index 6aa64730a..58257c9c4 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -1,6 +1,4 @@
# Security Policy
-If you find a vulnerability, send it to hello@bluewavelabs.ca
-
-Please do not create an issue for security vulnerabilities.
+If you find a vulnerability, [create an issue here](https://github.com/bluewave-labs/checkmate/security/advisories/new).
diff --git a/Server/controllers/distributedUptimeController.js b/Server/controllers/distributedUptimeController.js
deleted file mode 100644
index ce4ee2df5..000000000
--- a/Server/controllers/distributedUptimeController.js
+++ /dev/null
@@ -1,18 +0,0 @@
-import { handleError } from "./controllerUtils.js";
-import { successMessages } from "../utils/messages.js";
-
-const SERVICE_NAME = "DistributedUptimeQueueController";
-
-class DistributedUptimeController {
- constructor() {}
-
- async resultsCallback(req, res, next) {
- try {
- console.log(req.body);
- res.status(200).json({ message: "OK" });
- } catch (error) {
- throw handleError(error, SERVICE_NAME, "resultsCallback");
- }
- }
-}
-export default DistributedUptimeController;
diff --git a/Server/controllers/statusPageController.js b/Server/controllers/statusPageController.js
deleted file mode 100644
index a4ceb8039..000000000
--- a/Server/controllers/statusPageController.js
+++ /dev/null
@@ -1,54 +0,0 @@
-import { handleError, handleValidationError } from "./controllerUtils.js";
-import {
- createStatusPageBodyValidation,
- getStatusPageParamValidation,
-} from "../validation/joi.js";
-import { successMessages } from "../utils/messages.js";
-
-const SERVICE_NAME = "statusPageController";
-
-class StatusPageController {
- constructor(db) {
- this.db = db;
- }
-
- createStatusPage = async (req, res, next) => {
- try {
- await createStatusPageBodyValidation.validateAsync(req.body);
- } catch (error) {
- next(handleValidationError(error, SERVICE_NAME));
- return;
- }
-
- try {
- const statusPage = await this.db.createStatusPage(req.body);
- return res.success({
- msg: successMessages.STATUS_PAGE_CREATE,
- data: statusPage,
- });
- } catch (error) {
- next(handleError(error, SERVICE_NAME, "createStatusPage"));
- }
- };
- getStatusPageByUrl = async (req, res, next) => {
- try {
- await getStatusPageParamValidation.validateAsync(req.params);
- } catch (error) {
- next(handleValidationError(error, SERVICE_NAME));
- return;
- }
-
- try {
- const { url } = req.params;
- const statusPage = await this.db.getStatusPageByUrl(url);
- return res.success({
- msg: successMessages.STATUS_PAGE_BY_URL,
- data: statusPage,
- });
- } catch (error) {
- next(handleError(error, SERVICE_NAME, "getStatusPage"));
- }
- };
-}
-
-export default StatusPageController;
diff --git a/Server/db/FakeDb.js b/Server/db/FakeDb.js
deleted file mode 100644
index 4e9b32992..000000000
--- a/Server/db/FakeDb.js
+++ /dev/null
@@ -1,138 +0,0 @@
-// **************************
-// The idea here is to provide a layer of abstraction between the database and whoever is using it.
-// Instead of directly calling mongoose methods, we can call the methods on the DB object.
-// If this were Typescript or Java or Golang an interface would be implemented to ensure the methods are available.
-// But we do the best we can with Javascript.
-//
-// If the methods are consistent all we have to do to swap out one DB for another is simply change the import.
-//
-// Example:
-// We start with the fake DB:
-//
-// const db = require("../db/FakeDb");
-// const monitors = await db.getAllMonitors();
-//
-// And when we want to swtich to a real DB, all we have to do is swap the import
-//
-// const db = require("../db/MongoDb");
-// const monitors = await db.getAllMonitors();
-//
-// The rest of the code is the same, as all the `db` methods are standardized.
-// **************************
-
-const Monitor = require("./models/Monitor");
-const UserModel = require("./models/User");
-const bcrypt = require("bcrypt");
-
-let FAKE_MONITOR_DATA = [];
-const USERS = [];
-
-const connect = async () => {
- try {
- await console.log("Connected to FakeDB");
- } catch (error) {
- console.error(error);
- }
-};
-
-const insertUser = async (req, res) => {
- try {
- const newUser = new UserModel({ ...req.body });
- const salt = await bcrypt.genSalt(10); //genSalt is asynchronous, need to wait
- newUser.password = await bcrypt.hash(newUser.password, salt); // hash is also async, need to eitehr await or use hashSync
- USERS.push(newUser);
- const userToReturn = { ...newUser._doc };
- delete userToReturn.password;
- return userToReturn;
- } catch (error) {
- throw error;
- }
-};
-
-const getUserByEmail = async (req, res) => {
- const email = req.body.email;
- try {
- const idx = USERS.findIndex((user) => {
- return user.email === email;
- });
- if (idx === -1) {
- return null;
- }
- return USERS[idx];
- } catch (error) {
- throw new Error(`User with email ${email} not found`);
- }
-};
-
-const getAllMonitors = async () => {
- return FAKE_MONITOR_DATA;
-};
-
-const getMonitorById = async (monitorId) => {
- const idx = FAKE_MONITOR_DATA.findIndex((monitor) => {
- return monitor.id === monitorId;
- });
- if (idx === -1) {
- throw new Error(`Monitor with id ${monitorId} not found`);
- }
- return FAKE_MONITOR_DATA[idx];
-};
-
-const getMonitorsByUserId = async (userId) => {
- const userMonitors = FAKE_MONITOR_DATA.filter((monitor) => {
- return monitor.userId === userId;
- });
-
- if (userMonitors.length === 0) {
- throw new Error(`Monitors for user ${userId} not found`);
- }
- return userMonitors;
-};
-
-const createMonitor = async (req, res) => {
- const monitor = new Monitor(req.body);
- monitor.createdAt = Date.now();
- monitor.updatedAt = Date.now();
- FAKE_MONITOR_DATA.push(monitor);
- return monitor;
-};
-
-const deleteMonitor = async (req, res) => {
- const monitorId = req.params.monitorId;
- try {
- const monitor = getMonitorById(monitorId);
- FAKE_MONITOR_DATA = FAKE_MONITOR_DATA.filter((monitor) => {
- return monitor.id !== monitorId;
- });
- return monitor;
- } catch (error) {
- throw error;
- }
-};
-
-const editMonitor = async (req, res) => {
- const monitorId = req.params.monitorId;
- const idx = FAKE_MONITOR_DATA.findIndex((monitor) => {
- return monitor._id.toString() === monitorId;
- });
- const oldMonitor = FAKE_MONITOR_DATA[idx];
- const editedMonitor = new Monitor({ ...req.body });
- editedMonitor._id = oldMonitor._id;
- editedMonitor.userId = oldMonitor.userId;
- editedMonitor.updatedAt = Date.now();
- editedMonitor.createdAt = oldMonitor.createdAt;
- FAKE_MONITOR_DATA[idx] = editedMonitor;
- return FAKE_MONITOR_DATA[idx];
-};
-
-module.exports = {
- connect,
- insertUser,
- getUserByEmail,
- getAllMonitors,
- getMonitorById,
- getMonitorsByUserId,
- createMonitor,
- deleteMonitor,
- editMonitor,
-};
diff --git a/Server/db/models/AppSettings.js b/Server/db/models/AppSettings.js
deleted file mode 100644
index c4faa0881..000000000
--- a/Server/db/models/AppSettings.js
+++ /dev/null
@@ -1,91 +0,0 @@
-import mongoose from "mongoose";
-
-const AppSettingsSchema = mongoose.Schema(
- {
- apiBaseUrl: {
- type: String,
- required: true,
- default: "http://localhost:5000/api/v1",
- },
- logLevel: {
- type: String,
- default: "debug",
- enum: ["debug", "none", "error", "warn"],
- },
- clientHost: {
- type: String,
- required: true,
- default: "http://localhost:5173",
- },
- jwtSecret: {
- type: String,
- required: true,
- default: "my_secret",
- },
- refreshTokenSecret: {
- type: String,
- required: true,
- default: "my_refresh_secret",
- },
- dbType: {
- type: String,
- required: true,
- default: "MongoDB",
- },
- dbConnectionString: {
- type: String,
- required: true,
- default: "mongodb://localhost:27017/uptime_db",
- },
- redisHost: {
- type: String,
- required: true,
- default: "127.0.0.1",
- },
- redisPort: {
- type: Number,
- default: "6379",
- },
- jwtTTL: {
- type: String,
- required: true,
- default: "2h",
- },
- refreshTokenTTL: {
- type: String,
- required: true,
- default: "7d",
- },
- pagespeedApiKey: {
- type: String,
- default: "",
- },
- systemEmailHost: {
- type: String,
- default: "smtp.gmail.com",
- },
- systemEmailPort: {
- type: Number,
- default: 465,
- },
- systemEmailAddress: {
- type: String,
- default: "",
- },
- systemEmailPassword: {
- type: String,
- default: "",
- },
- singleton: {
- type: Boolean,
- required: true,
- unique: true,
- default: true,
- },
- },
- {
- timestamps: true,
- }
-);
-
-export default mongoose.model("AppSettings", AppSettingsSchema);
diff --git a/Server/db/models/DistributedUptimeCheck.js b/Server/db/models/DistributedUptimeCheck.js
deleted file mode 100644
index 0c7c25de3..000000000
--- a/Server/db/models/DistributedUptimeCheck.js
+++ /dev/null
@@ -1,15 +0,0 @@
-import mongoose from "mongoose";
-import { BaseCheckSchema } from "./Check.js";
-
-const DistributedUptimeCheckSchema = mongoose.Schema(
- {
- ...BaseCheckSchema.obj,
- },
- { timestamps: true }
-);
-
-DistributedUptimeCheckSchema.index({ createdAt: 1 });
-DistributedUptimeCheckSchema.index({ monitorId: 1, createdAt: 1 });
-DistributedUptimeCheckSchema.index({ monitorId: 1, createdAt: -1 });
-
-export default mongoose.model("DistributedUptimeCheck", DistributedUptimeCheckSchema);
diff --git a/Server/db/models/StatusPage.js b/Server/db/models/StatusPage.js
deleted file mode 100644
index 1169d4661..000000000
--- a/Server/db/models/StatusPage.js
+++ /dev/null
@@ -1,42 +0,0 @@
-import mongoose from "mongoose";
-
-const StatusPageSchema = mongoose.Schema(
- {
- companyName: {
- type: String,
- required: true,
- default: "",
- },
- url: {
- type: String,
- unique: true,
- required: true,
- default: "",
- },
- timezone: {
- type: String,
- required: true,
- default: "America/Toronto",
- },
- color: {
- type: String,
- required: true,
- default: "#4169E1",
- },
- theme: {
- type: String,
- required: true,
- default: "light",
- },
- monitors: [
- {
- type: mongoose.Schema.Types.ObjectId,
- ref: "Monitor",
- required: true,
- },
- ],
- },
- { timestamps: true }
-);
-
-export default mongoose.model("StatusPage", StatusPageSchema);
diff --git a/Server/db/mongo/modules/monitorModuleQueries.js b/Server/db/mongo/modules/monitorModuleQueries.js
deleted file mode 100644
index cdbcd51d8..000000000
--- a/Server/db/mongo/modules/monitorModuleQueries.js
+++ /dev/null
@@ -1,535 +0,0 @@
-const buildUptimeDetailsPipeline = (monitor, dates, dateString) => {
- return [
- {
- $match: {
- monitorId: monitor._id,
- },
- },
- {
- $sort: {
- createdAt: 1,
- },
- },
- {
- $facet: {
- aggregateData: [
- {
- $group: {
- _id: null,
- avgResponseTime: {
- $avg: "$responseTime",
- },
- lastCheck: {
- $last: "$$ROOT",
- },
- totalChecks: {
- $sum: 1,
- },
- },
- },
- ],
- uptimeStreak: [
- {
- $sort: {
- createdAt: -1,
- },
- },
- {
- $group: {
- _id: null,
- checks: { $push: "$$ROOT" },
- },
- },
- {
- $project: {
- streak: {
- $reduce: {
- input: "$checks",
- initialValue: { checks: [], foundFalse: false },
- in: {
- $cond: [
- {
- $and: [
- { $not: "$$value.foundFalse" }, // stop reducing if a false check has been found
- { $eq: ["$$this.status", true] }, // continue reducing if current check true
- ],
- },
- // true case
- {
- checks: { $concatArrays: ["$$value.checks", ["$$this"]] },
- foundFalse: false, // Add the check to the streak
- },
- // false case
- {
- checks: "$$value.checks",
- foundFalse: true, // Mark that we found a false
- },
- ],
- },
- },
- },
- },
- },
- ],
- // For the response time chart, should return checks for date window
- // Grouped by: {day: hour}, {week: day}, {month: day}
- groupedChecks: [
- {
- $match: {
- createdAt: { $gte: dates.start, $lte: dates.end },
- },
- },
- {
- $group: {
- _id: {
- $dateToString: {
- format: dateString,
- date: "$createdAt",
- },
- },
- avgResponseTime: {
- $avg: "$responseTime",
- },
- totalChecks: {
- $sum: 1,
- },
- },
- },
- {
- $sort: {
- _id: 1,
- },
- },
- ],
- // Average response time for the date window
- groupAvgResponseTime: [
- {
- $match: {
- createdAt: { $gte: dates.start, $lte: dates.end },
- },
- },
- {
- $group: {
- _id: null,
- avgResponseTime: {
- $avg: "$responseTime",
- },
- },
- },
- ],
- // All UpChecks for the date window
- upChecks: [
- {
- $match: {
- status: true,
- createdAt: { $gte: dates.start, $lte: dates.end },
- },
- },
- {
- $group: {
- _id: null,
- avgResponseTime: {
- $avg: "$responseTime",
- },
- totalChecks: {
- $sum: 1,
- },
- },
- },
- ],
- // Up checks grouped by: {day: hour}, {week: day}, {month: day}
- groupedUpChecks: [
- {
- $match: {
- status: true,
- createdAt: { $gte: dates.start, $lte: dates.end },
- },
- },
- {
- $group: {
- _id: {
- $dateToString: {
- format: dateString,
- date: "$createdAt",
- },
- },
- totalChecks: {
- $sum: 1,
- },
- avgResponseTime: {
- $avg: "$responseTime",
- },
- },
- },
- {
- $sort: { _id: 1 },
- },
- ],
- // All down checks for the date window
- downChecks: [
- {
- $match: {
- status: false,
- createdAt: { $gte: dates.start, $lte: dates.end },
- },
- },
- {
- $group: {
- _id: null,
- avgResponseTime: {
- $avg: "$responseTime",
- },
- totalChecks: {
- $sum: 1,
- },
- },
- },
- ],
- // Down checks grouped by: {day: hour}, {week: day}, {month: day} for the date window
- groupedDownChecks: [
- {
- $match: {
- status: false,
- createdAt: { $gte: dates.start, $lte: dates.end },
- },
- },
- {
- $group: {
- _id: {
- $dateToString: {
- format: dateString,
- date: "$createdAt",
- },
- },
- totalChecks: {
- $sum: 1,
- },
- avgResponseTime: {
- $avg: "$responseTime",
- },
- },
- },
- {
- $sort: { _id: 1 },
- },
- ],
- },
- },
- {
- $project: {
- uptimeStreak: {
- $cond: [
- { $eq: [{ $size: { $first: "$uptimeStreak.streak.checks" } }, 0] },
- 0,
- {
- $subtract: [
- new Date(),
- {
- $last: { $first: "$uptimeStreak.streak.checks.createdAt" },
- },
- ],
- },
- ],
- },
- avgResponseTime: {
- $arrayElemAt: ["$aggregateData.avgResponseTime", 0],
- },
- totalChecks: {
- $arrayElemAt: ["$aggregateData.totalChecks", 0],
- },
- latestResponseTime: {
- $arrayElemAt: ["$aggregateData.lastCheck.responseTime", 0],
- },
- timeSinceLastCheck: {
- $let: {
- vars: {
- lastCheck: {
- $arrayElemAt: ["$aggregateData.lastCheck", 0],
- },
- },
- in: {
- $cond: [
- {
- $ifNull: ["$$lastCheck", false],
- },
- {
- $subtract: [new Date(), "$$lastCheck.createdAt"],
- },
- 0,
- ],
- },
- },
- },
- groupedChecks: "$groupedChecks",
- groupedAvgResponseTime: {
- $arrayElemAt: ["$groupAvgResponseTime", 0],
- },
- upChecks: {
- $arrayElemAt: ["$upChecks", 0],
- },
- groupedUpChecks: "$groupedUpChecks",
- downChecks: {
- $arrayElemAt: ["$downChecks", 0],
- },
- groupedDownChecks: "$groupedDownChecks",
- },
- },
- ];
-};
-
-const buildHardwareDetailsPipeline = (monitor, dates, dateString) => {
- return [
- {
- $match: {
- monitorId: monitor._id,
- createdAt: { $gte: dates.start, $lte: dates.end },
- },
- },
- {
- $sort: {
- createdAt: 1,
- },
- },
- {
- $facet: {
- aggregateData: [
- {
- $group: {
- _id: null,
- latestCheck: {
- $last: "$$ROOT",
- },
- totalChecks: {
- $sum: 1,
- },
- },
- },
- ],
- upChecks: [
- {
- $match: {
- status: true,
- },
- },
- {
- $group: {
- _id: null,
- totalChecks: {
- $sum: 1,
- },
- },
- },
- ],
- checks: [
- {
- $limit: 1,
- },
- {
- $project: {
- diskCount: {
- $size: "$disk",
- },
- },
- },
- {
- $lookup: {
- from: "hardwarechecks",
- let: {
- diskCount: "$diskCount",
- },
- pipeline: [
- {
- $match: {
- $expr: {
- $and: [
- { $eq: ["$monitorId", monitor._id] },
- { $gte: ["$createdAt", dates.start] },
- { $lte: ["$createdAt", dates.end] },
- ],
- },
- },
- },
- {
- $group: {
- _id: {
- $dateToString: {
- format: dateString,
- date: "$createdAt",
- },
- },
- avgCpuUsage: {
- $avg: "$cpu.usage_percent",
- },
- avgMemoryUsage: {
- $avg: "$memory.usage_percent",
- },
- avgTemperatures: {
- $push: {
- $ifNull: ["$cpu.temperature", [0]],
- },
- },
- disks: {
- $push: "$disk",
- },
- },
- },
- {
- $project: {
- _id: 1,
- avgCpuUsage: 1,
- avgMemoryUsage: 1,
- avgTemperature: {
- $map: {
- input: {
- $range: [
- 0,
- {
- $size: {
- // Handle null temperatures array
- $ifNull: [
- { $arrayElemAt: ["$avgTemperatures", 0] },
- [0], // Default to single-element array if null
- ],
- },
- },
- ],
- },
- as: "index",
- in: {
- $avg: {
- $map: {
- input: "$avgTemperatures",
- as: "tempArray",
- in: {
- $ifNull: [
- { $arrayElemAt: ["$$tempArray", "$$index"] },
- 0, // Default to 0 if element is null
- ],
- },
- },
- },
- },
- },
- },
- disks: {
- $map: {
- input: {
- $range: [0, "$$diskCount"],
- },
- as: "diskIndex",
- in: {
- name: {
- $concat: [
- "disk",
- {
- $toString: "$$diskIndex",
- },
- ],
- },
- readSpeed: {
- $avg: {
- $map: {
- input: "$disks",
- as: "diskArray",
- in: {
- $arrayElemAt: [
- "$$diskArray.read_speed_bytes",
- "$$diskIndex",
- ],
- },
- },
- },
- },
- writeSpeed: {
- $avg: {
- $map: {
- input: "$disks",
- as: "diskArray",
- in: {
- $arrayElemAt: [
- "$$diskArray.write_speed_bytes",
- "$$diskIndex",
- ],
- },
- },
- },
- },
- totalBytes: {
- $avg: {
- $map: {
- input: "$disks",
- as: "diskArray",
- in: {
- $arrayElemAt: [
- "$$diskArray.total_bytes",
- "$$diskIndex",
- ],
- },
- },
- },
- },
- freeBytes: {
- $avg: {
- $map: {
- input: "$disks",
- as: "diskArray",
- in: {
- $arrayElemAt: ["$$diskArray.free_bytes", "$$diskIndex"],
- },
- },
- },
- },
- usagePercent: {
- $avg: {
- $map: {
- input: "$disks",
- as: "diskArray",
- in: {
- $arrayElemAt: [
- "$$diskArray.usage_percent",
- "$$diskIndex",
- ],
- },
- },
- },
- },
- },
- },
- },
- },
- },
- ],
- as: "hourlyStats",
- },
- },
- {
- $unwind: "$hourlyStats",
- },
- {
- $replaceRoot: {
- newRoot: "$hourlyStats",
- },
- },
- ],
- },
- },
- {
- $project: {
- aggregateData: {
- $arrayElemAt: ["$aggregateData", 0],
- },
- upChecks: {
- $arrayElemAt: ["$upChecks", 0],
- },
- checks: {
- $sortArray: {
- input: "$checks",
- sortBy: { _id: 1 },
- },
- },
- },
- },
- ];
-};
-
-export { buildUptimeDetailsPipeline, buildHardwareDetailsPipeline };
diff --git a/Server/db/mongo/modules/statusPageModule.js b/Server/db/mongo/modules/statusPageModule.js
deleted file mode 100644
index 194287448..000000000
--- a/Server/db/mongo/modules/statusPageModule.js
+++ /dev/null
@@ -1,40 +0,0 @@
-import StatusPage from "../../models/StatusPage.js";
-import { errorMessages } from "../../../utils/messages.js";
-
-const SERVICE_NAME = "statusPageModule";
-
-const createStatusPage = async (statusPageData) => {
- try {
- const statusPage = new StatusPage({ ...statusPageData });
- await statusPage.save();
- return statusPage;
- } catch (error) {
- if (error?.code === 11000) {
- // Handle duplicate URL errors
- error.status = 400;
- error.message = errorMessages.STATUS_PAGE_URL_NOT_UNIQUE;
- }
- error.service = SERVICE_NAME;
- error.method = "createStatusPage";
- throw error;
- }
-};
-
-const getStatusPageByUrl = async (url) => {
- try {
- const statusPage = await StatusPage.findOne({ url });
- if (statusPage === null || statusPage === undefined) {
- const error = new Error(errorMessages.STATUS_PAGE_NOT_FOUND);
- error.status = 404;
-
- throw error;
- }
- return statusPage;
- } catch (error) {
- error.service = SERVICE_NAME;
- error.method = "getStatusPageByUrl";
- throw error;
- }
-};
-
-export { createStatusPage, getStatusPageByUrl };
diff --git a/Server/db/mongo/utils/seedDb.js b/Server/db/mongo/utils/seedDb.js
deleted file mode 100644
index cd4abb8d5..000000000
--- a/Server/db/mongo/utils/seedDb.js
+++ /dev/null
@@ -1,57 +0,0 @@
-import Monitor from "../../models/Monitor.js";
-import Check from "../../models/Check.js";
-
-const generateRandomUrl = () => {
- const domains = ["example.com", "test.org", "demo.net", "sample.io", "mock.dev"];
- const paths = ["api", "status", "health", "ping", "check"];
- return `https://${domains[Math.floor(Math.random() * domains.length)]}/${paths[Math.floor(Math.random() * paths.length)]}`;
-};
-
-const generateChecks = (monitorId, teamId, count) => {
- const checks = [];
- const endTime = new Date(Date.now() - 10 * 60 * 1000); // 10 minutes ago
- const startTime = new Date(endTime - count * 60 * 1000); // count minutes before endTime
-
- for (let i = 0; i < count; i++) {
- const timestamp = new Date(startTime.getTime() + i * 60 * 1000);
- const status = Math.random() > 0.05; // 95% chance of being up
-
- checks.push({
- monitorId,
- teamId,
- status,
- responseTime: Math.floor(Math.random() * 1000), // Random response time between 0-1000ms
- createdAt: timestamp,
- updatedAt: timestamp,
- });
- }
-
- return checks;
-};
-
-const seedDb = async (userId, teamId) => {
- try {
- console.log("Deleting all monitors and checks");
- await Monitor.deleteMany({});
- await Check.deleteMany({});
- console.log("Adding monitors");
- for (let i = 0; i < 300; i++) {
- const monitor = await Monitor.create({
- name: `Monitor ${i}`,
- url: generateRandomUrl(),
- type: "http",
- userId,
- teamId,
- interval: 60000,
- active: false,
- });
- console.log(`Adding monitor and checks for monitor ${i}`);
- const checks = generateChecks(monitor._id, teamId, 10000);
- await Check.insertMany(checks);
- }
- } catch (error) {
- console.error(error);
- }
-};
-
-export default seedDb;
diff --git a/Server/middleware/handleErrors.js b/Server/middleware/handleErrors.js
deleted file mode 100644
index fa9af4c0b..000000000
--- a/Server/middleware/handleErrors.js
+++ /dev/null
@@ -1,20 +0,0 @@
-import logger from "../utils/logger.js";
-import { errorMessages } from "../utils/messages.js";
-
-const handleErrors = (error, req, res, next) => {
- const status = error.status || 500;
- const message = error.message || errorMessages.FRIENDLY_ERROR;
- const service = error.service || errorMessages.UNKNOWN_SERVICE;
- logger.error({
- message: message,
- service: service,
- method: error.method,
- stack: error.stack,
- });
- res.error({
- status,
- msg: message,
- });
-};
-
-export { handleErrors };
diff --git a/Server/middleware/responseHandler.js b/Server/middleware/responseHandler.js
deleted file mode 100644
index 061422f50..000000000
--- a/Server/middleware/responseHandler.js
+++ /dev/null
@@ -1,20 +0,0 @@
-const responseHandler = (req, res, next) => {
- res.success = ({ status = 200, msg = "OK", data = null }) => {
- return res.status(status).json({
- success: true,
- msg: msg,
- data: data,
- });
- };
-
- res.error = ({ status = 500, msg = "Internal server error", data = null }) => {
- return res.status(status).json({
- success: false,
- msg,
- data,
- });
- };
- next();
-};
-
-export { responseHandler };
diff --git a/Server/middleware/verifyJWT.js b/Server/middleware/verifyJWT.js
deleted file mode 100644
index 87fa53bd6..000000000
--- a/Server/middleware/verifyJWT.js
+++ /dev/null
@@ -1,95 +0,0 @@
-import jwt from "jsonwebtoken";
-import { errorMessages } from "../utils/messages.js";
-import ServiceRegistry from "../service/serviceRegistry.js";
-import SettingsService from "../service/settingsService.js";
-const SERVICE_NAME = "verifyJWT";
-const TOKEN_PREFIX = "Bearer ";
-
-/**
- * Verifies the JWT token
- * @function
- * @param {express.Request} req
- * @param {express.Response} res
- * @param {express.NextFunction} next
- * @returns {express.Response}
- */
-const verifyJWT = (req, res, next) => {
- const token = req.headers["authorization"];
- // Make sure a token is provided
- if (!token) {
- const error = new Error(errorMessages.NO_AUTH_TOKEN);
- error.status = 401;
- error.service = SERVICE_NAME;
- next(error);
- return;
- }
- // Make sure it is properly formatted
- if (!token.startsWith(TOKEN_PREFIX)) {
- const error = new Error(errorMessages.INVALID_AUTH_TOKEN); // Instantiate a new Error object for improperly formatted token
- error.status = 400;
- error.service = SERVICE_NAME;
- error.method = "verifyJWT";
- next(error);
- return;
- }
-
- const parsedToken = token.slice(TOKEN_PREFIX.length, token.length);
- // Verify the token's authenticity
- const { jwtSecret } = ServiceRegistry.get(SettingsService.SERVICE_NAME).getSettings();
- jwt.verify(parsedToken, jwtSecret, (err, decoded) => {
- if (err) {
- if (err.name === "TokenExpiredError") {
- // token has expired
- handleExpiredJwtToken(req, res, next);
- } else {
- // Invalid token (signature or token altered or other issue)
- const errorMessage = errorMessages.INVALID_AUTH_TOKEN;
- return res.status(401).json({ success: false, msg: errorMessage });
- }
- } else {
- // Token is valid and not expired, carry on with request, Add the decoded payload to the request
- req.user = decoded;
- next();
- }
- });
-};
-
-function handleExpiredJwtToken(req, res, next) {
- // check for refreshToken
- const refreshToken = req.headers["x-refresh-token"];
-
- if (!refreshToken) {
- // No refresh token provided
- const error = new Error(errorMessages.NO_REFRESH_TOKEN);
- error.status = 401;
- error.service = SERVICE_NAME;
- error.method = "handleExpiredJwtToken";
- return next(error);
- }
-
- // Verify refresh token
- const { refreshTokenSecret } = ServiceRegistry.get(
- SettingsService.SERVICE_NAME
- ).getSettings();
- jwt.verify(refreshToken, refreshTokenSecret, (refreshErr, refreshDecoded) => {
- if (refreshErr) {
- // Invalid or expired refresh token, trigger logout
- const errorMessage =
- refreshErr.name === "TokenExpiredError"
- ? errorMessages.EXPIRED_REFRESH_TOKEN
- : errorMessages.INVALID_REFRESH_TOKEN;
- const error = new Error(errorMessage);
- error.status = 401;
- error.service = SERVICE_NAME;
- return next(error);
- }
-
- // Refresh token is valid and unexpired, request for new access token
- res.status(403).json({
- success: false,
- msg: errorMessages.REQUEST_NEW_ACCESS_TOKEN,
- });
- });
-}
-
-export { verifyJWT };
diff --git a/Server/routes/distributedUptimeRoute.js b/Server/routes/distributedUptimeRoute.js
deleted file mode 100644
index eac4cb675..000000000
--- a/Server/routes/distributedUptimeRoute.js
+++ /dev/null
@@ -1,18 +0,0 @@
-import { Router } from "express";
-
-class DistributedUptimeRoutes {
- constructor(distributedUptimeController) {
- this.router = Router();
- this.distributedUptimeController = distributedUptimeController;
- this.initRoutes();
- }
- initRoutes() {
- this.router.post("/callback", this.distributedUptimeController.resultsCallback);
- }
-
- getRouter() {
- return this.router;
- }
-}
-
-export default DistributedUptimeRoutes;
diff --git a/Server/routes/queueRoute.js b/Server/routes/queueRoute.js
deleted file mode 100644
index af0e9d08e..000000000
--- a/Server/routes/queueRoute.js
+++ /dev/null
@@ -1,21 +0,0 @@
-import { Router } from "express";
-
-class QueueRoutes {
- constructor(queueController) {
- this.router = Router();
- this.queueController = queueController;
- this.initRoutes();
- }
- initRoutes() {
- this.router.get("/metrics", this.queueController.getMetrics);
- this.router.get("/jobs", this.queueController.getJobs);
- this.router.post("/jobs", this.queueController.addJob);
- this.router.post("/obliterate", this.queueController.obliterateQueue);
- }
-
- getRouter() {
- return this.router;
- }
-}
-
-export default QueueRoutes;
diff --git a/Server/routes/statusPageRoute.js b/Server/routes/statusPageRoute.js
deleted file mode 100644
index ff2a2018a..000000000
--- a/Server/routes/statusPageRoute.js
+++ /dev/null
@@ -1,22 +0,0 @@
-import { Router } from "express";
-
-import { verifyJWT } from "../middleware/verifyJWT.js";
-
-class StatusPageRoutes {
- constructor(statusPageController) {
- this.router = Router();
- this.statusPageController = statusPageController;
- this.initRoutes();
- }
-
- initRoutes() {
- this.router.get("/:url", this.statusPageController.getStatusPageByUrl);
- this.router.post("/:url", verifyJWT, this.statusPageController.createStatusPage);
- }
-
- getRouter() {
- return this.router;
- }
-}
-
-export default StatusPageRoutes;
diff --git a/Server/service/notificationService.js b/Server/service/notificationService.js
deleted file mode 100644
index 807640a61..000000000
--- a/Server/service/notificationService.js
+++ /dev/null
@@ -1,193 +0,0 @@
-const SERVICE_NAME = "NotificationService";
-
-class NotificationService {
- static SERVICE_NAME = SERVICE_NAME;
- /**
- * Creates an instance of NotificationService.
- *
- * @param {Object} emailService - The email service used for sending notifications.
- * @param {Object} db - The database instance for storing notification data.
- * @param {Object} logger - The logger instance for logging activities.
- */
- constructor(emailService, db, logger) {
- this.SERVICE_NAME = SERVICE_NAME;
- this.emailService = emailService;
- this.db = db;
- this.logger = logger;
- }
-
- /**
- * Sends an email notification for hardware infrastructure alerts
- *
- * @async
- * @function sendHardwareEmail
- * @param {Object} networkResponse - Response object containing monitor information
- * @param {string} address - Email address to send the notification to
- * @param {Array} [alerts=[]] - List of hardware alerts to include in the email
- * @returns {Promise} - Indicates whether email was sent successfully
- * @throws {Error}
- */
- async sendHardwareEmail(networkResponse, address, alerts = []) {
- if (alerts.length === 0) return false;
- const { monitor, status, prevStatus } = networkResponse;
- const template = "hardwareIncidentTemplate";
- const context = { monitor: monitor.name, url: monitor.url, alerts };
- const subject = `Monitor ${monitor.name} infrastructure alerts`;
- this.emailService.buildAndSendEmail(template, context, address, subject);
- return true;
- }
-
- /**
- * Sends an email notification about monitor status change
- *
- * @async
- * @function sendEmail
- * @param {Object} networkResponse - Response object containing monitor status information
- * @param {string} address - Email address to send the notification to
- * @returns {Promise} - Indicates email was sent successfully
- */
- async sendEmail(networkResponse, address) {
- const { monitor, status, prevStatus } = networkResponse;
- const template = prevStatus === false ? "serverIsUpTemplate" : "serverIsDownTemplate";
- const context = { monitor: monitor.name, url: monitor.url };
- const subject = `Monitor ${monitor.name} is ${status === true ? "up" : "down"}`;
- this.emailService.buildAndSendEmail(template, context, address, subject);
- return true;
- }
-
- async handleStatusNotifications(networkResponse) {
- try {
- //If status hasn't changed, we're done
- if (networkResponse.statusChanged === false) return false;
-
- // if prevStatus is undefined, monitor is resuming, we're done
- if (networkResponse.prevStatus === undefined) return false;
- const notifications = await this.db.getNotificationsByMonitorId(
- networkResponse.monitorId
- );
-
- for (const notification of notifications) {
- if (notification.type === "email") {
- this.sendEmail(networkResponse, notification.address);
- }
- // Handle other types of notifications here
- }
- return true;
- } catch (error) {
- this.logger.warn({
- message: error.message,
- service: this.SERVICE_NAME,
- method: "handleNotifications",
- stack: error.stack,
- });
- }
- }
- /**
- * Handles status change notifications for a monitor
- *
- * @async
- * @function handleStatusNotifications
- * @param {Object} networkResponse - Response object containing monitor status information
- * @returns {Promise} - Indicates whether notifications were processed
- * @throws {Error}
- */
- async handleHardwareNotifications(networkResponse) {
- const thresholds = networkResponse?.monitor?.thresholds;
- if (thresholds === undefined) return false; // No thresholds set, we're done
-
- // Get thresholds from monitor
- const {
- usage_cpu: cpuThreshold = -1,
- usage_memory: memoryThreshold = -1,
- usage_disk: diskThreshold = -1,
- } = thresholds;
-
- // Get metrics from response
- const metrics = networkResponse?.payload?.data ?? null;
- if (metrics === null) return false;
-
- const {
- cpu: { usage_percent: cpuUsage = -1 } = {},
- memory: { usage_percent: memoryUsage = -1 } = {},
- disk = [],
- } = metrics;
-
- const alerts = {
- cpu: cpuThreshold !== -1 && cpuUsage > cpuThreshold ? true : false,
- memory: memoryThreshold !== -1 && memoryUsage > memoryThreshold ? true : false,
- disk: disk.some((d) => diskThreshold !== -1 && d.usage_percent > diskThreshold)
- ? true
- : false,
- };
-
- const notifications = await this.db.getNotificationsByMonitorId(
- networkResponse.monitorId
- );
- for (const notification of notifications) {
- const alertsToSend = [];
- const alertTypes = ["cpu", "memory", "disk"];
-
- for (const type of alertTypes) {
- // Iterate over each alert type to see if any need to be decremented
- if (alerts[type] === true) {
- notification[`${type}AlertThreshold`]--; // Decrement threshold if an alert is triggered
-
- if (notification[`${type}AlertThreshold`] <= 0) {
- // If threshold drops below 0, reset and send notification
- notification[`${type}AlertThreshold`] = notification.alertThreshold;
-
- const formatAlert = {
- cpu: () =>
- `Your current CPU usage (${(cpuUsage * 100).toFixed(0)}%) is above your threshold (${(cpuThreshold * 100).toFixed(0)}%)`,
- memory: () =>
- `Your current memory usage (${(memoryUsage * 100).toFixed(0)}%) is above your threshold (${(memoryThreshold * 100).toFixed(0)}%)`,
- disk: () =>
- `Your current disk usage: ${disk
- .map((d, idx) => `(Disk${idx}: ${(d.usage_percent * 100).toFixed(0)}%)`)
- .join(
- ", "
- )} is above your threshold (${(diskThreshold * 100).toFixed(0)}%)`,
- };
- alertsToSend.push(formatAlert[type]());
- }
- }
- }
-
- await notification.save();
-
- if (alertsToSend.length === 0) continue; // No alerts to send, we're done
-
- if (notification.type === "email") {
- this.sendHardwareEmail(networkResponse, notification.address, alertsToSend);
- }
- }
- return true;
- }
-
- /**
- * Handles notifications for different monitor types
- *
- * @async
- * @function handleNotifications
- * @param {Object} networkResponse - Response object containing monitor information
- * @returns {Promise} - Indicates whether notifications were processed successfully
- */
- async handleNotifications(networkResponse) {
- try {
- if (networkResponse.monitor.type === "hardware") {
- this.handleHardwareNotifications(networkResponse);
- }
- this.handleStatusNotifications(networkResponse);
- return true;
- } catch (error) {
- this.logger.warn({
- message: error.message,
- service: this.SERVICE_NAME,
- method: "handleNotifications",
- stack: error.stack,
- });
- }
- }
-}
-
-export default NotificationService;
diff --git a/Server/service/settingsService.js b/Server/service/settingsService.js
deleted file mode 100644
index 24931f6ce..000000000
--- a/Server/service/settingsService.js
+++ /dev/null
@@ -1,84 +0,0 @@
-const SERVICE_NAME = "SettingsService";
-import dotenv from "dotenv";
-dotenv.config();
-const envConfig = {
- logLevel: process.env.LOG_LEVEL,
- apiBaseUrl: undefined,
- clientHost: process.env.CLIENT_HOST,
- jwtSecret: process.env.JWT_SECRET,
- refreshTokenSecret: process.env.REFRESH_TOKEN_SECRET,
- dbType: process.env.DB_TYPE,
- dbConnectionString: process.env.DB_CONNECTION_STRING,
- redisHost: process.env.REDIS_HOST,
- redisPort: process.env.REDIS_PORT,
- jwtTTL: process.env.TOKEN_TTL,
- refreshTokenTTL: process.env.REFRESH_TOKEN_TTL,
- pagespeedApiKey: process.env.PAGESPEED_API_KEY,
- systemEmailHost: process.env.SYSTEM_EMAIL_HOST,
- systemEmailPort: process.env.SYSTEM_EMAIL_PORT,
- systemEmailAddress: process.env.SYSTEM_EMAIL_ADDRESS,
- systemEmailPassword: process.env.SYSTEM_EMAIL_PASSWORD,
-};
-/**
- * SettingsService
- *
- * This service is responsible for loading and managing the application settings.
- * It gives priority to environment variables and will only load settings
- * from the database if they are not set in the environment.
- */
-class SettingsService {
- static SERVICE_NAME = SERVICE_NAME;
- /**
- * Constructs a new SettingsService
- * @constructor
- * @throws {Error}
- */ constructor(appSettings) {
- this.appSettings = appSettings;
- this.settings = { ...envConfig };
- }
- /**
- * Load settings from the database and merge with environment settings.
- * If there are any settings that weren't set by environment variables, use user settings from the database.
- * @returns {Promise} The merged settings.
- * @throws Will throw an error if settings are not found in the database or if settings have not been loaded.
- */ async loadSettings() {
- try {
- const dbSettings = await this.appSettings.findOne();
- if (!this.settings) {
- throw new Error("Settings not found");
- }
-
- // If there are any settings that weren't set by environment variables, use user settings from DB
- for (const key in envConfig) {
- if (envConfig[key] === undefined && dbSettings[key] !== undefined) {
- this.settings[key] = dbSettings[key];
- }
- }
- return this.settings;
- } catch (error) {
- error.service === undefined ? (error.service = SERVICE_NAME) : null;
- error.method === undefined ? (error.method = "loadSettings") : null;
- throw error;
- }
- }
- /**
- * Reload settings by calling loadSettings.
- * @returns {Promise} The reloaded settings.
- */
- async reloadSettings() {
- return this.loadSettings();
- }
- /**
- * Get the current settings.
- * @returns {Object} The current settings.
- * @throws Will throw an error if settings have not been loaded.
- */
- getSettings() {
- if (!this.settings) {
- throw new Error("Settings have not been loaded");
- }
- return this.settings;
- }
-}
-
-export default SettingsService;
diff --git a/Server/service/statusService.js b/Server/service/statusService.js
deleted file mode 100644
index cca443e9e..000000000
--- a/Server/service/statusService.js
+++ /dev/null
@@ -1,164 +0,0 @@
-const SERVICE_NAME = "StatusService";
-
-class StatusService {
- static SERVICE_NAME = SERVICE_NAME;
- /**
- * Creates an instance of StatusService.
- *
- * @param {Object} db - The database instance.
- * @param {Object} logger - The logger instance.
- */
- constructor(db, logger) {
- this.db = db;
- this.logger = logger;
- this.SERVICE_NAME = SERVICE_NAME;
- }
-
- getStatusString = (status) => {
- if (status === true) return "up";
- if (status === false) return "down";
- return "unknown";
- };
- /**
- * Updates the status of a monitor based on the network response.
- *
- * @param {Object} networkResponse - The network response containing monitorId and status.
- * @param {string} networkResponse.monitorId - The ID of the monitor.
- * @param {string} networkResponse.status - The new status of the monitor.
- * @returns {Promise} - A promise that resolves to an object containing the monitor, statusChanged flag, and previous status if the status changed, or false if an error occurred.
- * @returns {Promise} returnObject - The object returned by the function.
- * @returns {Object} returnObject.monitor - The monitor object.
- * @returns {boolean} returnObject.statusChanged - Flag indicating if the status has changed.
- * @returns {boolean} returnObject.prevStatus - The previous status of the monitor
- */
- updateStatus = async (networkResponse) => {
- this.insertCheck(networkResponse);
- try {
- const { monitorId, status } = networkResponse;
- const monitor = await this.db.getMonitorById(monitorId);
- // No change in monitor status, return early
- if (monitor.status === status)
- return { monitor, statusChanged: false, prevStatus: monitor.status };
- // Monitor status changed, save prev status and update monitor
-
- this.logger.info({
- service: this.SERVICE_NAME,
- message: `${monitor.name} went from ${this.getStatusString(monitor.status)} to ${this.getStatusString(status)}`,
- prevStatus: monitor.status,
- newStatus: status,
- });
-
- const prevStatus = monitor.status;
- monitor.status = status;
- await monitor.save();
-
- return {
- monitor,
- statusChanged: true,
- prevStatus: prevStatus,
- };
- //
- } catch (error) {
- this.logger.error({
- service: this.SERVICE_NAME,
- message: error.message,
- method: "updateStatus",
- stack: error.stack,
- });
- throw error;
- }
- };
-
- /**
- * Builds a check object from the network response.
- *
- * @param {Object} networkResponse - The network response object.
- * @param {string} networkResponse.monitorId - The monitor ID.
- * @param {string} networkResponse.type - The type of the response.
- * @param {string} networkResponse.status - The status of the response.
- * @param {number} networkResponse.responseTime - The response time.
- * @param {number} networkResponse.code - The status code.
- * @param {string} networkResponse.message - The message.
- * @param {Object} networkResponse.payload - The payload of the response.
- * @returns {Object} The check object.
- */
- buildCheck = (networkResponse) => {
- const { monitorId, teamId, type, status, responseTime, code, message, payload } =
- networkResponse;
- const check = {
- monitorId,
- teamId,
- status,
- statusCode: code,
- responseTime,
- message,
- };
-
- if (type === "pagespeed") {
- const categories = payload.lighthouseResult?.categories;
- const audits = payload.lighthouseResult?.audits;
- const {
- "cumulative-layout-shift": cls = 0,
- "speed-index": si = 0,
- "first-contentful-paint": fcp = 0,
- "largest-contentful-paint": lcp = 0,
- "total-blocking-time": tbt = 0,
- } = audits;
- check.accessibility = (categories.accessibility?.score || 0) * 100;
- check.bestPractices = (categories["best-practices"]?.score || 0) * 100;
- check.seo = (categories.seo?.score || 0) * 100;
- check.performance = (categories.performance?.score || 0) * 100;
- check.audits = { cls, si, fcp, lcp, tbt };
- }
-
- if (type === "hardware") {
- const { cpu, memory, disk, host } = payload?.data ?? {};
- const { errors } = payload?.errors ?? [];
- check.cpu = cpu ?? {};
- check.memory = memory ?? {};
- check.disk = disk ?? {};
- check.host = host ?? {};
- check.errors = errors ?? [];
- }
- return check;
- };
-
- /**
- * Inserts a check into the database based on the network response.
- *
- * @param {Object} networkResponse - The network response object.
- * @param {string} networkResponse.monitorId - The monitor ID.
- * @param {string} networkResponse.type - The type of the response.
- * @param {string} networkResponse.status - The status of the response.
- * @param {number} networkResponse.responseTime - The response time.
- * @param {number} networkResponse.code - The status code.
- * @param {string} networkResponse.message - The message.
- * @param {Object} networkResponse.payload - The payload of the response.
- * @returns {Promise} A promise that resolves when the check is inserted.
- */
- insertCheck = async (networkResponse) => {
- try {
- const operationMap = {
- http: this.db.createCheck,
- ping: this.db.createCheck,
- pagespeed: this.db.createPageSpeedCheck,
- hardware: this.db.createHardwareCheck,
- docker: this.db.createCheck,
- port: this.db.createCheck,
- };
- const operation = operationMap[networkResponse.type];
-
- const check = this.buildCheck(networkResponse);
- await operation(check);
- } catch (error) {
- this.logger.error({
- message: error.message,
- service: this.SERVICE_NAME,
- method: "insertCheck",
- details: `Error inserting check for monitor: ${networkResponse?.monitorId}`,
- stack: error.stack,
- });
- }
- };
-}
-export default StatusService;
diff --git a/Server/templates/hardwareIncident.mjml b/Server/templates/hardwareIncident.mjml
deleted file mode 100644
index e27933fb9..000000000
--- a/Server/templates/hardwareIncident.mjml
+++ /dev/null
@@ -1,43 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
- Message from BlueWave Infrastructure Monitoring
-
-
-
-
- Infrastructure Alerts
-
-
-
-
-
-
-
- Hello {{name}}!
- {{monitor}} at {{url}} has the following infrastructure alerts:
- {{#each alerts}}
- • {{this}}
- {{/each}}
-
-
-
-
- View Infrastructure Details
-
- This email was sent by BlueWave Infrastructure Monitoring.
-
-
-
-
-
\ No newline at end of file
diff --git a/Server/templates/serverIsDown.mjml b/Server/templates/serverIsDown.mjml
deleted file mode 100644
index 16df7a0a1..000000000
--- a/Server/templates/serverIsDown.mjml
+++ /dev/null
@@ -1,45 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
- Message from Checkmate Service
-
-
-
-
- {{monitor}} is down
-
-
-
-
-
-
-
- Hello {{name}}!
-
- We detected an incident on one of your monitors. Your service is currently
- down. We'll send a message to you once it is up again.
-
- Monitor name: {{monitor}}
- URL: {{url}}
-
-
-
-
- View incident details
-
- This email was sent by Checkmate.
-
-
-
-
-
diff --git a/Server/templates/serverIsUp.mjml b/Server/templates/serverIsUp.mjml
deleted file mode 100644
index 8dbaaf011..000000000
--- a/Server/templates/serverIsUp.mjml
+++ /dev/null
@@ -1,42 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
- Message from Checkmate Service
-
-
-
-
- {{monitor}} is up
-
-
-
-
-
-
-
- Hello {{name}}!
- Your latest incident is resolved and your monitored service is up again.
- Monitor name: {{monitor}}
- URL: {{url}}
-
-
-
-
- View incident details
-
- This email was sent by Checkmate.
-
-
-
-
-
\ No newline at end of file
diff --git a/Server/utils/messages.js b/Server/utils/messages.js
deleted file mode 100644
index 5fc3c70bc..000000000
--- a/Server/utils/messages.js
+++ /dev/null
@@ -1,147 +0,0 @@
-const errorMessages = {
- // General Errors:
- FRIENDLY_ERROR: "Something went wrong...",
- UNKNOWN_ERROR: "An unknown error occurred",
-
- // Auth Controller
- UNAUTHORIZED: "Unauthorized access",
- AUTH_ADMIN_EXISTS: "Admin already exists",
- AUTH_INVITE_NOT_FOUND: "Invite not found",
-
- //Error handling middleware
- UNKNOWN_SERVICE: "Unknown service",
- NO_AUTH_TOKEN: "No auth token provided",
- INVALID_AUTH_TOKEN: "Invalid auth token",
- EXPIRED_AUTH_TOKEN: "Token expired",
- NO_REFRESH_TOKEN: "No refresh token provided",
- INVALID_REFRESH_TOKEN: "Invalid refresh token",
- EXPIRED_REFRESH_TOKEN: "Refresh token expired",
- REQUEST_NEW_ACCESS_TOKEN: "Request new access token",
-
- //Payload
- INVALID_PAYLOAD: "Invalid payload",
-
- //Ownership Middleware
- VERIFY_OWNER_NOT_FOUND: "Document not found",
- VERIFY_OWNER_UNAUTHORIZED: "Unauthorized access",
-
- //Permissions Middleware
- INSUFFICIENT_PERMISSIONS: "Insufficient permissions",
-
- //DB Errors
- DB_USER_EXISTS: "User already exists",
- DB_USER_NOT_FOUND: "User not found",
- DB_TOKEN_NOT_FOUND: "Token not found",
- DB_RESET_PASSWORD_BAD_MATCH: "New password must be different from old password",
- DB_FIND_MONITOR_BY_ID: (monitorId) => `Monitor with id ${monitorId} not found`,
- DB_DELETE_CHECKS: (monitorId) => `No checks found for monitor with id ${monitorId}`,
-
- //Auth errors
- AUTH_INCORRECT_PASSWORD: "Incorrect password",
- AUTH_UNAUTHORIZED: "Unauthorized access",
-
- // Monitor Errors
- MONITOR_GET_BY_ID: "Monitor not found",
- MONITOR_GET_BY_USER_ID: "No monitors found for user",
-
- // Job Queue Errors
- JOB_QUEUE_WORKER_CLOSE: "Error closing worker",
- JOB_QUEUE_DELETE_JOB: "Job not found in queue",
- JOB_QUEUE_OBLITERATE: "Error obliterating queue",
-
- // PING Operations
- PING_CANNOT_RESOLVE: "No response",
-
- // Status Page Errors
- STATUS_PAGE_NOT_FOUND: "Status page not found",
- STATUS_PAGE_URL_NOT_UNIQUE: "Status page url must be unique",
-
- // Docker
- DOCKER_FAIL: "Failed to fetch Docker container information",
- DOCKER_NOT_FOUND: "Docker container not found",
-
- // Port
- PORT_FAIL: "Failed to connect to port",
-};
-
-const successMessages = {
- //Alert Controller
- ALERT_CREATE: "Alert created successfully",
- ALERT_GET_BY_USER: "Got alerts successfully",
- ALERT_GET_BY_MONITOR: "Got alerts by Monitor successfully",
- ALERT_GET_BY_ID: "Got alert by Id successfully",
- ALERT_EDIT: "Alert edited successfully",
- ALERT_DELETE: "Alert deleted successfully",
-
- // Auth Controller
- AUTH_CREATE_USER: "User created successfully",
- AUTH_LOGIN_USER: "User logged in successfully",
- AUTH_LOGOUT_USER: "User logged out successfully",
- AUTH_UPDATE_USER: "User updated successfully",
- AUTH_CREATE_RECOVERY_TOKEN: "Recovery token created successfully",
- AUTH_VERIFY_RECOVERY_TOKEN: "Recovery token verified successfully",
- AUTH_RESET_PASSWORD: "Password reset successfully",
- AUTH_ADMIN_CHECK: "Admin check completed successfully",
- AUTH_DELETE_USER: "User deleted successfully",
- AUTH_TOKEN_REFRESHED: "Auth token is refreshed",
- AUTH_GET_ALL_USERS: "Got all users successfully",
-
- // Invite Controller
- INVITE_ISSUED: "Invite sent successfully",
- INVITE_VERIFIED: "Invite verified successfully",
-
- // Check Controller
- CHECK_CREATE: "Check created successfully",
- CHECK_GET: "Got checks successfully",
- CHECK_DELETE: "Checks deleted successfully",
- CHECK_UPDATE_TTL: "Checks TTL updated successfully",
-
- //Monitor Controller
- MONITOR_GET_ALL: "Got all monitors successfully",
- MONITOR_STATS_BY_ID: "Got monitor stats by Id successfully",
- MONITOR_GET_BY_ID: "Got monitor by Id successfully",
- MONITOR_GET_BY_TEAM_ID: "Got monitors by Team Id successfully",
- MONITOR_GET_BY_USER_ID: (userId) => `Got monitor for ${userId} successfully"`,
- MONITOR_CREATE: "Monitor created successfully",
- MONITOR_DELETE: "Monitor deleted successfully",
- MONITOR_EDIT: "Monitor edited successfully",
- MONITOR_CERTIFICATE: "Got monitor certificate successfully",
- MONITOR_DEMO_ADDED: "Successfully added demo monitors",
-
- // Queue Controller
- QUEUE_GET_METRICS: "Got metrics successfully",
- QUEUE_ADD_JOB: "Job added successfully",
- QUEUE_OBLITERATE: "Queue obliterated",
-
- //Job Queue
- JOB_QUEUE_DELETE_JOB: "Job removed successfully",
- JOB_QUEUE_OBLITERATE: "Queue OBLITERATED!!!",
- JOB_QUEUE_PAUSE_JOB: "Job paused successfully",
- JOB_QUEUE_RESUME_JOB: "Job resumed successfully",
-
- //Maintenance Window Controller
- MAINTENANCE_WINDOW_GET_BY_ID: "Got Maintenance Window by Id successfully",
- MAINTENANCE_WINDOW_CREATE: "Maintenance Window created successfully",
- MAINTENANCE_WINDOW_GET_BY_TEAM: "Got Maintenance Windows by Team successfully",
- MAINTENANCE_WINDOW_DELETE: "Maintenance Window deleted successfully",
- MAINTENANCE_WINDOW_EDIT: "Maintenance Window edited successfully",
-
- //Ping Operations
- PING_SUCCESS: "Success",
-
- // App Settings
- GET_APP_SETTINGS: "Got app settings successfully",
- UPDATE_APP_SETTINGS: "Updated app settings successfully",
-
- // Status Page
- STATUS_PAGE_BY_URL: "Got status page by url successfully",
- STATUS_PAGE_CREATE: "Status page created successfully",
-
- // Docker
- DOCKER_SUCCESS: "Docker container status fetched successfully",
-
- // Port
- PORT_SUCCESS: "Port connected successfully",
-};
-
-export { errorMessages, successMessages };
diff --git a/.coderabbit.yaml b/client/.coderrabbit.yaml
similarity index 100%
rename from .coderabbit.yaml
rename to client/.coderrabbit.yaml
diff --git a/.dockerignore b/client/.dockerignore
similarity index 100%
rename from .dockerignore
rename to client/.dockerignore
diff --git a/client/.env.production b/client/.env.production
new file mode 100644
index 000000000..7a11848c0
--- /dev/null
+++ b/client/.env.production
@@ -0,0 +1,3 @@
+VITE_APP_API_BASE_URL=UPTIME_APP_API_BASE_URL
+VITE_APP_CLIENT_HOST=UPTIME_APP_CLIENT_HOST
+VITE_APP_LOG_LEVEL=UPTIME_APP_LOG_LEVEL
\ No newline at end of file
diff --git a/Client/.eslintrc.cjs b/client/.eslintrc.cjs
similarity index 100%
rename from Client/.eslintrc.cjs
rename to client/.eslintrc.cjs
diff --git a/Client/.gitignore b/client/.gitignore
similarity index 94%
rename from Client/.gitignore
rename to client/.gitignore
index ebf01f87a..83f6fe9ed 100644
--- a/Client/.gitignore
+++ b/client/.gitignore
@@ -25,4 +25,7 @@ dist-ssr
.env
+
+# Scripts
+*.sh
!env.sh
\ No newline at end of file
diff --git a/.prettierrc b/client/.prettierrc
similarity index 100%
rename from .prettierrc
rename to client/.prettierrc
diff --git a/client/README.md b/client/README.md
new file mode 100644
index 000000000..ee3ed2de2
--- /dev/null
+++ b/client/README.md
@@ -0,0 +1,2 @@
+
+This directory contains the client side (frontend) of Checkmate.
diff --git a/Client/env.sh b/client/env.sh
similarity index 100%
rename from Client/env.sh
rename to client/env.sh
diff --git a/Client/index.html b/client/index.html
similarity index 99%
rename from Client/index.html
rename to client/index.html
index 2d13bd25d..a667d1ecf 100644
--- a/Client/index.html
+++ b/client/index.html
@@ -5,6 +5,7 @@
+
Checkmate
diff --git a/Client/package-lock.json b/client/package-lock.json
similarity index 82%
rename from Client/package-lock.json
rename to client/package-lock.json
index f58aa9d46..b7859e0fe 100644
--- a/Client/package-lock.json
+++ b/client/package-lock.json
@@ -11,24 +11,35 @@
"@emotion/react": "^11.13.3",
"@emotion/styled": "^11.13.0",
"@fontsource/roboto": "^5.0.13",
- "@mui/icons-material": "6.4.1",
- "@mui/lab": "6.0.0-beta.24",
- "@mui/material": "6.4.1",
+ "@hello-pangea/dnd": "^18.0.0",
+ "@mui/icons-material": "6.4.11",
+ "@mui/lab": "6.0.0-dev.240424162023-9968b4889d",
+ "@mui/material": "6.4.11",
"@mui/x-charts": "^7.5.1",
- "@mui/x-data-grid": "7.24.0",
- "@mui/x-date-pickers": "7.24.0",
- "@reduxjs/toolkit": "2.5.0",
+ "@mui/x-data-grid": "7.29.0",
+ "@mui/x-date-pickers": "7.29.0",
+ "@reduxjs/toolkit": "2.7.0",
"axios": "^1.7.4",
"dayjs": "1.11.13",
+ "flag-icons": "7.3.2",
+ "html2canvas": "^1.4.1",
+ "i18next": "^24.2.2",
+ "immutability-helper": "^3.1.1",
"joi": "17.13.3",
"jwt-decode": "^4.0.0",
- "react": "^18.2.0",
+ "maplibre-gl": "5.3.1",
+ "mui-color-input": "^6.0.0",
+ "react": "18.3.1",
+ "react-dnd": "^16.0.1",
+ "react-dnd-html5-backend": "^16.0.1",
"react-dom": "^18.2.0",
+ "react-i18next": "^15.4.0",
+ "react-icons": "5.5.0",
"react-redux": "9.2.0",
"react-router": "^6.23.0",
"react-router-dom": "^6.23.1",
"react-toastify": "^10.0.5",
- "recharts": "2.15.0",
+ "recharts": "2.15.2",
"redux-persist": "6.0.0",
"vite-plugin-svgr": "^4.2.0"
},
@@ -72,30 +83,30 @@
}
},
"node_modules/@babel/compat-data": {
- "version": "7.26.2",
- "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.26.2.tgz",
- "integrity": "sha512-Z0WgzSEa+aUcdiJuCIqgujCshpMWgUpgOxXotrYPSA53hA3qopNaqcJpyr0hVb1FeWdnqFA35/fUtXgBK8srQg==",
+ "version": "7.26.8",
+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.26.8.tgz",
+ "integrity": "sha512-oH5UPLMWR3L2wEFLnFJ1TZXqHufiTKAiLfqw5zkhS4dKXLJ10yVztfil/twG8EDTA4F/tvVNw9nOl4ZMslB8rQ==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/core": {
- "version": "7.26.0",
- "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.26.0.tgz",
- "integrity": "sha512-i1SLeK+DzNnQ3LL/CswPCa/E5u4lh1k6IAEphON8F+cXt0t9euTshDru0q7/IqMa1PMPz5RnHuHscF8/ZJsStg==",
+ "version": "7.26.10",
+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.26.10.tgz",
+ "integrity": "sha512-vMqyb7XCDMPvJFFOaT9kxtiRh42GwlZEg1/uIgtZshS5a/8OaduUfCi7kynKgc3Tw/6Uo2D+db9qBttghhmxwQ==",
"license": "MIT",
"dependencies": {
"@ampproject/remapping": "^2.2.0",
- "@babel/code-frame": "^7.26.0",
- "@babel/generator": "^7.26.0",
- "@babel/helper-compilation-targets": "^7.25.9",
+ "@babel/code-frame": "^7.26.2",
+ "@babel/generator": "^7.26.10",
+ "@babel/helper-compilation-targets": "^7.26.5",
"@babel/helper-module-transforms": "^7.26.0",
- "@babel/helpers": "^7.26.0",
- "@babel/parser": "^7.26.0",
- "@babel/template": "^7.25.9",
- "@babel/traverse": "^7.25.9",
- "@babel/types": "^7.26.0",
+ "@babel/helpers": "^7.26.10",
+ "@babel/parser": "^7.26.10",
+ "@babel/template": "^7.26.9",
+ "@babel/traverse": "^7.26.10",
+ "@babel/types": "^7.26.10",
"convert-source-map": "^2.0.0",
"debug": "^4.1.0",
"gensync": "^1.0.0-beta.2",
@@ -117,13 +128,13 @@
"license": "MIT"
},
"node_modules/@babel/generator": {
- "version": "7.26.2",
- "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.26.2.tgz",
- "integrity": "sha512-zevQbhbau95nkoxSq3f/DC/SC+EEOUZd3DYqfSkMhY2/wfSeaHV1Ew4vk8e+x8lja31IbyuUa2uQ3JONqKbysw==",
+ "version": "7.27.0",
+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.27.0.tgz",
+ "integrity": "sha512-VybsKvpiN1gU1sdMZIp7FcqphVVKEwcuj02x73uvcHE0PTihx1nlBcowYWhDwjpoAXRv43+gDzyggGnn1XZhVw==",
"license": "MIT",
"dependencies": {
- "@babel/parser": "^7.26.2",
- "@babel/types": "^7.26.0",
+ "@babel/parser": "^7.27.0",
+ "@babel/types": "^7.27.0",
"@jridgewell/gen-mapping": "^0.3.5",
"@jridgewell/trace-mapping": "^0.3.25",
"jsesc": "^3.0.2"
@@ -133,12 +144,12 @@
}
},
"node_modules/@babel/helper-compilation-targets": {
- "version": "7.25.9",
- "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.25.9.tgz",
- "integrity": "sha512-j9Db8Suy6yV/VHa4qzrj9yZfZxhLWQdVnRlXxmKLYlhWUVB1sB2G5sxuWYXk/whHD9iW76PmNzxZ4UCnTQTVEQ==",
+ "version": "7.26.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.26.5.tgz",
+ "integrity": "sha512-IXuyn5EkouFJscIDuFF5EsiSolseme1s0CZB+QxVugqJLYmKdxI1VfIBOst0SUu4rnk2Z7kqTwmoO1lp3HIfnA==",
"license": "MIT",
"dependencies": {
- "@babel/compat-data": "^7.25.9",
+ "@babel/compat-data": "^7.26.5",
"@babel/helper-validator-option": "^7.25.9",
"browserslist": "^4.24.0",
"lru-cache": "^5.1.1",
@@ -179,9 +190,9 @@
}
},
"node_modules/@babel/helper-plugin-utils": {
- "version": "7.25.9",
- "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.25.9.tgz",
- "integrity": "sha512-kSMlyUVdWe25rEsRGviIgOWnoT/nfABVWlqt9N19/dIPWViAOW2s9wznP5tURbs/IDuNk4gPy3YdYRgH3uxhBw==",
+ "version": "7.26.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.26.5.tgz",
+ "integrity": "sha512-RS+jZcRdZdRFzMyr+wcsaqOmld1/EqTghfaBGQQd/WnRdzdlvSZ//kF7U8VQTxf1ynZ4cjUcYgjVGx13ewNPMg==",
"dev": true,
"license": "MIT",
"engines": {
@@ -216,25 +227,25 @@
}
},
"node_modules/@babel/helpers": {
- "version": "7.26.0",
- "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.26.0.tgz",
- "integrity": "sha512-tbhNuIxNcVb21pInl3ZSjksLCvgdZy9KwJ8brv993QtIVKJBBkYXz4q4ZbAv31GdnC+R90np23L5FbEBlthAEw==",
+ "version": "7.27.0",
+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.27.0.tgz",
+ "integrity": "sha512-U5eyP/CTFPuNE3qk+WZMxFkp/4zUzdceQlfzf7DdGdhp+Fezd7HD+i8Y24ZuTMKX3wQBld449jijbGq6OdGNQg==",
"license": "MIT",
"dependencies": {
- "@babel/template": "^7.25.9",
- "@babel/types": "^7.26.0"
+ "@babel/template": "^7.27.0",
+ "@babel/types": "^7.27.0"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/parser": {
- "version": "7.26.2",
- "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.2.tgz",
- "integrity": "sha512-DWMCZH9WA4Maitz2q21SRKHo9QXZxkDsbNZoVD62gusNtNBBqDg9i7uOhASfTfIGNzW+O+r7+jAlM8dwphcJKQ==",
+ "version": "7.27.0",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.27.0.tgz",
+ "integrity": "sha512-iaepho73/2Pz7w2eMS0Q5f83+0RKI7i4xmiYeBmDzfRVbQtTOG7Ts0S4HzJVsTMGI9keU8rNfuZr8DKfSt7Yyg==",
"license": "MIT",
"dependencies": {
- "@babel/types": "^7.26.0"
+ "@babel/types": "^7.27.0"
},
"bin": {
"parser": "bin/babel-parser.js"
@@ -276,9 +287,9 @@
}
},
"node_modules/@babel/runtime": {
- "version": "7.26.0",
- "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.0.tgz",
- "integrity": "sha512-FDSOghenHTiToteC/QRlv2q3DhPZ/oOXTBoirfWNx1Cx3TMVcGWQtMMmQcSvb/JjpNeGzx8Pq/b4fKEJuWm1sw==",
+ "version": "7.26.10",
+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.10.tgz",
+ "integrity": "sha512-2WJMeRQPHKSPemqk/awGrAiuFfzBmOIPXKizAsVhWH9YJqLZ0H+HS4c8loHGgW6utJ3E/ejXQUsiGaQy2NZ9Fw==",
"license": "MIT",
"dependencies": {
"regenerator-runtime": "^0.14.0"
@@ -288,30 +299,30 @@
}
},
"node_modules/@babel/template": {
- "version": "7.25.9",
- "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.25.9.tgz",
- "integrity": "sha512-9DGttpmPvIxBb/2uwpVo3dqJ+O6RooAFOS+lB+xDqoE2PVCE8nfoHMdZLpfCQRLwvohzXISPZcgxt80xLfsuwg==",
+ "version": "7.27.0",
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.0.tgz",
+ "integrity": "sha512-2ncevenBqXI6qRMukPlXwHKHchC7RyMuu4xv5JBXRfOGVcTy1mXCD12qrp7Jsoxll1EV3+9sE4GugBVRjT2jFA==",
"license": "MIT",
"dependencies": {
- "@babel/code-frame": "^7.25.9",
- "@babel/parser": "^7.25.9",
- "@babel/types": "^7.25.9"
+ "@babel/code-frame": "^7.26.2",
+ "@babel/parser": "^7.27.0",
+ "@babel/types": "^7.27.0"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/traverse": {
- "version": "7.25.9",
- "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.25.9.tgz",
- "integrity": "sha512-ZCuvfwOwlz/bawvAuvcj8rrithP2/N55Tzz342AkTvq4qaWbGfmCk/tKhNaV2cthijKrPAA8SRJV5WWe7IBMJw==",
+ "version": "7.27.0",
+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.27.0.tgz",
+ "integrity": "sha512-19lYZFzYVQkkHkl4Cy4WrAVcqBkgvV2YM2TU3xG6DIwO7O3ecbDPfW3yM3bjAGcqcQHi+CCtjMR3dIEHxsd6bA==",
"license": "MIT",
"dependencies": {
- "@babel/code-frame": "^7.25.9",
- "@babel/generator": "^7.25.9",
- "@babel/parser": "^7.25.9",
- "@babel/template": "^7.25.9",
- "@babel/types": "^7.25.9",
+ "@babel/code-frame": "^7.26.2",
+ "@babel/generator": "^7.27.0",
+ "@babel/parser": "^7.27.0",
+ "@babel/template": "^7.27.0",
+ "@babel/types": "^7.27.0",
"debug": "^4.3.1",
"globals": "^11.1.0"
},
@@ -320,9 +331,9 @@
}
},
"node_modules/@babel/types": {
- "version": "7.26.0",
- "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.0.tgz",
- "integrity": "sha512-Z/yiTPj+lDVnF7lWeKCIJzaIkI0vYO87dMpZ4bg4TDrFe4XXLFWL1TbXU27gBP3QccxV9mZICCrnjnYlJjXHOA==",
+ "version": "7.27.0",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.27.0.tgz",
+ "integrity": "sha512-H45s8fVLYjbhFH62dIJ3WtmJ6RSPt/3DRO0ZcT2SUiYiQyz3BLVb9ADEnLl91m74aQPS3AzzeajZHYOalWe3bg==",
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.25.9",
@@ -332,6 +343,14 @@
"node": ">=6.9.0"
}
},
+ "node_modules/@ctrl/tinycolor": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/@ctrl/tinycolor/-/tinycolor-4.1.0.tgz",
+ "integrity": "sha512-WyOx8cJQ+FQus4Mm4uPIZA64gbk3Wxh0so5Lcii0aJifqwoVOlfFtorjLE0Hen4OYyHZMXDWqMmaQemBhgxFRQ==",
+ "engines": {
+ "node": ">=14"
+ }
+ },
"node_modules/@emotion/babel-plugin": {
"version": "11.13.5",
"resolved": "https://registry.npmjs.org/@emotion/babel-plugin/-/babel-plugin-11.13.5.tgz",
@@ -478,262 +497,6 @@
"integrity": "sha512-snKqtPW01tN0ui7yu9rGv69aJXr/a/Ywvl11sUjNtEcRc+ng/mQriFL0wLXMef74iHa/EkftbDzU9F8iFbH+zg==",
"license": "MIT"
},
- "node_modules/@esbuild/aix-ppc64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
- "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==",
- "cpu": [
- "ppc64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "aix"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/android-arm": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz",
- "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==",
- "cpu": [
- "arm"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "android"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/android-arm64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz",
- "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "android"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/android-x64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz",
- "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "android"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/darwin-arm64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz",
- "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/darwin-x64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz",
- "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/freebsd-arm64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz",
- "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "freebsd"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/freebsd-x64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz",
- "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "freebsd"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/linux-arm": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz",
- "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==",
- "cpu": [
- "arm"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/linux-arm64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz",
- "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/linux-ia32": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz",
- "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==",
- "cpu": [
- "ia32"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/linux-loong64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz",
- "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==",
- "cpu": [
- "loong64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/linux-mips64el": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz",
- "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==",
- "cpu": [
- "mips64el"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/linux-ppc64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz",
- "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==",
- "cpu": [
- "ppc64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/linux-riscv64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz",
- "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==",
- "cpu": [
- "riscv64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/linux-s390x": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz",
- "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==",
- "cpu": [
- "s390x"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=12"
- }
- },
"node_modules/@esbuild/linux-x64": {
"version": "0.21.5",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz",
@@ -750,102 +513,6 @@
"node": ">=12"
}
},
- "node_modules/@esbuild/netbsd-x64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz",
- "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "netbsd"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/openbsd-x64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz",
- "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "openbsd"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/sunos-x64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz",
- "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "sunos"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/win32-arm64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz",
- "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/win32-ia32": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz",
- "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==",
- "cpu": [
- "ia32"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@esbuild/win32-x64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz",
- "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=12"
- }
- },
"node_modules/@eslint-community/eslint-utils": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.1.tgz",
@@ -964,10 +631,13 @@
"license": "MIT"
},
"node_modules/@fontsource/roboto": {
- "version": "5.1.1",
- "resolved": "https://registry.npmjs.org/@fontsource/roboto/-/roboto-5.1.1.tgz",
- "integrity": "sha512-XwVVXtERDQIM7HPUIbyDe0FP4SRovpjF7zMI8M7pbqFp3ahLJsJTd18h+E6pkar6UbV3btbwkKjYARr5M+SQow==",
- "license": "Apache-2.0"
+ "version": "5.2.5",
+ "resolved": "https://registry.npmjs.org/@fontsource/roboto/-/roboto-5.2.5.tgz",
+ "integrity": "sha512-70r2UZ0raqLn5W+sPeKhqlf8wGvUXFWlofaDlcbt/S3d06+17gXKr3VNqDODB0I1ASme3dGT5OJj9NABt7OTZQ==",
+ "license": "OFL-1.1",
+ "funding": {
+ "url": "https://github.com/sponsors/ayuhito"
+ }
},
"node_modules/@hapi/hoek": {
"version": "9.3.0",
@@ -984,6 +654,23 @@
"@hapi/hoek": "^9.0.0"
}
},
+ "node_modules/@hello-pangea/dnd": {
+ "version": "18.0.1",
+ "resolved": "https://registry.npmjs.org/@hello-pangea/dnd/-/dnd-18.0.1.tgz",
+ "integrity": "sha512-xojVWG8s/TGrKT1fC8K2tIWeejJYTAeJuj36zM//yEm/ZrnZUSFGS15BpO+jGZT1ybWvyXmeDJwPYb4dhWlbZQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@babel/runtime": "^7.26.7",
+ "css-box-model": "^1.2.1",
+ "raf-schd": "^4.0.3",
+ "react-redux": "^9.2.0",
+ "redux": "^5.0.1"
+ },
+ "peerDependencies": {
+ "react": "^18.0.0 || ^19.0.0",
+ "react-dom": "^18.0.0 || ^19.0.0"
+ }
+ },
"node_modules/@humanwhocodes/config-array": {
"version": "0.13.0",
"resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz",
@@ -1054,6 +741,18 @@
"node": ">=6.0.0"
}
},
+ "node_modules/@jridgewell/source-map": {
+ "version": "0.3.6",
+ "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.6.tgz",
+ "integrity": "sha512-1ZJTZebgqllO79ue2bm3rIGud/bOe0pP5BjSRCRxxYkEZS8STV7zN84UBbiYu7jy+eCKSnVIUgoWWE/tt+shMQ==",
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "@jridgewell/gen-mapping": "^0.3.5",
+ "@jridgewell/trace-mapping": "^0.3.25"
+ }
+ },
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz",
@@ -1070,42 +769,87 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
- "node_modules/@mui/base": {
- "version": "5.0.0-beta.69",
- "resolved": "https://registry.npmjs.org/@mui/base/-/base-5.0.0-beta.69.tgz",
- "integrity": "sha512-r2YyGUXpZxj8rLAlbjp1x2BnMERTZ/dMqd9cClKj2OJ7ALAuiv/9X5E9eHfRc9o/dGRuLSMq/WTjREktJVjxVA==",
- "license": "MIT",
+ "node_modules/@mapbox/geojson-rewind": {
+ "version": "0.5.2",
+ "resolved": "https://registry.npmjs.org/@mapbox/geojson-rewind/-/geojson-rewind-0.5.2.tgz",
+ "integrity": "sha512-tJaT+RbYGJYStt7wI3cq4Nl4SXxG8W7JDG5DMJu97V25RnbNg3QtQtf+KD+VLjNpWKYsRvXDNmNrBgEETr1ifA==",
+ "license": "ISC",
"dependencies": {
- "@babel/runtime": "^7.26.0",
- "@floating-ui/react-dom": "^2.1.1",
- "@mui/types": "^7.2.21",
- "@mui/utils": "^6.4.1",
- "@popperjs/core": "^2.11.8",
- "clsx": "^2.1.1",
- "prop-types": "^15.8.1"
+ "get-stream": "^6.0.1",
+ "minimist": "^1.2.6"
},
+ "bin": {
+ "geojson-rewind": "geojson-rewind"
+ }
+ },
+ "node_modules/@mapbox/jsonlint-lines-primitives": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/@mapbox/jsonlint-lines-primitives/-/jsonlint-lines-primitives-2.0.2.tgz",
+ "integrity": "sha512-rY0o9A5ECsTQRVhv7tL/OyDpGAoUB4tTvLiW1DSzQGq4bvTPhNw1VpSNjDJc5GFZ2XuyOtSWSVN05qOtcD71qQ==",
"engines": {
- "node": ">=14.0.0"
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/@mapbox/point-geometry": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/@mapbox/point-geometry/-/point-geometry-0.1.0.tgz",
+ "integrity": "sha512-6j56HdLTwWGO0fJPlrZtdU/B13q8Uwmo18Ck2GnGgN9PCFyKTZ3UbXeEdRFh18i9XQ92eH2VdtpJHpBD3aripQ==",
+ "license": "ISC"
+ },
+ "node_modules/@mapbox/tiny-sdf": {
+ "version": "2.0.6",
+ "resolved": "https://registry.npmjs.org/@mapbox/tiny-sdf/-/tiny-sdf-2.0.6.tgz",
+ "integrity": "sha512-qMqa27TLw+ZQz5Jk+RcwZGH7BQf5G/TrutJhspsca/3SHwmgKQ1iq+d3Jxz5oysPVYTGP6aXxCo5Lk9Er6YBAA==",
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/@mapbox/unitbezier": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/@mapbox/unitbezier/-/unitbezier-0.0.1.tgz",
+ "integrity": "sha512-nMkuDXFv60aBr9soUG5q+GvZYL+2KZHVvsqFCzqnkGEf46U2fvmytHaEVc1/YZbiLn8X+eR3QzX1+dwDO1lxlw==",
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/@mapbox/vector-tile": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/@mapbox/vector-tile/-/vector-tile-1.3.1.tgz",
+ "integrity": "sha512-MCEddb8u44/xfQ3oD+Srl/tNcQoqTw3goGk2oLsrFxOTc3dUp+kAnby3PvAeeBYSMSjSPD1nd1AJA6W49WnoUw==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@mapbox/point-geometry": "~0.1.0"
+ }
+ },
+ "node_modules/@mapbox/whoots-js": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@mapbox/whoots-js/-/whoots-js-3.1.0.tgz",
+ "integrity": "sha512-Es6WcD0nO5l+2BOQS4uLfNPYQaNDfbot3X1XUoloz+x0mPDS3eeORZJl06HXjwBG1fOGwCRnzK88LMdxKRrd6Q==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@maplibre/maplibre-gl-style-spec": {
+ "version": "23.1.0",
+ "resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-23.1.0.tgz",
+ "integrity": "sha512-R6/ihEuC5KRexmKIYkWqUv84Gm+/QwsOUgHyt1yy2XqCdGdLvlBWVWIIeTZWN4NGdwmY6xDzdSGU2R9oBLNg2w==",
+ "license": "ISC",
+ "dependencies": {
+ "@mapbox/jsonlint-lines-primitives": "~2.0.2",
+ "@mapbox/unitbezier": "^0.0.1",
+ "json-stringify-pretty-compact": "^4.0.0",
+ "minimist": "^1.2.8",
+ "quickselect": "^3.0.0",
+ "rw": "^1.3.3",
+ "tinyqueue": "^3.0.0"
},
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/mui-org"
- },
- "peerDependencies": {
- "@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0",
- "react": "^17.0.0 || ^18.0.0 || ^19.0.0",
- "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0"
- },
- "peerDependenciesMeta": {
- "@types/react": {
- "optional": true
- }
+ "bin": {
+ "gl-style-format": "dist/gl-style-format.mjs",
+ "gl-style-migrate": "dist/gl-style-migrate.mjs",
+ "gl-style-validate": "dist/gl-style-validate.mjs"
}
},
"node_modules/@mui/core-downloads-tracker": {
- "version": "6.4.1",
- "resolved": "https://registry.npmjs.org/@mui/core-downloads-tracker/-/core-downloads-tracker-6.4.1.tgz",
- "integrity": "sha512-SfDLWMV5b5oXgDf3NTa2hCTPC1d2defhDH2WgFKmAiejC4mSfXYbyi+AFCLzpizauXhgBm8OaZy9BHKnrSpahQ==",
+ "version": "6.4.11",
+ "resolved": "https://registry.npmjs.org/@mui/core-downloads-tracker/-/core-downloads-tracker-6.4.11.tgz",
+ "integrity": "sha512-CzAQs9CTzlwbsF9ZYB4o4lLwBv1/qNE264NjuYao+ctAXsmlPtYa8RtER4UsUXSMxNN9Qi+aQdYcKl2sUpnmAw==",
"license": "MIT",
"funding": {
"type": "opencollective",
@@ -1113,9 +857,9 @@
}
},
"node_modules/@mui/icons-material": {
- "version": "6.4.1",
- "resolved": "https://registry.npmjs.org/@mui/icons-material/-/icons-material-6.4.1.tgz",
- "integrity": "sha512-wsxFcUTQxt4s+7Bg4GgobqRjyaHLmZGNOs+HJpbwrwmLbT6mhIJxhpqsKzzWq9aDY8xIe7HCjhpH7XI5UD6teA==",
+ "version": "6.4.11",
+ "resolved": "https://registry.npmjs.org/@mui/icons-material/-/icons-material-6.4.11.tgz",
+ "integrity": "sha512-+jjJGIrB1awNbMv4ZVPPdN/p7O1UKFZ+xqRvNIQ8B1KnlID5hPMPBLM6UUbRF4bu3UDCbu79rn9Nye5LGNzmeA==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.26.0"
@@ -1128,7 +872,7 @@
"url": "https://opencollective.com/mui-org"
},
"peerDependencies": {
- "@mui/material": "^6.4.1",
+ "@mui/material": "^6.4.11",
"@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0",
"react": "^17.0.0 || ^18.0.0 || ^19.0.0"
},
@@ -1139,21 +883,21 @@
}
},
"node_modules/@mui/lab": {
- "version": "6.0.0-beta.24",
- "resolved": "https://registry.npmjs.org/@mui/lab/-/lab-6.0.0-beta.24.tgz",
- "integrity": "sha512-Off0rx2065TfGu5Z8E4OduNiVAqE9p9A8N1268hoXOcx7HzARxJsDFLRKvWgpPMqmGEvR8DVaHkcF2N90UB15A==",
+ "version": "6.0.0-dev.240424162023-9968b4889d",
+ "resolved": "https://registry.npmjs.org/@mui/lab/-/lab-6.0.0-dev.240424162023-9968b4889d.tgz",
+ "integrity": "sha512-iKFAz7/EeWI4PaFsP4jK2FcYJmUYDBkn3XZwpQSAl5806yYq5J2U2mPQLuZBdhrH50gT2O98p95i3vwL4YBwAg==",
"license": "MIT",
"dependencies": {
- "@babel/runtime": "^7.26.0",
- "@mui/base": "5.0.0-beta.69",
- "@mui/system": "^6.4.1",
- "@mui/types": "^7.2.21",
- "@mui/utils": "^6.4.1",
- "clsx": "^2.1.1",
+ "@babel/runtime": "^7.24.4",
+ "@mui/base": "5.0.0-beta.42",
+ "@mui/system": "^6.0.0-dev.240424162023-9968b4889d",
+ "@mui/types": "^7.2.14",
+ "@mui/utils": "^6.0.0-alpha.3",
+ "clsx": "^2.1.0",
"prop-types": "^15.8.1"
},
"engines": {
- "node": ">=14.0.0"
+ "node": ">=12.0.0"
},
"funding": {
"type": "opencollective",
@@ -1162,11 +906,10 @@
"peerDependencies": {
"@emotion/react": "^11.5.0",
"@emotion/styled": "^11.3.0",
- "@mui/material": "^6.4.1",
- "@mui/material-pigment-css": "^6.4.1",
- "@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0",
- "react": "^17.0.0 || ^18.0.0 || ^19.0.0",
- "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0"
+ "@mui/material": "^6.0.0-dev.240424162023-9968b4889d",
+ "@types/react": "^17.0.0 || ^18.0.0",
+ "react": "^17.0.0 || ^18.0.0",
+ "react-dom": "^17.0.0 || ^18.0.0"
},
"peerDependenciesMeta": {
"@emotion/react": {
@@ -1175,25 +918,55 @@
"@emotion/styled": {
"optional": true
},
- "@mui/material-pigment-css": {
+ "@types/react": {
"optional": true
- },
+ }
+ }
+ },
+ "node_modules/@mui/lab/node_modules/@mui/base": {
+ "version": "5.0.0-beta.42",
+ "resolved": "https://registry.npmjs.org/@mui/base/-/base-5.0.0-beta.42.tgz",
+ "integrity": "sha512-fWRiUJVCHCPF+mxd5drn08bY2qRw3jj5f1SSQdUXmaJ/yKpk23ys8MgLO2KGVTRtbks/+ctRfgffGPbXifj0Ug==",
+ "deprecated": "This package has been replaced by @base-ui-components/react",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.24.4",
+ "@floating-ui/react-dom": "^2.0.8",
+ "@mui/types": "^7.2.14",
+ "@mui/utils": "^6.0.0-alpha.1",
+ "@popperjs/core": "^2.11.8",
+ "clsx": "^2.1.0",
+ "prop-types": "^15.8.1"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/mui-org"
+ },
+ "peerDependencies": {
+ "@types/react": "^17.0.0 || ^18.0.0",
+ "react": "^17.0.0 || ^18.0.0",
+ "react-dom": "^17.0.0 || ^18.0.0"
+ },
+ "peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@mui/material": {
- "version": "6.4.1",
- "resolved": "https://registry.npmjs.org/@mui/material/-/material-6.4.1.tgz",
- "integrity": "sha512-MFBfia6UiKxyoLeGkAh8M15bkeDmfnsUTMRJd/vTQue6YQ8AQ6lw9HqDthyYghzDEWIvZO/lQQzLrZE8XwNJLA==",
+ "version": "6.4.11",
+ "resolved": "https://registry.npmjs.org/@mui/material/-/material-6.4.11.tgz",
+ "integrity": "sha512-k2D3FLJS+/qD0qnd6ZlAjGFvaaxe1Dl10NyvpeDzIebMuYdn8VqYe6XBgGueEAtnzSJM4V03VD9kb5Fi24dnTA==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.26.0",
- "@mui/core-downloads-tracker": "^6.4.1",
- "@mui/system": "^6.4.1",
- "@mui/types": "^7.2.21",
- "@mui/utils": "^6.4.1",
+ "@mui/core-downloads-tracker": "^6.4.11",
+ "@mui/system": "^6.4.11",
+ "@mui/types": "~7.2.24",
+ "@mui/utils": "^6.4.9",
"@popperjs/core": "^2.11.8",
"@types/react-transition-group": "^4.4.12",
"clsx": "^2.1.1",
@@ -1212,7 +985,7 @@
"peerDependencies": {
"@emotion/react": "^11.5.0",
"@emotion/styled": "^11.3.0",
- "@mui/material-pigment-css": "^6.4.1",
+ "@mui/material-pigment-css": "^6.4.11",
"@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0",
"react": "^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0"
@@ -1233,19 +1006,19 @@
}
},
"node_modules/@mui/material/node_modules/react-is": {
- "version": "19.0.0",
- "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.0.0.tgz",
- "integrity": "sha512-H91OHcwjZsbq3ClIDHMzBShc1rotbfACdWENsmEf0IFvZ3FgGPtdHMcsv45bQ1hAbgdfiA8SnxTKfDS+x/8m2g==",
+ "version": "19.1.0",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.1.0.tgz",
+ "integrity": "sha512-Oe56aUPnkHyyDxxkvqtd7KkdQP5uIUfHxd5XTb3wE9d/kRnZLmKbDB0GWk919tdQ+mxxPtG6EAs6RMT6i1qtHg==",
"license": "MIT"
},
"node_modules/@mui/private-theming": {
- "version": "6.4.1",
- "resolved": "https://registry.npmjs.org/@mui/private-theming/-/private-theming-6.4.1.tgz",
- "integrity": "sha512-DcT7mwK89owwgcEuiE7w458te4CIjHbYWW6Kn6PiR6eLtxBsoBYphA968uqsQAOBQDpbYxvkuFLwhgk4bxoN/Q==",
+ "version": "6.4.9",
+ "resolved": "https://registry.npmjs.org/@mui/private-theming/-/private-theming-6.4.9.tgz",
+ "integrity": "sha512-LktcVmI5X17/Q5SkwjCcdOLBzt1hXuc14jYa7NPShog0GBDCDvKtcnP0V7a2s6EiVRlv7BzbWEJzH6+l/zaCxw==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.26.0",
- "@mui/utils": "^6.4.1",
+ "@mui/utils": "^6.4.9",
"prop-types": "^15.8.1"
},
"engines": {
@@ -1266,9 +1039,9 @@
}
},
"node_modules/@mui/styled-engine": {
- "version": "6.4.0",
- "resolved": "https://registry.npmjs.org/@mui/styled-engine/-/styled-engine-6.4.0.tgz",
- "integrity": "sha512-ek/ZrDujrger12P6o4luQIfRd2IziH7jQod2WMbLqGE03Iy0zUwYmckRTVhRQTLPNccpD8KXGcALJF+uaUQlbg==",
+ "version": "6.4.11",
+ "resolved": "https://registry.npmjs.org/@mui/styled-engine/-/styled-engine-6.4.11.tgz",
+ "integrity": "sha512-74AUmlHXaGNbyUqdK/+NwDJOZqgRQw6BcNvhoWYLq3LGbLTkE+khaJ7soz6cIabE4CPYqO2/QAIU1Z/HEjjpcw==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.26.0",
@@ -1300,16 +1073,16 @@
}
},
"node_modules/@mui/system": {
- "version": "6.4.1",
- "resolved": "https://registry.npmjs.org/@mui/system/-/system-6.4.1.tgz",
- "integrity": "sha512-rgQzgcsHCTtzF9MZ+sL0tOhf2ZBLazpjrujClcb4Siju5lTrK0xX4PsiropActzCemNfM+mOu+0jezAVnfRK8g==",
+ "version": "6.4.11",
+ "resolved": "https://registry.npmjs.org/@mui/system/-/system-6.4.11.tgz",
+ "integrity": "sha512-gibtsrZEwnDaT5+I/KloOj/yHluX5G8heknuxBpQOdEQ3Gc0avjSImn5hSeKp8D4thiwZiApuggIjZw1dQguUA==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.26.0",
- "@mui/private-theming": "^6.4.1",
- "@mui/styled-engine": "^6.4.0",
- "@mui/types": "^7.2.21",
- "@mui/utils": "^6.4.1",
+ "@mui/private-theming": "^6.4.9",
+ "@mui/styled-engine": "^6.4.11",
+ "@mui/types": "~7.2.24",
+ "@mui/utils": "^6.4.9",
"clsx": "^2.1.1",
"csstype": "^3.1.3",
"prop-types": "^15.8.1"
@@ -1340,9 +1113,9 @@
}
},
"node_modules/@mui/types": {
- "version": "7.2.21",
- "resolved": "https://registry.npmjs.org/@mui/types/-/types-7.2.21.tgz",
- "integrity": "sha512-6HstngiUxNqLU+/DPqlUJDIPbzUBxIVHb1MmXP0eTWDIROiCR2viugXpEif0PPe2mLqqakPzzRClWAnK+8UJww==",
+ "version": "7.2.24",
+ "resolved": "https://registry.npmjs.org/@mui/types/-/types-7.2.24.tgz",
+ "integrity": "sha512-3c8tRt/CbWZ+pEg7QpSwbdxOk36EfmhbKf6AGZsD1EcLDLTSZoxxJ86FVtcjxvjuhdyBiWKSTGZFaXCnidO2kw==",
"license": "MIT",
"peerDependencies": {
"@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0"
@@ -1354,13 +1127,13 @@
}
},
"node_modules/@mui/utils": {
- "version": "6.4.1",
- "resolved": "https://registry.npmjs.org/@mui/utils/-/utils-6.4.1.tgz",
- "integrity": "sha512-iQUDUeYh87SvR4lVojaRaYnQix8BbRV51MxaV6MBmqthecQoxwSbS5e2wnbDJUeFxY2ppV505CiqPLtd0OWkqw==",
+ "version": "6.4.9",
+ "resolved": "https://registry.npmjs.org/@mui/utils/-/utils-6.4.9.tgz",
+ "integrity": "sha512-Y12Q9hbK9g+ZY0T3Rxrx9m2m10gaphDuUMgWxyV5kNJevVxXYCLclYUCC9vXaIk1/NdNDTcW2Yfr2OGvNFNmHg==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.26.0",
- "@mui/types": "^7.2.21",
+ "@mui/types": "~7.2.24",
"@types/prop-types": "^15.7.14",
"clsx": "^2.1.1",
"prop-types": "^15.8.1",
@@ -1390,15 +1163,15 @@
"license": "MIT"
},
"node_modules/@mui/x-charts": {
- "version": "7.24.0",
- "resolved": "https://registry.npmjs.org/@mui/x-charts/-/x-charts-7.24.0.tgz",
- "integrity": "sha512-X/zN0GxPHJC24QckFrtEbIK0HYoGwZgpNC5CV9cvRGvHphDFuNZk9xg9fJwIg1i3PPZHXRO3E+L/ee6fJ9ufhw==",
+ "version": "7.29.0",
+ "resolved": "https://registry.npmjs.org/@mui/x-charts/-/x-charts-7.29.0.tgz",
+ "integrity": "sha512-sFkMaw4qSQwy9yYlT9/T21c2pOVI3OAqfvy9aQp+GaEbDjTuyWwcWRX4dkN2fb674qofSbRgk5VW9xrnuGuYNQ==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.25.7",
- "@mui/utils": "^5.16.6 || ^6.0.0",
+ "@mui/utils": "^5.16.6 || ^6.0.0 || ^7.0.0",
"@mui/x-charts-vendor": "7.20.0",
- "@mui/x-internals": "7.24.0",
+ "@mui/x-internals": "7.29.0",
"@react-spring/rafz": "^9.7.5",
"@react-spring/web": "^9.7.5",
"clsx": "^2.1.1",
@@ -1410,8 +1183,8 @@
"peerDependencies": {
"@emotion/react": "^11.9.0",
"@emotion/styled": "^11.8.1",
- "@mui/material": "^5.15.14 || ^6.0.0",
- "@mui/system": "^5.15.14 || ^6.0.0",
+ "@mui/material": "^5.15.14 || ^6.0.0 || ^7.0.0",
+ "@mui/system": "^5.15.14 || ^6.0.0 || ^7.0.0",
"react": "^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0"
},
@@ -1448,17 +1221,18 @@
}
},
"node_modules/@mui/x-data-grid": {
- "version": "7.24.0",
- "resolved": "https://registry.npmjs.org/@mui/x-data-grid/-/x-data-grid-7.24.0.tgz",
- "integrity": "sha512-goYTKDp+e+dXw7E+WndWUhWXTjX3aTqN8W2dCKhXnmE9Gu8dFwG6Azl7GK9l2m5YHGuqYmpWqcSG9etLdwYaVg==",
+ "version": "7.29.0",
+ "resolved": "https://registry.npmjs.org/@mui/x-data-grid/-/x-data-grid-7.29.0.tgz",
+ "integrity": "sha512-v3HiwcT/oqgv6xkynOd3oxH26IS0OvspgmfHtfPF9WeRsnUHcTTZ7E1EoAKjT9/Ms2f3oKKJAR6rZBZ5ymik1g==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.25.7",
- "@mui/utils": "^5.16.6 || ^6.0.0",
- "@mui/x-internals": "7.24.0",
+ "@mui/utils": "^5.16.6 || ^6.0.0 || ^7.0.0",
+ "@mui/x-internals": "7.29.0",
"clsx": "^2.1.1",
"prop-types": "^15.8.1",
- "reselect": "^5.1.1"
+ "reselect": "^5.1.1",
+ "use-sync-external-store": "^1.0.0"
},
"engines": {
"node": ">=14.0.0"
@@ -1470,8 +1244,8 @@
"peerDependencies": {
"@emotion/react": "^11.9.0",
"@emotion/styled": "^11.8.1",
- "@mui/material": "^5.15.14 || ^6.0.0",
- "@mui/system": "^5.15.14 || ^6.0.0",
+ "@mui/material": "^5.15.14 || ^6.0.0 || ^7.0.0",
+ "@mui/system": "^5.15.14 || ^6.0.0 || ^7.0.0",
"react": "^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0"
},
@@ -1485,14 +1259,14 @@
}
},
"node_modules/@mui/x-date-pickers": {
- "version": "7.24.0",
- "resolved": "https://registry.npmjs.org/@mui/x-date-pickers/-/x-date-pickers-7.24.0.tgz",
- "integrity": "sha512-oBM9Yp2H3tJ7qoHB4APQJYxZG4rz6JD4CwLzbzD9o3r+E1HGpGSLhwK3rDEz9VEjbOq8893Z2TGYLLWoyjeFXQ==",
+ "version": "7.29.0",
+ "resolved": "https://registry.npmjs.org/@mui/x-date-pickers/-/x-date-pickers-7.29.0.tgz",
+ "integrity": "sha512-6jpkbXB1/9/VLvlJ5wLs4M54fi9WeCpJSJ3I76MbZBKtZUDMFsuc3V5Mm4bsTd08xF6py1o+Qx2HapsE2gFhrg==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.25.7",
- "@mui/utils": "^5.16.6 || ^6.0.0",
- "@mui/x-internals": "7.24.0",
+ "@mui/utils": "^5.16.6 || ^6.0.0 || ^7.0.0",
+ "@mui/x-internals": "7.29.0",
"@types/react-transition-group": "^4.4.11",
"clsx": "^2.1.1",
"prop-types": "^15.8.1",
@@ -1508,8 +1282,8 @@
"peerDependencies": {
"@emotion/react": "^11.9.0",
"@emotion/styled": "^11.8.1",
- "@mui/material": "^5.15.14 || ^6.0.0",
- "@mui/system": "^5.15.14 || ^6.0.0",
+ "@mui/material": "^5.15.14 || ^6.0.0 || ^7.0.0",
+ "@mui/system": "^5.15.14 || ^6.0.0 || ^7.0.0",
"date-fns": "^2.25.0 || ^3.2.0 || ^4.0.0",
"date-fns-jalali": "^2.13.0-0 || ^3.2.0-0 || ^4.0.0-0",
"dayjs": "^1.10.7",
@@ -1551,13 +1325,13 @@
}
},
"node_modules/@mui/x-internals": {
- "version": "7.24.0",
- "resolved": "https://registry.npmjs.org/@mui/x-internals/-/x-internals-7.24.0.tgz",
- "integrity": "sha512-lYa/XLltxNMY8YAFDopIHrXda2EAoqMCilyGMuPMz+WTG+b+StlUKqtj8cgFPQ/sa5dQ2fR7R3KJdjLREKUrlQ==",
+ "version": "7.29.0",
+ "resolved": "https://registry.npmjs.org/@mui/x-internals/-/x-internals-7.29.0.tgz",
+ "integrity": "sha512-+Gk6VTZIFD70XreWvdXBwKd8GZ2FlSCuecQFzm6znwqXg1ZsndavrhG9tkxpxo2fM1Zf7Tk8+HcOO0hCbhTQFA==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.25.7",
- "@mui/utils": "^5.16.6 || ^6.0.0"
+ "@mui/utils": "^5.16.6 || ^6.0.0 || ^7.0.0"
},
"engines": {
"node": ">=14.0.0"
@@ -1618,6 +1392,21 @@
"url": "https://opencollective.com/popperjs"
}
},
+ "node_modules/@react-dnd/asap": {
+ "version": "5.0.2",
+ "resolved": "https://registry.npmjs.org/@react-dnd/asap/-/asap-5.0.2.tgz",
+ "integrity": "sha512-WLyfoHvxhs0V9U+GTsGilGgf2QsPl6ZZ44fnv0/b8T3nQyvzxidxsg/ZltbWssbsRDlYW8UKSQMTGotuTotZ6A=="
+ },
+ "node_modules/@react-dnd/invariant": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@react-dnd/invariant/-/invariant-4.0.2.tgz",
+ "integrity": "sha512-xKCTqAK/FFauOM9Ta2pswIyT3D8AQlfrYdOi/toTPEhqCuAs1v5tcJ3Y08Izh1cJ5Jchwy9SeAXmMg6zrKs2iw=="
+ },
+ "node_modules/@react-dnd/shallowequal": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@react-dnd/shallowequal/-/shallowequal-4.0.2.tgz",
+ "integrity": "sha512-/RVXdLvJxLg4QKvMoM5WlwNR9ViO9z8B/qPcc+C0Sa/teJY7QG7kJ441DwzOjMYEY7GmU4dj5EcGHIkKZiQZCA=="
+ },
"node_modules/@react-spring/animated": {
"version": "9.7.5",
"resolved": "https://registry.npmjs.org/@react-spring/animated/-/animated-9.7.5.tgz",
@@ -1691,11 +1480,13 @@
}
},
"node_modules/@reduxjs/toolkit": {
- "version": "2.5.0",
- "resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.5.0.tgz",
- "integrity": "sha512-awNe2oTodsZ6LmRqmkFhtb/KH03hUhxOamEQy411m3Njj3BbFvoBovxo4Q1cBWnV1ErprVj9MlF0UPXkng0eyg==",
+ "version": "2.7.0",
+ "resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.7.0.tgz",
+ "integrity": "sha512-XVwolG6eTqwV0N8z/oDlN93ITCIGIop6leXlGJI/4EKy+0POYkR+ABHRSdGXY+0MQvJBP8yAzh+EYFxTuvmBiQ==",
"license": "MIT",
"dependencies": {
+ "@standard-schema/spec": "^1.0.0",
+ "@standard-schema/utils": "^0.3.0",
"immer": "^10.0.3",
"redux": "^5.0.1",
"redux-thunk": "^3.1.0",
@@ -1715,9 +1506,9 @@
}
},
"node_modules/@remix-run/router": {
- "version": "1.21.1",
- "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.21.1.tgz",
- "integrity": "sha512-KeBYSwohb8g4/wCcnksvKTYlg69O62sQeLynn2YE+5z7JWEj95if27kclW9QqbrlsQ2DINI8fjbV3zyuKfwjKg==",
+ "version": "1.23.0",
+ "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.0.tgz",
+ "integrity": "sha512-O3rHJzAQKamUz1fvE0Qaw0xSFqsA/yafi2iqeE0pvdFtCO1viYx8QL6f3Ln/aCCTLxs68SLf0KPM9eSeM8yBnA==",
"license": "MIT",
"engines": {
"node": ">=14.0.0"
@@ -1745,175 +1536,6 @@
}
}
},
- "node_modules/@rollup/rollup-android-arm-eabi": {
- "version": "4.27.4",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.27.4.tgz",
- "integrity": "sha512-2Y3JT6f5MrQkICUyRVCw4oa0sutfAsgaSsb0Lmmy1Wi2y7X5vT9Euqw4gOsCyy0YfKURBg35nhUKZS4mDcfULw==",
- "cpu": [
- "arm"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "android"
- ]
- },
- "node_modules/@rollup/rollup-android-arm64": {
- "version": "4.27.4",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.27.4.tgz",
- "integrity": "sha512-wzKRQXISyi9UdCVRqEd0H4cMpzvHYt1f/C3CoIjES6cG++RHKhrBj2+29nPF0IB5kpy9MS71vs07fvrNGAl/iA==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "android"
- ]
- },
- "node_modules/@rollup/rollup-darwin-arm64": {
- "version": "4.27.4",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.27.4.tgz",
- "integrity": "sha512-PlNiRQapift4LNS8DPUHuDX/IdXiLjf8mc5vdEmUR0fF/pyy2qWwzdLjB+iZquGr8LuN4LnUoSEvKRwjSVYz3Q==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ]
- },
- "node_modules/@rollup/rollup-darwin-x64": {
- "version": "4.27.4",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.27.4.tgz",
- "integrity": "sha512-o9bH2dbdgBDJaXWJCDTNDYa171ACUdzpxSZt+u/AAeQ20Nk5x+IhA+zsGmrQtpkLiumRJEYef68gcpn2ooXhSQ==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ]
- },
- "node_modules/@rollup/rollup-freebsd-arm64": {
- "version": "4.27.4",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.27.4.tgz",
- "integrity": "sha512-NBI2/i2hT9Q+HySSHTBh52da7isru4aAAo6qC3I7QFVsuhxi2gM8t/EI9EVcILiHLj1vfi+VGGPaLOUENn7pmw==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "freebsd"
- ]
- },
- "node_modules/@rollup/rollup-freebsd-x64": {
- "version": "4.27.4",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.27.4.tgz",
- "integrity": "sha512-wYcC5ycW2zvqtDYrE7deary2P2UFmSh85PUpAx+dwTCO9uw3sgzD6Gv9n5X4vLaQKsrfTSZZ7Z7uynQozPVvWA==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "freebsd"
- ]
- },
- "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
- "version": "4.27.4",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.27.4.tgz",
- "integrity": "sha512-9OwUnK/xKw6DyRlgx8UizeqRFOfi9mf5TYCw1uolDaJSbUmBxP85DE6T4ouCMoN6pXw8ZoTeZCSEfSaYo+/s1w==",
- "cpu": [
- "arm"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/@rollup/rollup-linux-arm-musleabihf": {
- "version": "4.27.4",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.27.4.tgz",
- "integrity": "sha512-Vgdo4fpuphS9V24WOV+KwkCVJ72u7idTgQaBoLRD0UxBAWTF9GWurJO9YD9yh00BzbkhpeXtm6na+MvJU7Z73A==",
- "cpu": [
- "arm"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/@rollup/rollup-linux-arm64-gnu": {
- "version": "4.27.4",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.27.4.tgz",
- "integrity": "sha512-pleyNgyd1kkBkw2kOqlBx+0atfIIkkExOTiifoODo6qKDSpnc6WzUY5RhHdmTdIJXBdSnh6JknnYTtmQyobrVg==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/@rollup/rollup-linux-arm64-musl": {
- "version": "4.27.4",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.27.4.tgz",
- "integrity": "sha512-caluiUXvUuVyCHr5DxL8ohaaFFzPGmgmMvwmqAITMpV/Q+tPoaHZ/PWa3t8B2WyoRcIIuu1hkaW5KkeTDNSnMA==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/@rollup/rollup-linux-powerpc64le-gnu": {
- "version": "4.27.4",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.27.4.tgz",
- "integrity": "sha512-FScrpHrO60hARyHh7s1zHE97u0KlT/RECzCKAdmI+LEoC1eDh/RDji9JgFqyO+wPDb86Oa/sXkily1+oi4FzJQ==",
- "cpu": [
- "ppc64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/@rollup/rollup-linux-riscv64-gnu": {
- "version": "4.27.4",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.27.4.tgz",
- "integrity": "sha512-qyyprhyGb7+RBfMPeww9FlHwKkCXdKHeGgSqmIXw9VSUtvyFZ6WZRtnxgbuz76FK7LyoN8t/eINRbPUcvXB5fw==",
- "cpu": [
- "riscv64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/@rollup/rollup-linux-s390x-gnu": {
- "version": "4.27.4",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.27.4.tgz",
- "integrity": "sha512-PFz+y2kb6tbh7m3A7nA9++eInGcDVZUACulf/KzDtovvdTizHpZaJty7Gp0lFwSQcrnebHOqxF1MaKZd7psVRg==",
- "cpu": [
- "s390x"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
"node_modules/@rollup/rollup-linux-x64-gnu": {
"version": "4.27.4",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.27.4.tgz",
@@ -1940,45 +1562,6 @@
"linux"
]
},
- "node_modules/@rollup/rollup-win32-arm64-msvc": {
- "version": "4.27.4",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.27.4.tgz",
- "integrity": "sha512-yOpVsA4K5qVwu2CaS3hHxluWIK5HQTjNV4tWjQXluMiiiu4pJj4BN98CvxohNCpcjMeTXk/ZMJBRbgRg8HBB6A==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ]
- },
- "node_modules/@rollup/rollup-win32-ia32-msvc": {
- "version": "4.27.4",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.27.4.tgz",
- "integrity": "sha512-KtwEJOaHAVJlxV92rNYiG9JQwQAdhBlrjNRp7P9L8Cb4Rer3in+0A+IPhJC9y68WAi9H0sX4AiG2NTsVlmqJeQ==",
- "cpu": [
- "ia32"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ]
- },
- "node_modules/@rollup/rollup-win32-x64-msvc": {
- "version": "4.27.4",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.27.4.tgz",
- "integrity": "sha512-3j4jx1TppORdTAoBJRd+/wJRGCPC0ETWkXOecJ6PPZLj6SptXkrXcNqdj0oclbKML6FkQltdz7bBA3rUSirZug==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ]
- },
"node_modules/@sideway/address": {
"version": "4.1.5",
"resolved": "https://registry.npmjs.org/@sideway/address/-/address-4.1.5.tgz",
@@ -2000,6 +1583,18 @@
"integrity": "sha512-RNiOoTPkptFtSVzQevY/yWtZwf/RxyVnPy/OcA9HBM3MlGDnBEYL5B41H0MTn0Uec8Hi+2qUtTfG2WWZBmMejQ==",
"license": "BSD-3-Clause"
},
+ "node_modules/@standard-schema/spec": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.0.0.tgz",
+ "integrity": "sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==",
+ "license": "MIT"
+ },
+ "node_modules/@standard-schema/utils": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
+ "integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
+ "license": "MIT"
+ },
"node_modules/@svgr/babel-plugin-add-jsx-attribute": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/@svgr/babel-plugin-add-jsx-attribute/-/babel-plugin-add-jsx-attribute-8.0.0.tgz",
@@ -2359,12 +1954,61 @@
"integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==",
"license": "MIT"
},
+ "node_modules/@types/geojson": {
+ "version": "7946.0.16",
+ "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
+ "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
+ "license": "MIT"
+ },
+ "node_modules/@types/geojson-vt": {
+ "version": "3.2.5",
+ "resolved": "https://registry.npmjs.org/@types/geojson-vt/-/geojson-vt-3.2.5.tgz",
+ "integrity": "sha512-qDO7wqtprzlpe8FfQ//ClPV9xiuoh2nkIgiouIptON9w5jvD/fA4szvP9GBlDVdJ5dldAl0kX/sy3URbWwLx0g==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/geojson": "*"
+ }
+ },
+ "node_modules/@types/mapbox__point-geometry": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/@types/mapbox__point-geometry/-/mapbox__point-geometry-0.1.4.tgz",
+ "integrity": "sha512-mUWlSxAmYLfwnRBmgYV86tgYmMIICX4kza8YnE/eIlywGe2XoOxlpVnXWwir92xRLjwyarqwpu2EJKD2pk0IUA==",
+ "license": "MIT"
+ },
+ "node_modules/@types/mapbox__vector-tile": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@types/mapbox__vector-tile/-/mapbox__vector-tile-1.3.4.tgz",
+ "integrity": "sha512-bpd8dRn9pr6xKvuEBQup8pwQfD4VUyqO/2deGjfpe6AwC8YRlyEipvefyRJUSiCJTZuCb8Pl1ciVV5ekqJ96Bg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/geojson": "*",
+ "@types/mapbox__point-geometry": "*",
+ "@types/pbf": "*"
+ }
+ },
+ "node_modules/@types/node": {
+ "version": "22.13.2",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.13.2.tgz",
+ "integrity": "sha512-Z+r8y3XL9ZpI2EY52YYygAFmo2/oWfNSj4BCpAXE2McAexDk8VcnBMGC9Djn9gTKt4d2T/hhXqmPzo4hfIXtTg==",
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "undici-types": "~6.20.0"
+ }
+ },
"node_modules/@types/parse-json": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.2.tgz",
"integrity": "sha512-dISoDXWWQwUquiKsyZ4Ng+HX2KsPL7LyHKHQwgGFEA3IaKac4Obd+h2a/a6waisAoepJlBcx9paWqjA8/HVjCw==",
"license": "MIT"
},
+ "node_modules/@types/pbf": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/@types/pbf/-/pbf-3.0.5.tgz",
+ "integrity": "sha512-j3pOPiEcWZ34R6a6mN07mUkM4o4Lwf6hPNt8eilOeZhTFbxFXmKhvXl9Y28jotFPaI1bpPDJsbCprUoNke6OrA==",
+ "license": "MIT"
+ },
"node_modules/@types/prop-types": {
"version": "15.7.14",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.14.tgz",
@@ -2372,9 +2016,9 @@
"license": "MIT"
},
"node_modules/@types/react": {
- "version": "18.3.18",
- "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.18.tgz",
- "integrity": "sha512-t4yC+vtgnkYjNSKlFx1jkAhH8LgTo2N/7Qvi83kdEaUtMDiwpbLAktKDaAMlRcJ5eSxZkH74eEGt1ky31d7kfQ==",
+ "version": "18.3.20",
+ "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.20.tgz",
+ "integrity": "sha512-IPaCZN7PShZK/3t6Q87pfTkRm6oLTd4vztyoj+cbHUF1g3FfVb2tFIL79uCRKEfv16AhqDMBywP2VW3KIZUvcg==",
"license": "MIT",
"dependencies": {
"@types/prop-types": "*",
@@ -2382,9 +2026,9 @@
}
},
"node_modules/@types/react-dom": {
- "version": "18.3.5",
- "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.5.tgz",
- "integrity": "sha512-P4t6saawp+b/dFrUr2cvkVsfvPguwsxtH6dNIYRllMsefqFzkZk5UIjzyDOv5g1dXIPdG4Sp1yCR4Z6RCUsG/Q==",
+ "version": "18.3.6",
+ "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.6.tgz",
+ "integrity": "sha512-nf22//wEbKXusP6E9pfOCDwFdHAX4u172eaJI4YkDRQEZiorm6KfYnSC2SWLDMVWUOWPERmJnN0ujeAfTBLvrw==",
"dev": true,
"license": "MIT",
"peerDependencies": {
@@ -2400,6 +2044,15 @@
"@types/react": "*"
}
},
+ "node_modules/@types/supercluster": {
+ "version": "7.1.3",
+ "resolved": "https://registry.npmjs.org/@types/supercluster/-/supercluster-7.1.3.tgz",
+ "integrity": "sha512-Z0pOY34GDFl3Q6hUFYf3HkTwKEE02e7QgtJppBt+beEAxnyOpJua+voGFvxINBHa06GwLFFym7gRPY2SiKIfIA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/geojson": "*"
+ }
+ },
"node_modules/@types/use-sync-external-store": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",
@@ -2414,17 +2067,17 @@
"license": "ISC"
},
"node_modules/@vitejs/plugin-react": {
- "version": "4.3.4",
- "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.3.4.tgz",
- "integrity": "sha512-SCCPBJtYLdE8PX/7ZQAs1QAZ8Jqwih+0VBLum1EGqmCCQal+MIUqLCzj3ZUy8ufbC0cAM4LRlSTm7IQJwWT4ug==",
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.4.0.tgz",
+ "integrity": "sha512-x/EztcTKVj+TDeANY1WjNeYsvZjZdfWRMP/KXi5Yn8BoTzpa13ZltaQqKfvWYbX8CE10GOHHdC5v86jY9x8i/g==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/core": "^7.26.0",
+ "@babel/core": "^7.26.10",
"@babel/plugin-transform-react-jsx-self": "^7.25.9",
"@babel/plugin-transform-react-jsx-source": "^7.25.9",
"@types/babel__core": "^7.20.5",
- "react-refresh": "^0.14.2"
+ "react-refresh": "^0.17.0"
},
"engines": {
"node": "^14.18.0 || >=16.0.0"
@@ -2433,11 +2086,21 @@
"vite": "^4.2.0 || ^5.0.0 || ^6.0.0"
}
},
+ "node_modules/@vitejs/plugin-react/node_modules/react-refresh": {
+ "version": "0.17.0",
+ "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz",
+ "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/acorn": {
"version": "8.14.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz",
"integrity": "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==",
- "dev": true,
+ "devOptional": true,
"license": "MIT",
"bin": {
"acorn": "bin/acorn"
@@ -2664,9 +2327,9 @@
}
},
"node_modules/axios": {
- "version": "1.7.9",
- "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz",
- "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==",
+ "version": "1.8.4",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.4.tgz",
+ "integrity": "sha512-eBSYY4Y68NNlHbHBMdeDmKNtDgXWhQsJcGqzO3iLUM0GraQFSS9cVgPX5I9b3lbdFKyYoAEGAZF1DwhTaljNAw==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
@@ -2696,6 +2359,14 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/base64-arraybuffer": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-1.0.2.tgz",
+ "integrity": "sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==",
+ "engines": {
+ "node": ">= 0.6.0"
+ }
+ },
"node_modules/brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
@@ -2708,9 +2379,9 @@
}
},
"node_modules/browserslist": {
- "version": "4.24.2",
- "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.24.2.tgz",
- "integrity": "sha512-ZIc+Q62revdMcqC6aChtW4jz3My3klmCO1fEmINZY/8J3EpBg5/A/D0AKmBveUh6pgoeycoMkVMko84tuYS+Gg==",
+ "version": "4.24.4",
+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.24.4.tgz",
+ "integrity": "sha512-KDi1Ny1gSePi1vm0q4oxSF8b4DR44GF4BbmS2YdhPLOEqd8pDviZOGH/GsmRwoWJ2+5Lr085X7naowMwKHDG1A==",
"funding": [
{
"type": "opencollective",
@@ -2727,9 +2398,9 @@
],
"license": "MIT",
"dependencies": {
- "caniuse-lite": "^1.0.30001669",
- "electron-to-chromium": "^1.5.41",
- "node-releases": "^2.0.18",
+ "caniuse-lite": "^1.0.30001688",
+ "electron-to-chromium": "^1.5.73",
+ "node-releases": "^2.0.19",
"update-browserslist-db": "^1.1.1"
},
"bin": {
@@ -2739,6 +2410,14 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
+ "node_modules/buffer-from": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
+ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
+ "license": "MIT",
+ "optional": true,
+ "peer": true
+ },
"node_modules/call-bind": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.8.tgz",
@@ -2759,9 +2438,9 @@
}
},
"node_modules/call-bind-apply-helpers": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.1.tgz",
- "integrity": "sha512-BhYE+WDaywFg2TBWYNXAE+8B1ATnThNBqXHP5nQu0jWJdVvY2hvkpyB3qOmtmDePiS5/BDQ8wASEWGMWRG148g==",
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -2773,14 +2452,14 @@
}
},
"node_modules/call-bound": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.3.tgz",
- "integrity": "sha512-YTd+6wGlNlPxSuri7Y6X8tY2dmm12UMH66RpKMhiX6rsk5wXXnYgbUcOt8kiS31/AjfoTOvCsE+w8nZQLQnzHA==",
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "call-bind-apply-helpers": "^1.0.1",
- "get-intrinsic": "^1.2.6"
+ "call-bind-apply-helpers": "^1.0.2",
+ "get-intrinsic": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
@@ -2811,9 +2490,9 @@
}
},
"node_modules/caniuse-lite": {
- "version": "1.0.30001684",
- "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001684.tgz",
- "integrity": "sha512-G1LRwLIQjBQoyq0ZJGqGIJUXzJ8irpbjHLpVRXDvBEScFJ9b17sgK6vlx0GAJFE21okD7zXl08rRRUfq6HdoEQ==",
+ "version": "1.0.30001699",
+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001699.tgz",
+ "integrity": "sha512-b+uH5BakXZ9Do9iK+CkDmctUSEqZl+SP056vc5usa0PL+ev5OHw003rZXcnjNDv3L8P5j6rwT6C0BPKSikW08w==",
"funding": [
{
"type": "opencollective",
@@ -2932,6 +2611,22 @@
"node": ">= 8"
}
},
+ "node_modules/css-box-model": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/css-box-model/-/css-box-model-1.2.1.tgz",
+ "integrity": "sha512-a7Vr4Q/kd/aw96bnJG332W9V9LkJO69JRcaCYDUqjp6/z0w6VcZjgAcTbgFxEPfBgdnAwlh3iwu+hLopa+flJw==",
+ "dependencies": {
+ "tiny-invariant": "^1.0.6"
+ }
+ },
+ "node_modules/css-line-break": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/css-line-break/-/css-line-break-2.1.0.tgz",
+ "integrity": "sha512-FHcKFCZcAha3LwfVBhCQbW2nCNbkZXn7KVUJcsT5/P8YmfsVja0FMPJr0B903j/E69HUphKiV9iQArX8SDYA4w==",
+ "dependencies": {
+ "utrie": "^1.0.2"
+ }
+ },
"node_modules/csstype": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
@@ -3215,6 +2910,24 @@
"node": ">=0.4.0"
}
},
+ "node_modules/dnd-core": {
+ "version": "16.0.1",
+ "resolved": "https://registry.npmjs.org/dnd-core/-/dnd-core-16.0.1.tgz",
+ "integrity": "sha512-HK294sl7tbw6F6IeuK16YSBUoorvHpY8RHO+9yFfaJyCDVb6n7PRcezrOEOa2SBCqiYpemh5Jx20ZcjKdFAVng==",
+ "dependencies": {
+ "@react-dnd/asap": "^5.0.1",
+ "@react-dnd/invariant": "^4.0.1",
+ "redux": "^4.2.0"
+ }
+ },
+ "node_modules/dnd-core/node_modules/redux": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/redux/-/redux-4.2.1.tgz",
+ "integrity": "sha512-LAUYz4lc+Do8/g7aeRa8JkyDErK6ekstQaqWQrNRW//MY1TvCEpMtpTWvlQ+FPbWCx+Xixu/6SHt5N0HR+SB4w==",
+ "dependencies": {
+ "@babel/runtime": "^7.9.2"
+ }
+ },
"node_modules/doctrine": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz",
@@ -3263,10 +2976,16 @@
"node": ">= 0.4"
}
},
+ "node_modules/earcut": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/earcut/-/earcut-3.0.1.tgz",
+ "integrity": "sha512-0l1/0gOjESMeQyYaK5IDiPNvFeu93Z/cO0TjZh9eZ1vyCtZnA7KMZ8rQggpsJHIbGSdrqYq9OhuveadOVHCshw==",
+ "license": "ISC"
+ },
"node_modules/electron-to-chromium": {
- "version": "1.5.65",
- "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.65.tgz",
- "integrity": "sha512-PWVzBjghx7/wop6n22vS2MLU8tKGd4Q91aCEGhG/TYmW6PP5OcSXcdnxTe1NNt0T66N8D6jxh4kC8UsdzOGaIw==",
+ "version": "1.5.99",
+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.99.tgz",
+ "integrity": "sha512-77c/+fCyL2U+aOyqfIFi89wYLBeSTCs55xCZL0oFH0KjqsvSvyh6AdQ+UIl1vgpnQQE6g+/KK8hOIupH6VwPtg==",
"license": "ISC"
},
"node_modules/entities": {
@@ -3401,9 +3120,9 @@
}
},
"node_modules/es-object-atoms": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.0.0.tgz",
- "integrity": "sha512-MZ4iQ6JwHOBQjahnjwaC1ZtIBH+2ohjamzAO3oaHcXYup7qxjF2fixyH+Q71voWHeOkI2q/TnJao/KfXYIZWbw==",
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -3573,9 +3292,9 @@
}
},
"node_modules/eslint-plugin-react": {
- "version": "7.37.4",
- "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.37.4.tgz",
- "integrity": "sha512-BGP0jRmfYyvOyvMoRX/uoUeW+GqNj9y16bPQzqAHf3AYII/tDs+jMN0dBVkl88/OZwNGwrVFxE7riHsXVfy/LQ==",
+ "version": "7.37.5",
+ "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.37.5.tgz",
+ "integrity": "sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -3589,7 +3308,7 @@
"hasown": "^2.0.2",
"jsx-ast-utils": "^2.4.1 || ^3.0.0",
"minimatch": "^3.1.2",
- "object.entries": "^1.1.8",
+ "object.entries": "^1.1.9",
"object.fromentries": "^2.0.8",
"object.values": "^1.2.1",
"prop-types": "^15.8.1",
@@ -3606,9 +3325,9 @@
}
},
"node_modules/eslint-plugin-react-hooks": {
- "version": "5.1.0",
- "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-5.1.0.tgz",
- "integrity": "sha512-mpJRtPgHN2tNAvZ35AMfqeB3Xqeo273QxrHJsbBEPWODRM4r0yB6jfoROqKEYrOn27UtRPpcpHc2UqyBSuUNTw==",
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-5.2.0.tgz",
+ "integrity": "sha512-+f15FfK64YQwZdJNELETdn5ibXEUQmW1DZL6KXhNnc2heoy/sg9VJJeT7n8TlMWouzWqSWavFkIhHyIbIAEapg==",
"dev": true,
"license": "MIT",
"engines": {
@@ -3619,9 +3338,9 @@
}
},
"node_modules/eslint-plugin-react-refresh": {
- "version": "0.4.18",
- "resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.4.18.tgz",
- "integrity": "sha512-IRGEoFn3OKalm3hjfolEWGqoF/jPqeEYFp+C8B0WMzwGwBMvlRDQd06kghDhF0C61uJ6WfSDhEZE/sAQjduKgw==",
+ "version": "0.4.19",
+ "resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.4.19.tgz",
+ "integrity": "sha512-eyy8pcr/YxSYjBoqIFSrlbn9i/xvxUFa8CjzAYo9cFjgGXqq1hyjihcpZvxRLalpaWmueWR81xn7vuKmAFijDQ==",
"dev": true,
"license": "MIT",
"peerDependencies": {
@@ -3785,7 +3504,6 @@
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
- "dev": true,
"license": "MIT"
},
"node_modules/fast-equals": {
@@ -3857,6 +3575,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/flag-icons": {
+ "version": "7.3.2",
+ "resolved": "https://registry.npmjs.org/flag-icons/-/flag-icons-7.3.2.tgz",
+ "integrity": "sha512-QkaZ6Zvai8LIjx+UNAHUJ5Dhz9OLZpBDwCRWxF6YErxIcR16jTkIFm3bFu54EkvKQy4+wicW+Gm7/0631wVQyQ==",
+ "license": "MIT"
+ },
"node_modules/flat-cache": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz",
@@ -3993,23 +3717,29 @@
"node": ">=6.9.0"
}
},
+ "node_modules/geojson-vt": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/geojson-vt/-/geojson-vt-4.0.2.tgz",
+ "integrity": "sha512-AV9ROqlNqoZEIJGfm1ncNjEXfkz2hdFlZf0qkVfmkwdKa8vj7H16YUOT81rJw1rdFhyEDlN2Tds91p/glzbl5A==",
+ "license": "ISC"
+ },
"node_modules/get-intrinsic": {
- "version": "1.2.6",
- "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.6.tgz",
- "integrity": "sha512-qxsEs+9A+u85HhllWJJFicJfPDhRmjzoYdl64aMWW9yRIJmSyxdn8IEkuIM530/7T+lv0TIHd8L6Q/ra0tEoeA==",
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "call-bind-apply-helpers": "^1.0.1",
- "dunder-proto": "^1.0.0",
+ "call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
- "es-object-atoms": "^1.0.0",
+ "es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
+ "get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
- "math-intrinsics": "^1.0.0"
+ "math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
@@ -4018,6 +3748,32 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/get-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "dunder-proto": "^1.0.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/get-stream": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz",
+ "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/get-symbol-description": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz",
@@ -4036,6 +3792,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/gl-matrix": {
+ "version": "3.4.3",
+ "resolved": "https://registry.npmjs.org/gl-matrix/-/gl-matrix-3.4.3.tgz",
+ "integrity": "sha512-wcCp8vu8FT22BnvKVPjXa/ICBWRq/zjFfdofZy1WSpQZpphblv12/bOQLBC1rMM7SGOFS9ltVmKOHil5+Ml7gA==",
+ "license": "MIT"
+ },
"node_modules/glob": {
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
@@ -4071,6 +3833,44 @@
"node": ">=10.13.0"
}
},
+ "node_modules/global-prefix": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-4.0.0.tgz",
+ "integrity": "sha512-w0Uf9Y9/nyHinEk5vMJKRie+wa4kR5hmDbEhGGds/kG1PwGLLHKRoNMeJOyCQjjBkANlnScqgzcFwGHgmgLkVA==",
+ "license": "MIT",
+ "dependencies": {
+ "ini": "^4.1.3",
+ "kind-of": "^6.0.3",
+ "which": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/global-prefix/node_modules/isexe": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.1.tgz",
+ "integrity": "sha512-LpB/54B+/2J5hqQ7imZHfdU31OlgQqx7ZicVlkm9kzg9/w8GKLEcFfJl/t7DCEDueOyBAD6zCCwTO6Fzs0NoEQ==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/global-prefix/node_modules/which": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/which/-/which-4.0.0.tgz",
+ "integrity": "sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg==",
+ "license": "ISC",
+ "dependencies": {
+ "isexe": "^3.1.1"
+ },
+ "bin": {
+ "node-which": "bin/which.js"
+ },
+ "engines": {
+ "node": "^16.13.0 || >=18.0.0"
+ }
+ },
"node_modules/globals": {
"version": "11.12.0",
"resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz",
@@ -4222,6 +4022,77 @@
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
"license": "MIT"
},
+ "node_modules/html-parse-stringify": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-3.0.1.tgz",
+ "integrity": "sha512-KknJ50kTInJ7qIScF3jeaFRpMpE8/lfiTdzf/twXyPBLAGrLRTmkz3AdTnKeh40X8k9L2fdYwEp/42WGXIRGcg==",
+ "dependencies": {
+ "void-elements": "3.1.0"
+ }
+ },
+ "node_modules/html2canvas": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/html2canvas/-/html2canvas-1.4.1.tgz",
+ "integrity": "sha512-fPU6BHNpsyIhr8yyMpTLLxAbkaK8ArIBcmZIRiBLiDhjeqvXolaEmDGmELFuX9I4xDcaKKcJl+TKZLqruBbmWA==",
+ "dependencies": {
+ "css-line-break": "^2.1.0",
+ "text-segmentation": "^1.0.3"
+ },
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
+ "node_modules/i18next": {
+ "version": "24.2.3",
+ "resolved": "https://registry.npmjs.org/i18next/-/i18next-24.2.3.tgz",
+ "integrity": "sha512-lfbf80OzkocvX7nmZtu7nSTNbrTYR52sLWxPtlXX1zAhVw8WEnFk4puUkCR4B1dNQwbSpEHHHemcZu//7EcB7A==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://locize.com"
+ },
+ {
+ "type": "individual",
+ "url": "https://locize.com/i18next.html"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.26.10"
+ },
+ "peerDependencies": {
+ "typescript": "^5"
+ },
+ "peerDependenciesMeta": {
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/ieee754": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
"node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
@@ -4242,6 +4113,11 @@
"url": "https://opencollective.com/immer"
}
},
+ "node_modules/immutability-helper": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/immutability-helper/-/immutability-helper-3.1.1.tgz",
+ "integrity": "sha512-Q0QaXjPjwIju/28TsugCHNEASwoCcJSyJV3uO1sOIQGI0jKgm9f41Lvz0DZj3n46cNCyAZTsEYoY4C2bVRUzyQ=="
+ },
"node_modules/import-fresh": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz",
@@ -4287,6 +4163,15 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/ini": {
+ "version": "4.1.3",
+ "resolved": "https://registry.npmjs.org/ini/-/ini-4.1.3.tgz",
+ "integrity": "sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg==",
+ "license": "ISC",
+ "engines": {
+ "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
+ }
+ },
"node_modules/internal-slot": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz",
@@ -4789,6 +4674,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/json-stringify-pretty-compact": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/json-stringify-pretty-compact/-/json-stringify-pretty-compact-4.0.0.tgz",
+ "integrity": "sha512-3CNZ2DnrpByG9Nqj6Xo8vqbjT4F6N+tb4Gb28ESAZjYZ5yqvmc56J+/kuIwkaAMOyblTQhUW7PxMkUb8Q36N3Q==",
+ "license": "MIT"
+ },
"node_modules/json5": {
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
@@ -4826,6 +4717,12 @@
"node": ">=18"
}
},
+ "node_modules/kdbush": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/kdbush/-/kdbush-4.0.2.tgz",
+ "integrity": "sha512-WbCVYJ27Sz8zi9Q7Q0xHC+05iwkm3Znipc2XTlrnJbsHMYktW4hPhXUE8Ys1engBrvffoSCqbil1JQAa7clRpA==",
+ "license": "ISC"
+ },
"node_modules/keyv": {
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
@@ -4836,6 +4733,15 @@
"json-buffer": "3.0.1"
}
},
+ "node_modules/kind-of": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",
+ "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/levn": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",
@@ -4915,6 +4821,47 @@
"yallist": "^3.0.2"
}
},
+ "node_modules/maplibre-gl": {
+ "version": "5.3.1",
+ "resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-5.3.1.tgz",
+ "integrity": "sha512-Ihx+oUUSsZkjMou1Cw5J6silE+5OtFFQSPslWF9+7v4yFC/XDHrpsORYO9lWE4KZI0djCEUpZQJpkpnMArAbeA==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@mapbox/geojson-rewind": "^0.5.2",
+ "@mapbox/jsonlint-lines-primitives": "^2.0.2",
+ "@mapbox/point-geometry": "^0.1.0",
+ "@mapbox/tiny-sdf": "^2.0.6",
+ "@mapbox/unitbezier": "^0.0.1",
+ "@mapbox/vector-tile": "^1.3.1",
+ "@mapbox/whoots-js": "^3.1.0",
+ "@maplibre/maplibre-gl-style-spec": "^23.1.0",
+ "@types/geojson": "^7946.0.16",
+ "@types/geojson-vt": "3.2.5",
+ "@types/mapbox__point-geometry": "^0.1.4",
+ "@types/mapbox__vector-tile": "^1.3.4",
+ "@types/pbf": "^3.0.5",
+ "@types/supercluster": "^7.1.3",
+ "earcut": "^3.0.1",
+ "geojson-vt": "^4.0.2",
+ "gl-matrix": "^3.4.3",
+ "global-prefix": "^4.0.0",
+ "kdbush": "^4.0.2",
+ "murmurhash-js": "^1.0.0",
+ "pbf": "^3.3.0",
+ "potpack": "^2.0.0",
+ "quickselect": "^3.0.0",
+ "supercluster": "^8.0.1",
+ "tinyqueue": "^3.0.0",
+ "vt-pbf": "^3.1.3"
+ },
+ "engines": {
+ "node": ">=16.14.0",
+ "npm": ">=8.1.0"
+ },
+ "funding": {
+ "url": "https://github.com/maplibre/maplibre-gl-js?sponsor=1"
+ }
+ },
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@@ -4959,12 +4906,49 @@
"node": "*"
}
},
+ "node_modules/minimist": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
+ "node_modules/mui-color-input": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/mui-color-input/-/mui-color-input-6.0.0.tgz",
+ "integrity": "sha512-F9n/RqPLq7fnPWeF53/qssbIHvart7clpOfE+f+dsM+3ddfawwg98+PEhzv3cdAYlJLE9zfVViVTsp/ckUUd3g==",
+ "license": "MIT",
+ "dependencies": {
+ "@ctrl/tinycolor": "^4.1.0"
+ },
+ "peerDependencies": {
+ "@emotion/react": "^11.13.0",
+ "@emotion/styled": "^11.13.0",
+ "@mui/material": "^6.0.0",
+ "@types/react": "^18.0.0 || ^19.0.0",
+ "react": "^18.0.0 || ^19.0.0",
+ "react-dom": "^18.0.0 || ^19.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/murmurhash-js": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/murmurhash-js/-/murmurhash-js-1.0.0.tgz",
+ "integrity": "sha512-TvmkNhkv8yct0SVBSy+o8wYzXjE4Zz3PCesbfs8HiCXXdcTuocApFv11UWlNFWKYsP2okqrhb7JNlSm9InBhIw==",
+ "license": "MIT"
+ },
"node_modules/nanoid": {
"version": "3.3.8",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.8.tgz",
@@ -5000,9 +4984,9 @@
}
},
"node_modules/node-releases": {
- "version": "2.0.18",
- "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.18.tgz",
- "integrity": "sha512-d9VeXT4SJ7ZeOqGX6R5EM022wpL+eWPooLI+5UpWn2jCT1aosUQEhQP214x33Wkwx3JQMvIm+tIoVOdodFS40g==",
+ "version": "2.0.19",
+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.19.tgz",
+ "integrity": "sha512-xxOWJsBKtzAq7DY0J+DTzuz58K8e7sJbdgwkbMWQe8UYB6ekmsQ45q0M/tJDsGaZmbC+l7n57UV8Hl5tHxO9uw==",
"license": "MIT"
},
"node_modules/object-assign": {
@@ -5059,15 +5043,16 @@
}
},
"node_modules/object.entries": {
- "version": "1.1.8",
- "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.8.tgz",
- "integrity": "sha512-cmopxi8VwRIAw/fkijJohSfpef5PdN0pMQJN6VC/ZKvn0LIknWD8KtgY6KlQdEc4tIjcQ3HxSMmnvtzIscdaYQ==",
+ "version": "1.1.9",
+ "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.9.tgz",
+ "integrity": "sha512-8u/hfXFRBD1O0hPUjioLhoWFHRmt6tKA4/vZPyckBr18l1KE9uHrFaFaUi8MDRTpi4uak2goyPTSNJLXX2k2Hw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "call-bind": "^1.0.7",
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.4",
"define-properties": "^1.2.1",
- "es-object-atoms": "^1.0.0"
+ "es-object-atoms": "^1.1.1"
},
"engines": {
"node": ">= 0.4"
@@ -5246,6 +5231,19 @@
"node": ">=8"
}
},
+ "node_modules/pbf": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/pbf/-/pbf-3.3.0.tgz",
+ "integrity": "sha512-XDF38WCH3z5OV/OVa8GKUNtLAyneuzbCisx7QUCF8Q6Nutx0WnJrQe5O+kOtBlLfRNUws98Y58Lblp+NJG5T4Q==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "ieee754": "^1.1.12",
+ "resolve-protobuf-schema": "^2.1.0"
+ },
+ "bin": {
+ "pbf": "bin/pbf"
+ }
+ },
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -5302,6 +5300,12 @@
"node": "^10 || ^12 || >=14"
}
},
+ "node_modules/potpack": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/potpack/-/potpack-2.0.0.tgz",
+ "integrity": "sha512-Q+/tYsFU9r7xoOJ+y/ZTtdVQwTWfzjbiXBDMM/JKUux3+QPP02iUuIoeBQ+Ot6oEDlC+/PGjB/5A3K7KKb7hcw==",
+ "license": "ISC"
+ },
"node_modules/prelude-ls": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
@@ -5313,9 +5317,9 @@
}
},
"node_modules/prettier": {
- "version": "3.4.2",
- "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.4.2.tgz",
- "integrity": "sha512-e9MewbtFo+Fevyuxn/4rrcDAaq0IYxPGLvObpQjiZBMAzB9IGmzlnG9RZy3FFas+eBMu2vA0CszMeduow5dIuQ==",
+ "version": "3.5.3",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.5.3.tgz",
+ "integrity": "sha512-QQtaxnoDJeAkDvDKWCLiwIXkTgRhwYDEQCghU9Z6q03iyek/rxRh/2lC3HB7P8sWT2xC/y5JDctPLBIGzHKbhw==",
"dev": true,
"license": "MIT",
"bin": {
@@ -5345,6 +5349,12 @@
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
"license": "MIT"
},
+ "node_modules/protocol-buffers-schema": {
+ "version": "3.6.0",
+ "resolved": "https://registry.npmjs.org/protocol-buffers-schema/-/protocol-buffers-schema-3.6.0.tgz",
+ "integrity": "sha512-TdDRD+/QNdrCGCE7v8340QyuXd4kIWIgapsE2+n/SaGiSSbomYl4TjHlvIoCWRpE7wFt02EpB35VVA2ImcBVqw==",
+ "license": "MIT"
+ },
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
@@ -5382,6 +5392,17 @@
],
"license": "MIT"
},
+ "node_modules/quickselect": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/quickselect/-/quickselect-3.0.0.tgz",
+ "integrity": "sha512-XdjUArbK4Bm5fLLvlm5KpTFOiOThgfWWI4axAZDWg4E/0mKdZyI9tNEfds27qCi1ze/vwTR16kvmmGhRra3c2g==",
+ "license": "ISC"
+ },
+ "node_modules/raf-schd": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/raf-schd/-/raf-schd-4.0.3.tgz",
+ "integrity": "sha512-tQkJl2GRWh83ui2DiPTJz9wEiMN20syf+5oKfB03yYP7ioZcJwsIK8FjrtLwH1m7C7e+Tt2yYBlrOpdT+dyeIQ=="
+ },
"node_modules/react": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
@@ -5394,6 +5415,43 @@
"node": ">=0.10.0"
}
},
+ "node_modules/react-dnd": {
+ "version": "16.0.1",
+ "resolved": "https://registry.npmjs.org/react-dnd/-/react-dnd-16.0.1.tgz",
+ "integrity": "sha512-QeoM/i73HHu2XF9aKksIUuamHPDvRglEwdHL4jsp784BgUuWcg6mzfxT0QDdQz8Wj0qyRKx2eMg8iZtWvU4E2Q==",
+ "dependencies": {
+ "@react-dnd/invariant": "^4.0.1",
+ "@react-dnd/shallowequal": "^4.0.1",
+ "dnd-core": "^16.0.1",
+ "fast-deep-equal": "^3.1.3",
+ "hoist-non-react-statics": "^3.3.2"
+ },
+ "peerDependencies": {
+ "@types/hoist-non-react-statics": ">= 3.3.1",
+ "@types/node": ">= 12",
+ "@types/react": ">= 16",
+ "react": ">= 16.14"
+ },
+ "peerDependenciesMeta": {
+ "@types/hoist-non-react-statics": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/react-dnd-html5-backend": {
+ "version": "16.0.1",
+ "resolved": "https://registry.npmjs.org/react-dnd-html5-backend/-/react-dnd-html5-backend-16.0.1.tgz",
+ "integrity": "sha512-Wu3dw5aDJmOGw8WjH1I1/yTH+vlXEL4vmjk5p+MHxP8HuHJS1lAGeIdG/hze1AvNeXWo/JgULV87LyQOr+r5jw==",
+ "dependencies": {
+ "dnd-core": "^16.0.1"
+ }
+ },
"node_modules/react-dom": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
@@ -5407,6 +5465,37 @@
"react": "^18.3.1"
}
},
+ "node_modules/react-i18next": {
+ "version": "15.4.1",
+ "resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-15.4.1.tgz",
+ "integrity": "sha512-ahGab+IaSgZmNPYXdV1n+OYky95TGpFwnKRflX/16dY04DsYYKHtVLjeny7sBSCREEcoMbAgSkFiGLF5g5Oofw==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.25.0",
+ "html-parse-stringify": "^3.0.1"
+ },
+ "peerDependencies": {
+ "i18next": ">= 23.2.3",
+ "react": ">= 16.8.0"
+ },
+ "peerDependenciesMeta": {
+ "react-dom": {
+ "optional": true
+ },
+ "react-native": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/react-icons": {
+ "version": "5.5.0",
+ "resolved": "https://registry.npmjs.org/react-icons/-/react-icons-5.5.0.tgz",
+ "integrity": "sha512-MEFcXdkP3dLo8uumGI5xN3lDFNsRtrjbOEKDLD7yv76v4wpnEq2Lt2qeHaQOr34I/wPN3s3+N08WkQ+CW37Xiw==",
+ "license": "MIT",
+ "peerDependencies": {
+ "react": "*"
+ }
+ },
"node_modules/react-is": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",
@@ -5436,23 +5525,13 @@
}
}
},
- "node_modules/react-refresh": {
- "version": "0.14.2",
- "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.14.2.tgz",
- "integrity": "sha512-jCvmsr+1IUSMUyzOkRcvnVbX3ZYC6g9TDrDbFuFmRDq7PD4yaGbLKNQL6k2jnArV8hjYxh7hVhAZB6s9HDGpZA==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=0.10.0"
- }
- },
"node_modules/react-router": {
- "version": "6.28.2",
- "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.28.2.tgz",
- "integrity": "sha512-BgFY7+wEGVjHCiqaj2XiUBQ1kkzfg6UoKYwEe0wv+FF+HNPCxtS/MVPvLAPH++EsuCMReZl9RYVGqcHLk5ms3A==",
+ "version": "6.30.0",
+ "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.0.tgz",
+ "integrity": "sha512-D3X8FyH9nBcTSHGdEKurK7r8OYE1kKFn3d/CF+CoxbSHkxU7o37+Uh7eAHRXr6k2tSExXYO++07PeXJtA/dEhQ==",
"license": "MIT",
"dependencies": {
- "@remix-run/router": "1.21.1"
+ "@remix-run/router": "1.23.0"
},
"engines": {
"node": ">=14.0.0"
@@ -5462,13 +5541,13 @@
}
},
"node_modules/react-router-dom": {
- "version": "6.28.2",
- "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.28.2.tgz",
- "integrity": "sha512-O81EWqNJWqvlN/a7eTudAdQm0TbI7hw+WIi7OwwMcTn5JMyZ0ibTFNGz+t+Lju0df4LcqowCegcrK22lB1q9Kw==",
+ "version": "6.30.0",
+ "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.0.tgz",
+ "integrity": "sha512-x30B78HV5tFk8ex0ITwzC9TTZMua4jGyA9IUlH1JLQYQTFyxr/ZxwOJq7evg1JX1qGVUcvhsmQSKdPncQrjTgA==",
"license": "MIT",
"dependencies": {
- "@remix-run/router": "1.21.1",
- "react-router": "6.28.2"
+ "@remix-run/router": "1.23.0",
+ "react-router": "6.30.0"
},
"engines": {
"node": ">=14.0.0"
@@ -5479,9 +5558,9 @@
}
},
"node_modules/react-smooth": {
- "version": "4.0.1",
- "resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.1.tgz",
- "integrity": "sha512-OE4hm7XqR0jNOq3Qmk9mFLyd6p2+j6bvbPJ7qlB7+oo0eNcL2l7WQzG6MBnT3EXY6xzkLMUBec3AfewJdA0J8w==",
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.4.tgz",
+ "integrity": "sha512-gnGKTpYwqL0Iii09gHobNolvX4Kiq4PKx6eWBCYYix+8cdw+cGo3do906l1NBPKkSWx1DghC1dlWG9L2uGd61Q==",
"license": "MIT",
"dependencies": {
"fast-equals": "^5.0.1",
@@ -5489,8 +5568,8 @@
"react-transition-group": "^4.4.5"
},
"peerDependencies": {
- "react": "^16.8.0 || ^17.0.0 || ^18.0.0",
- "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0"
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
+ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/react-toastify": {
@@ -5523,16 +5602,16 @@
}
},
"node_modules/recharts": {
- "version": "2.15.0",
- "resolved": "https://registry.npmjs.org/recharts/-/recharts-2.15.0.tgz",
- "integrity": "sha512-cIvMxDfpAmqAmVgc4yb7pgm/O1tmmkl/CjrvXuW+62/+7jj/iF9Ykm+hb/UJt42TREHMyd3gb+pkgoa2MxgDIw==",
+ "version": "2.15.2",
+ "resolved": "https://registry.npmjs.org/recharts/-/recharts-2.15.2.tgz",
+ "integrity": "sha512-xv9lVztv3ingk7V3Jf05wfAZbM9Q2umJzu5t/cfnAK7LUslNrGT7LPBr74G+ok8kSCeFMaePmWMg0rcYOnczTw==",
"license": "MIT",
"dependencies": {
"clsx": "^2.0.0",
"eventemitter3": "^4.0.1",
"lodash": "^4.17.21",
"react-is": "^18.3.1",
- "react-smooth": "^4.0.0",
+ "react-smooth": "^4.0.4",
"recharts-scale": "^0.4.4",
"tiny-invariant": "^1.3.1",
"victory-vendor": "^36.6.8"
@@ -5658,6 +5737,15 @@
"node": ">=4"
}
},
+ "node_modules/resolve-protobuf-schema": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/resolve-protobuf-schema/-/resolve-protobuf-schema-2.1.0.tgz",
+ "integrity": "sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ==",
+ "license": "MIT",
+ "dependencies": {
+ "protocol-buffers-schema": "^3.3.1"
+ }
+ },
"node_modules/reusify": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz",
@@ -5753,6 +5841,12 @@
"queue-microtask": "^1.2.2"
}
},
+ "node_modules/rw": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz",
+ "integrity": "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==",
+ "license": "BSD-3-Clause"
+ },
"node_modules/safe-array-concat": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.3.tgz",
@@ -5970,6 +6064,29 @@
"node": ">=0.10.0"
}
},
+ "node_modules/source-map-support": {
+ "version": "0.5.21",
+ "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",
+ "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "buffer-from": "^1.0.0",
+ "source-map": "^0.6.0"
+ }
+ },
+ "node_modules/source-map-support/node_modules/source-map": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
+ "license": "BSD-3-Clause",
+ "optional": true,
+ "peer": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/string.prototype.matchall": {
"version": "4.0.12",
"resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.12.tgz",
@@ -6100,6 +6217,15 @@
"integrity": "sha512-Orov6g6BB1sDfYgzWfTHDOxamtX1bE/zo104Dh9e6fqJ3PooipYyfJ0pUmrZO2wAvO8YbEyeFrkV91XTsGMSrw==",
"license": "MIT"
},
+ "node_modules/supercluster": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/supercluster/-/supercluster-8.0.1.tgz",
+ "integrity": "sha512-IiOea5kJ9iqzD2t7QJq/cREyLHTtSmUT6gQsweojg9WH2sYJqZK9SswTu6jrscO6D1G5v5vYZ9ru/eq85lXeZQ==",
+ "license": "ISC",
+ "dependencies": {
+ "kdbush": "^4.0.2"
+ }
+ },
"node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
@@ -6131,6 +6257,42 @@
"integrity": "sha512-e4hG1hRwoOdRb37cIMSgzNsxyzKfayW6VOflrwvR+/bzrkyxY/31WkbgnQpgtrNp1SdpJvpUAGTa/ZoiPNDuRQ==",
"license": "MIT"
},
+ "node_modules/terser": {
+ "version": "5.39.0",
+ "resolved": "https://registry.npmjs.org/terser/-/terser-5.39.0.tgz",
+ "integrity": "sha512-LBAhFyLho16harJoWMg/nZsQYgTrg5jXOn2nCYjRUcZZEdE3qa2zb8QEDRUGVZBW4rlazf2fxkg8tztybTaqWw==",
+ "license": "BSD-2-Clause",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "@jridgewell/source-map": "^0.3.3",
+ "acorn": "^8.8.2",
+ "commander": "^2.20.0",
+ "source-map-support": "~0.5.20"
+ },
+ "bin": {
+ "terser": "bin/terser"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/terser/node_modules/commander": {
+ "version": "2.20.3",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
+ "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",
+ "license": "MIT",
+ "optional": true,
+ "peer": true
+ },
+ "node_modules/text-segmentation": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/text-segmentation/-/text-segmentation-1.0.3.tgz",
+ "integrity": "sha512-iOiPUo/BGnZ6+54OsWxZidGCsdU8YbE4PSpdPinp7DeMtUJNJBoJ/ouUSTJjHkh1KntHaltHl/gDs2FC4i5+Nw==",
+ "dependencies": {
+ "utrie": "^1.0.2"
+ }
+ },
"node_modules/text-table": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz",
@@ -6144,6 +6306,12 @@
"integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",
"license": "MIT"
},
+ "node_modules/tinyqueue": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/tinyqueue/-/tinyqueue-3.0.0.tgz",
+ "integrity": "sha512-gRa9gwYU3ECmQYv3lslts5hxuIa90veaEcxDYuu3QGOIAEM2mOZkVHp48ANJuu1CURtRdHKUBY5Lm1tHV+sD4g==",
+ "license": "ISC"
+ },
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
@@ -6254,6 +6422,21 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/typescript": {
+ "version": "5.7.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz",
+ "integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "peer": true,
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
"node_modules/unbox-primitive": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz",
@@ -6273,6 +6456,14 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/undici-types": {
+ "version": "6.20.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz",
+ "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==",
+ "license": "MIT",
+ "optional": true,
+ "peer": true
+ },
"node_modules/update-browserslist-db": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.1.tgz",
@@ -6322,6 +6513,14 @@
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
+ "node_modules/utrie": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/utrie/-/utrie-1.0.2.tgz",
+ "integrity": "sha512-1MLa5ouZiOmQzUbjbu9VmjLzn1QLXBhwpUa7kdLUQK+KQ5KA9I1vk5U4YHe/X2Ch7PYnJfWuWT+VbuxbGwljhw==",
+ "dependencies": {
+ "base64-arraybuffer": "^1.0.2"
+ }
+ },
"node_modules/victory-vendor": {
"version": "36.9.2",
"resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-36.9.2.tgz",
@@ -6345,9 +6544,9 @@
}
},
"node_modules/vite": {
- "version": "5.4.14",
- "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.14.tgz",
- "integrity": "sha512-EK5cY7Q1D8JNhSaPKVK4pwBFvaTmZxEnoKXLG/U9gmdDcihQGNzFlgIvaxezFR4glP1LsuiedwMBqCXH3wZccA==",
+ "version": "5.4.18",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.18.tgz",
+ "integrity": "sha512-1oDcnEp3lVyHCuQ2YFelM4Alm2o91xNoMncRm1U7S+JdYfYOvbiGZ3/CxGttrOu2M/KcGz7cRC2DoNUA6urmMA==",
"license": "MIT",
"dependencies": {
"esbuild": "^0.21.3",
@@ -6417,6 +6616,25 @@
"vite": ">=2.6.0"
}
},
+ "node_modules/void-elements": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/void-elements/-/void-elements-3.1.0.tgz",
+ "integrity": "sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w==",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/vt-pbf": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/vt-pbf/-/vt-pbf-3.1.3.tgz",
+ "integrity": "sha512-2LzDFzt0mZKZ9IpVF2r69G9bXaP2Q2sArJCmcCgvfTdCCZzSyz4aCLoQyUilu37Ll56tCblIZrXFIjNUpGIlmA==",
+ "license": "MIT",
+ "dependencies": {
+ "@mapbox/point-geometry": "0.1.0",
+ "@mapbox/vector-tile": "^1.3.1",
+ "pbf": "^3.2.1"
+ }
+ },
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
diff --git a/Client/package.json b/client/package.json
similarity index 54%
rename from Client/package.json
rename to client/package.json
index 247e1fe72..ba745503a 100644
--- a/Client/package.json
+++ b/client/package.json
@@ -14,27 +14,46 @@
"@emotion/react": "^11.13.3",
"@emotion/styled": "^11.13.0",
"@fontsource/roboto": "^5.0.13",
- "@mui/icons-material": "6.4.1",
- "@mui/lab": "6.0.0-beta.24",
- "@mui/material": "6.4.1",
+ "@hello-pangea/dnd": "^18.0.0",
"@mui/x-charts": "^7.5.1",
- "@mui/x-data-grid": "7.24.0",
- "@mui/x-date-pickers": "7.24.0",
- "@reduxjs/toolkit": "2.5.0",
+ "@mui/x-data-grid": "7.29.0",
+ "@mui/x-date-pickers": "7.29.0",
+ "@mui/icons-material": "6.4.11",
+ "@mui/lab": "6.0.0-dev.240424162023-9968b4889d",
+ "@mui/material": "6.4.11",
+ "@reduxjs/toolkit": "2.7.0",
"axios": "^1.7.4",
"dayjs": "1.11.13",
- "joi": "17.13.3",
+ "flag-icons": "7.3.2",
"jwt-decode": "^4.0.0",
- "react": "^18.2.0",
+ "html2canvas": "^1.4.1",
+ "i18next": "^24.2.2",
+ "immutability-helper": "^3.1.1",
+ "joi": "17.13.3",
+ "maplibre-gl": "5.3.1",
+ "mui-color-input": "^6.0.0",
+ "react": "18.3.1",
+ "react-dnd": "^16.0.1",
+ "react-dnd-html5-backend": "^16.0.1",
"react-dom": "^18.2.0",
+ "react-i18next": "^15.4.0",
+ "react-icons": "5.5.0",
"react-redux": "9.2.0",
"react-router": "^6.23.0",
"react-router-dom": "^6.23.1",
"react-toastify": "^10.0.5",
- "recharts": "2.15.0",
+ "recharts": "2.15.2",
"redux-persist": "6.0.0",
"vite-plugin-svgr": "^4.2.0"
},
+ "unusedDepencies": {
+ "@solana/wallet-adapter-base": "0.9.25",
+ "@solana/wallet-adapter-material-ui": "0.16.35",
+ "@solana/wallet-adapter-react": "0.15.37",
+ "@solana/wallet-adapter-react-ui": "0.9.37",
+ "@solana/wallet-adapter-wallets": "0.19.34",
+ "@solana/web3.js": "1.98.0"
+ },
"devDependencies": {
"@types/react": "^18.2.66",
"@types/react-dom": "^18.2.22",
diff --git a/client/public/bulk_import_monitors_sample.csv b/client/public/bulk_import_monitors_sample.csv
new file mode 100644
index 000000000..2a01ea483
--- /dev/null
+++ b/client/public/bulk_import_monitors_sample.csv
@@ -0,0 +1,6 @@
+type,name,url,interval,port,expectedValue,jsonPath,matchMethod
+http,HTTP Monitor,https://www.google.com,60000,,,,
+http,API Monitor,http://reqres.in/api/users/2,120000,,Janet,data.first_name,equal
+ping,Ping monitor,127.0.0.1,60000,,,,
+docker,Docker monitor,bbdd20b4e3757d63e070bc16e04d3f770c4a8f6e62e813de380f23b141e2ca01,60000,,,,
+port,Port monitor,127.0.0.1,60000,5000,,,
\ No newline at end of file
diff --git a/client/public/bulk_import_monitors_template.csv b/client/public/bulk_import_monitors_template.csv
new file mode 100644
index 000000000..2902010fc
--- /dev/null
+++ b/client/public/bulk_import_monitors_template.csv
@@ -0,0 +1 @@
+type,name,url,interval,port,expectedValue,jsonPath,matchMethod
\ No newline at end of file
diff --git a/Client/public/checkmate_favicon.svg b/client/public/checkmate_favicon.svg
similarity index 100%
rename from Client/public/checkmate_favicon.svg
rename to client/public/checkmate_favicon.svg
diff --git a/renovate.json b/client/renovate.json
similarity index 100%
rename from renovate.json
rename to client/renovate.json
diff --git a/Client/src/App.jsx b/client/src/App.jsx
similarity index 55%
rename from Client/src/App.jsx
rename to client/src/App.jsx
index 05822a5f5..7fb63ee61 100644
--- a/Client/src/App.jsx
+++ b/client/src/App.jsx
@@ -1,27 +1,18 @@
import { useEffect } from "react";
import { useSelector } from "react-redux";
-import { useDispatch } from "react-redux";
import "react-toastify/dist/ReactToastify.css";
import { ToastContainer } from "react-toastify";
import { ThemeProvider } from "@emotion/react";
import lightTheme from "./Utils/Theme/lightTheme";
import darkTheme from "./Utils/Theme/darkTheme";
import { CssBaseline, GlobalStyles } from "@mui/material";
-import { getAppSettings } from "./Features/Settings/settingsSlice";
import { logger } from "./Utils/Logger"; // Import the logger
import { networkService } from "./main";
import { Routes } from "./Routes";
+import WalletProvider from "./Components/WalletProvider";
function App() {
const mode = useSelector((state) => state.ui.mode);
- const { authToken } = useSelector((state) => state.auth);
- const dispatch = useDispatch();
-
- useEffect(() => {
- if (authToken) {
- dispatch(getAppSettings({ authToken }));
- }
- }, [dispatch, authToken]);
// Cleanup
useEffect(() => {
@@ -34,19 +25,21 @@ function App() {
return (
/* Extract Themeprovider, baseline and global styles to Styles */
-
- {
- return {
- body: {
- backgroundImage: `radial-gradient(circle, ${palette.gradient.color1}, ${palette.gradient.color2}, ${palette.gradient.color3}, ${palette.gradient.color4}, ${palette.gradient.color5})`,
- color: palette.primary.contrastText,
- },
- };
- }}
- />
-
-
+
+
+ {
+ return {
+ body: {
+ backgroundImage: `radial-gradient(circle, ${palette.gradient.color1}, ${palette.gradient.color2}, ${palette.gradient.color3}, ${palette.gradient.color4}, ${palette.gradient.color5})`,
+ color: palette.primary.contrastText,
+ },
+ };
+ }}
+ />
+
+
+
);
}
diff --git a/Client/src/Pages/Uptime/Home/actionsMenu.jsx b/client/src/Components/ActionsMenu/index.jsx
similarity index 88%
rename from Client/src/Pages/Uptime/Home/actionsMenu.jsx
rename to client/src/Components/ActionsMenu/index.jsx
index 493c5f25e..4d5ab7c01 100644
--- a/Client/src/Pages/Uptime/Home/actionsMenu.jsx
+++ b/client/src/Components/ActionsMenu/index.jsx
@@ -2,40 +2,36 @@ import { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { useTheme } from "@emotion/react";
import { useNavigate } from "react-router-dom";
-import { createToast } from "../../../Utils/toastUtils";
-import { logger } from "../../../Utils/Logger";
+import { createToast } from "../../Utils/toastUtils";
+import { logger } from "../../Utils/Logger";
import { IconButton, Menu, MenuItem } from "@mui/material";
import {
deleteUptimeMonitor,
pauseUptimeMonitor,
-} from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
-import Settings from "../../../assets/icons/settings-bold.svg?react";
+} from "../../Features/UptimeMonitors/uptimeMonitorsSlice";
+import Settings from "../../assets/icons/settings-bold.svg?react";
import PropTypes from "prop-types";
-import Dialog from "../../../Components/Dialog";
+import Dialog from "../../Components/Dialog";
const ActionsMenu = ({
monitor,
isAdmin,
updateRowCallback,
pauseCallback,
- setIsLoading,
+ setIsLoading = () => {},
}) => {
const [anchorEl, setAnchorEl] = useState(null);
const [actions, setActions] = useState({});
const [isOpen, setIsOpen] = useState(false);
const dispatch = useDispatch();
const theme = useTheme();
- const authState = useSelector((state) => state.auth);
- const authToken = authState.authToken;
const { isLoading } = useSelector((state) => state.uptimeMonitors);
const handleRemove = async (event) => {
event.preventDefault();
event.stopPropagation();
let monitor = { _id: actions.id };
- const action = await dispatch(
- deleteUptimeMonitor({ authToken: authState.authToken, monitor })
- );
+ const action = await dispatch(deleteUptimeMonitor({ monitor }));
if (action.meta.requestStatus === "fulfilled") {
setIsOpen(false); // close modal
updateRowCallback();
@@ -48,11 +44,9 @@ const ActionsMenu = ({
const handlePause = async () => {
try {
setIsLoading(true);
- const action = await dispatch(
- pauseUptimeMonitor({ authToken, monitorId: monitor._id })
- );
+ const action = await dispatch(pauseUptimeMonitor({ monitorId: monitor._id }));
if (pauseUptimeMonitor.fulfilled.match(action)) {
- const state = action?.payload?.data.isActive === false ? "paused" : "resumed";
+ const state = action?.payload?.data.isActive === false ? "resumed" : "paused";
createToast({ body: `Monitor ${state} successfully.` });
pauseCallback();
} else {
diff --git a/Client/src/Components/Alert/index.css b/client/src/Components/Alert/index.css
similarity index 100%
rename from Client/src/Components/Alert/index.css
rename to client/src/Components/Alert/index.css
diff --git a/Client/src/Components/Alert/index.jsx b/client/src/Components/Alert/index.jsx
similarity index 95%
rename from Client/src/Components/Alert/index.jsx
rename to client/src/Components/Alert/index.jsx
index a52761ca4..921d4fd6e 100644
--- a/Client/src/Components/Alert/index.jsx
+++ b/client/src/Components/Alert/index.jsx
@@ -36,8 +36,8 @@ const Alert = ({ variant, title, body, isToast, hasIcon = true, onClick }) => {
*/
const text = theme.palette.secondary.contrastText;
- const bg = theme.palette.secondary.main;
- const border = theme.palette.secondary.contrastText;
+ const border = theme.palette.alert.contrastText;
+ const bg = theme.palette.alert.main;
const icon = icons[variant];
return (
@@ -111,7 +111,7 @@ const Alert = ({ variant, title, body, isToast, hasIcon = true, onClick }) => {
Alert.propTypes = {
variant: PropTypes.oneOf(["info", "error", "warning"]).isRequired,
title: PropTypes.string,
- body: PropTypes.string,
+ body: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
isToast: PropTypes.bool,
hasIcon: PropTypes.bool,
onClick: function (props, propName, componentName) {
diff --git a/Client/src/Components/Animated/PulseDot.jsx b/client/src/Components/Animated/PulseDot.jsx
similarity index 100%
rename from Client/src/Components/Animated/PulseDot.jsx
rename to client/src/Components/Animated/PulseDot.jsx
diff --git a/Client/src/Components/Avatar/index.css b/client/src/Components/Avatar/index.css
similarity index 100%
rename from Client/src/Components/Avatar/index.css
rename to client/src/Components/Avatar/index.css
diff --git a/Client/src/Components/Avatar/index.jsx b/client/src/Components/Avatar/index.jsx
similarity index 100%
rename from Client/src/Components/Avatar/index.jsx
rename to client/src/Components/Avatar/index.jsx
diff --git a/Client/src/Components/Breadcrumbs/index.css b/client/src/Components/Breadcrumbs/index.css
similarity index 100%
rename from Client/src/Components/Breadcrumbs/index.css
rename to client/src/Components/Breadcrumbs/index.css
diff --git a/Client/src/Components/Breadcrumbs/index.jsx b/client/src/Components/Breadcrumbs/index.jsx
similarity index 100%
rename from Client/src/Components/Breadcrumbs/index.jsx
rename to client/src/Components/Breadcrumbs/index.jsx
diff --git a/client/src/Components/Buttons/RoundGradientButton.jsx b/client/src/Components/Buttons/RoundGradientButton.jsx
new file mode 100644
index 000000000..f9e14735c
--- /dev/null
+++ b/client/src/Components/Buttons/RoundGradientButton.jsx
@@ -0,0 +1,30 @@
+import React from "react";
+import Button from "@mui/material/Button";
+import { styled } from "@mui/material/styles";
+
+const RoundGradientButton = styled(Button)(({ theme }) => ({
+ position: "relative",
+ border: "5px solid transparent",
+ backgroundClip: "padding-box",
+ borderRadius: 30,
+ fontSize: "1.2rem",
+ color: theme.palette.primary.contrastText,
+ backgroundColor: theme.palette.background.main,
+
+ "&:after": {
+ position: "absolute",
+ top: -3,
+ left: -3,
+ right: -3,
+ bottom: -3,
+ background:
+ theme.palette.mode === "dark"
+ ? "linear-gradient(90deg, #842bd2, #ff5451, #8c52ff)"
+ : "linear-gradient(90deg, #842bd2, #ff5451, #8c52ff)",
+ content: '""',
+ zIndex: -1,
+ borderRadius: 30,
+ },
+}));
+
+export default RoundGradientButton;
diff --git a/Client/src/Components/Charts/AreaChart/index.jsx b/client/src/Components/Charts/AreaChart/index.jsx
similarity index 100%
rename from Client/src/Components/Charts/AreaChart/index.jsx
rename to client/src/Components/Charts/AreaChart/index.jsx
diff --git a/Client/src/Components/Charts/BarChart/index.css b/client/src/Components/Charts/BarChart/index.css
similarity index 100%
rename from Client/src/Components/Charts/BarChart/index.css
rename to client/src/Components/Charts/BarChart/index.css
diff --git a/Client/src/Components/Charts/BarChart/index.jsx b/client/src/Components/Charts/BarChart/index.jsx
similarity index 99%
rename from Client/src/Components/Charts/BarChart/index.jsx
rename to client/src/Components/Charts/BarChart/index.jsx
index 101afe648..375773b94 100644
--- a/Client/src/Components/Charts/BarChart/index.jsx
+++ b/client/src/Components/Charts/BarChart/index.jsx
@@ -58,7 +58,7 @@ const BarChart = ({ checks = [] }) => {
<>
{formatDateWithTz(
- check.createdAt,
+ check.updatedAt,
"ddd, MMMM D, YYYY, HH:mm A",
uiTimezone
)}
diff --git a/client/src/Components/Charts/ChartBox/EmptyView.jsx b/client/src/Components/Charts/ChartBox/EmptyView.jsx
new file mode 100644
index 000000000..94b1af7b0
--- /dev/null
+++ b/client/src/Components/Charts/ChartBox/EmptyView.jsx
@@ -0,0 +1,108 @@
+// Components
+import { Typography, Stack } from "@mui/material";
+import PropTypes from "prop-types";
+import { useTheme } from "@emotion/react";
+import IconBox from "../../IconBox";
+
+/**
+ * `EmptyView` is a functional React component that displays an empty state view with an optional icon, header, and message.
+ *
+ * @component
+ * @param {Object} props - The properties that define the `EmptyView` component.
+ * @param {React.ReactNode} [props.icon] - An optional icon to display at the top of the empty view.
+ * @param {string} [props.header] - An optional header text displayed next to the icon.
+ * @param {string} [props.message="No Data"] - The message to be displayed in the empty view.
+ * @param {'h1' | 'h2' | 'h3'} [props.headingLevel="h2"] - The heading level for the message text.
+ * @param {string} [props.justifyContent="flex-start"] - The CSS `justify-content` value to align elements vertically.
+ * @param {string} [props.height="100%"] - The height of the empty view container.
+ *
+ * @example
+ * // Example usage of EmptyView component:
+ * }
+ * header="Average Response Time"
+ * message="No Response Time Available"
+ * headingLevel="h2"
+ * justifyContent="center"
+ * height="50%"
+ * />
+ *
+ * @returns {React.Element} The `EmptyView` component with customizable icon, header, and message.
+ */
+
+const EmptyView = ({
+ icon,
+ header,
+ message = "No Data",
+ headingLevel = "h2",
+ justifyContent = "flex-start",
+ height = "100%"
+}) => {
+ const theme = useTheme();
+ return (
+
+
+
+ {icon && {icon} }
+ {header && {header} }
+
+
+
+ {message}
+
+
+
+
+ );
+};
+
+EmptyView.propTypes = {
+ message: PropTypes.string,
+ icon: PropTypes.node,
+ header: PropTypes.string,
+ headingLevel: PropTypes.oneOf(['h1', 'h2', 'h3']),
+ justifyContent: PropTypes.string,
+ height: PropTypes.string
+};
+
+export default EmptyView;
diff --git a/client/src/Components/Charts/ChartBox/index.jsx b/client/src/Components/Charts/ChartBox/index.jsx
new file mode 100644
index 000000000..4b72fe16a
--- /dev/null
+++ b/client/src/Components/Charts/ChartBox/index.jsx
@@ -0,0 +1,99 @@
+import { Stack, Typography } from "@mui/material";
+import { useTheme } from "@emotion/react";
+import IconBox from "../../IconBox";
+import EmptyView from "./EmptyView";
+import PropTypes from "prop-types";
+
+const ChartBox = ({
+ children,
+ icon,
+ header,
+ height = "300px",
+ justifyContent = "space-between",
+ Legend,
+ borderRadiusRight = 4,
+ sx,
+ noDataMessage,
+ isEmpty = false,
+}) => {
+ const theme = useTheme();
+ if (isEmpty) {
+ return ;
+ }
+ return (
+
+ span": {
+ color: theme.palette.primary.contrastText,
+ fontSize: 20,
+ "& span": {
+ opacity: 0.8,
+ marginLeft: 2,
+ fontSize: 15,
+ },
+ },
+
+ "& tspan, & text": {
+ fill: theme.palette.primary.contrastTextTertiary,
+ },
+ "& path": {
+ transition: "fill 300ms ease, stroke-width 400ms ease",
+ },
+ }}
+ >
+
+ {icon && {icon} }
+ {header && {header} }
+
+ {children}
+
+ {Legend && Legend}
+
+ );
+};
+
+export default ChartBox;
+
+ChartBox.propTypes = {
+ children: PropTypes.node,
+ icon: PropTypes.node,
+ header: PropTypes.string,
+ height: PropTypes.string,
+ noDataMessage: PropTypes.string,
+ isEmpty: PropTypes.bool
+};
diff --git a/Client/src/Components/Charts/CustomGauge/index.css b/client/src/Components/Charts/CustomGauge/index.css
similarity index 100%
rename from Client/src/Components/Charts/CustomGauge/index.css
rename to client/src/Components/Charts/CustomGauge/index.css
diff --git a/Client/src/Components/Charts/CustomGauge/index.jsx b/client/src/Components/Charts/CustomGauge/index.jsx
similarity index 93%
rename from Client/src/Components/Charts/CustomGauge/index.jsx
rename to client/src/Components/Charts/CustomGauge/index.jsx
index d29663004..3c7e13610 100644
--- a/Client/src/Components/Charts/CustomGauge/index.jsx
+++ b/client/src/Components/Charts/CustomGauge/index.jsx
@@ -62,6 +62,7 @@ const CustomGauge = ({ progress = 0, radius = 70, strokeWidth = 15, threshold =
className="radial-chart"
width={radius}
height={radius}
+ sx={{ backgroundColor: theme.palette.primary.main, borderRadius: "50%" }}
>
{`${progressWithinRange.toFixed(1)}%`}
diff --git a/client/src/Components/Charts/DePINStatusPageBarChart/index.jsx b/client/src/Components/Charts/DePINStatusPageBarChart/index.jsx
new file mode 100644
index 000000000..65c6278f1
--- /dev/null
+++ b/client/src/Components/Charts/DePINStatusPageBarChart/index.jsx
@@ -0,0 +1,181 @@
+// Components
+import { Stack, Box, Tooltip, Typography } from "@mui/material";
+
+// Utils
+import { useTheme } from "@emotion/react";
+import { useState, useEffect } from "react";
+import PropTypes from "prop-types";
+import { formatDateWithTz } from "../../../Utils/timeUtils";
+import { useSelector } from "react-redux";
+
+const PlaceholderCheck = ({ daysToShow }) => {
+ const theme = useTheme();
+
+ return (
+
+ );
+};
+
+PlaceholderCheck.propTypes = {
+ daysToShow: PropTypes.number,
+};
+
+const Check = ({ check, daysToShow }) => {
+ const [animate, setAnimate] = useState(false);
+
+ const theme = useTheme();
+ useEffect(() => {
+ setAnimate(true);
+ }, []);
+ const uiTimezone = useSelector((state) => state.ui.timezone);
+
+ return (
+
+
+ {formatDateWithTz(check._id, "ddd, MMMM D, YYYY", uiTimezone)}
+
+
+
+
+ Uptime percentage
+
+
+ {check.upPercentage.toFixed(2)}
+
+ {" "}
+ %
+
+
+
+
+ >
+ }
+ placement="top"
+ key={`check-${check?._id}`}
+ slotProps={{
+ popper: {
+ className: "bar-tooltip",
+ modifiers: [
+ {
+ name: "offset",
+ options: {
+ offset: [0, -10],
+ },
+ },
+ ],
+ sx: {
+ "& .MuiTooltip-tooltip": {
+ backgroundColor: theme.palette.secondary.main,
+ border: 1,
+ borderColor: theme.palette.primary.lowContrast,
+ borderRadius: theme.shape.borderRadius,
+ boxShadow: theme.shape.boxShadow,
+ px: theme.spacing(4),
+ py: theme.spacing(3),
+ },
+ "& .MuiTooltip-tooltip p": {
+ /* TODO Font size should point to theme */
+ fontSize: 12,
+ color: theme.palette.secondary.contrastText,
+ fontWeight: 500,
+ },
+ "& .MuiTooltip-tooltip span": {
+ /* TODO Font size should point to theme */
+ fontSize: 11,
+ color: theme.palette.secondary.contrastText,
+ fontWeight: 600,
+ },
+ },
+ },
+ }}
+ >
+
+
+
+
+ );
+};
+
+Check.propTypes = {
+ check: PropTypes.object,
+ daysToShow: PropTypes.number,
+};
+
+const DePINStatusPageBarChart = ({ checks = [], daysToShow = 30 }) => {
+ if (checks.length !== daysToShow) {
+ const placeholders = Array(daysToShow - checks.length).fill("placeholder");
+ checks = [...checks, ...placeholders];
+ }
+ return (
+
+ {checks.map((check) => {
+ if (check === "placeholder") {
+ return (
+
+ );
+ }
+ return (
+
+ );
+ })}
+
+ );
+};
+
+DePINStatusPageBarChart.propTypes = {
+ checks: PropTypes.array,
+ daysToShow: PropTypes.number,
+};
+
+export default DePINStatusPageBarChart;
diff --git a/client/src/Components/Charts/LegendBox/index.jsx b/client/src/Components/Charts/LegendBox/index.jsx
new file mode 100644
index 000000000..ac14669e3
--- /dev/null
+++ b/client/src/Components/Charts/LegendBox/index.jsx
@@ -0,0 +1,42 @@
+import { Stack, Typography } from "@mui/material";
+import { useTheme } from "@emotion/react";
+import IconBox from "../../IconBox";
+import PropTypes from "prop-types";
+
+const LegendBox = ({ children, icon, header, sx }) => {
+ const theme = useTheme();
+ return (
+
+
+ {icon}
+ {header}
+
+ {children}
+
+ );
+};
+
+LegendBox.propTypes = {
+ children: PropTypes.node,
+ icon: PropTypes.node,
+ header: PropTypes.string,
+};
+
+export default LegendBox;
diff --git a/Client/src/Components/Charts/MonitorDetailsAreaChart/index.css b/client/src/Components/Charts/MonitorDetailsAreaChart/index.css
similarity index 100%
rename from Client/src/Components/Charts/MonitorDetailsAreaChart/index.css
rename to client/src/Components/Charts/MonitorDetailsAreaChart/index.css
diff --git a/Client/src/Components/Charts/MonitorDetailsAreaChart/index.jsx b/client/src/Components/Charts/MonitorDetailsAreaChart/index.jsx
similarity index 97%
rename from Client/src/Components/Charts/MonitorDetailsAreaChart/index.jsx
rename to client/src/Components/Charts/MonitorDetailsAreaChart/index.jsx
index 0b959a392..a1ead3cf9 100644
--- a/Client/src/Components/Charts/MonitorDetailsAreaChart/index.jsx
+++ b/client/src/Components/Charts/MonitorDetailsAreaChart/index.jsx
@@ -73,9 +73,12 @@ const CustomToolTip = ({ active, payload, label, dateRange }) => {
component="span"
sx={{ opacity: 0.8 }}
>
- Response Time
- {" "}
-
+ Response time:
+
+
{Math.floor(responseTime)}
{
+ const theme = useTheme();
+
+ return (
+
+ {children}
+
+ );
+};
+
+Bar.propTypes = {
+ width: PropTypes.string.isRequired,
+ height: PropTypes.string.isRequired,
+ backgroundColor: PropTypes.string.isRequired,
+ borderRadius: PropTypes.string,
+ children: PropTypes.node,
+};
+
+/* TODO add prop validation and jsdocs */
+const StatusPageBarChart = ({ checks = [] }) => {
+ const theme = useTheme();
+ const [animate, setAnimate] = useState(false);
+ const uiTimezone = useSelector((state) => state.ui.timezone);
+
+ const barWidth = {
+ xs: "calc(60% / 25)",
+ xl: "calc(40% / 25)",
+ };
+
+ useEffect(() => {
+ setAnimate(true);
+ }, []);
+
+ // set responseTime to average if there's only one check
+ if (checks.length === 1) {
+ checks[0] = { ...checks[0], responseTime: 50 };
+ }
+
+ if (checks.length !== 25) {
+ const placeholders = Array(25 - checks.length).fill("placeholder");
+ checks = [...checks, ...placeholders];
+ }
+
+ return (
+ event.stopPropagation()}
+ sx={{
+ cursor: "default",
+ }}
+ >
+ {checks.map((check, index) =>
+ check === "placeholder" ? (
+ /* TODO what is the purpose of this box? */
+ // CAIO_REVIEW the purpose of this box is to make sure there are always at least 25 bars
+ // even if there are less than 25 checks
+
+ ) : (
+
+
+ {formatDateWithTz(
+ check.createdAt,
+ "ddd, MMMM D, YYYY, HH:mm A",
+ uiTimezone
+ )}
+
+
+
+
+
+ Response Time
+
+
+ {check.originalResponseTime}
+
+ {" "}
+ ms
+
+
+
+
+ >
+ }
+ placement="top"
+ key={`check-${check?._id}`}
+ slotProps={{
+ popper: {
+ className: "bar-tooltip",
+ modifiers: [
+ {
+ name: "offset",
+ options: {
+ offset: [0, -10],
+ },
+ },
+ ],
+ sx: {
+ "& .MuiTooltip-tooltip": {
+ backgroundColor: theme.palette.secondary.main,
+ border: 1,
+ borderColor: theme.palette.primary.lowContrast,
+ borderRadius: theme.shape.borderRadius,
+ boxShadow: theme.shape.boxShadow,
+ px: theme.spacing(4),
+ py: theme.spacing(3),
+ },
+ "& .MuiTooltip-tooltip p": {
+ /* TODO Font size should point to theme */
+ fontSize: 12,
+ color: theme.palette.secondary.contrastText,
+ fontWeight: 500,
+ },
+ "& .MuiTooltip-tooltip span": {
+ /* TODO Font size should point to theme */
+ fontSize: 11,
+ color: theme.palette.secondary.contrastText,
+ fontWeight: 600,
+ },
+ },
+ },
+ }}
+ >
+
+
+
+
+ )
+ )}
+
+ );
+};
+
+export default StatusPageBarChart;
diff --git a/Client/src/Components/Charts/Utils/chartUtilFunctions.js b/client/src/Components/Charts/Utils/chartUtilFunctions.js
similarity index 96%
rename from Client/src/Components/Charts/Utils/chartUtilFunctions.js
rename to client/src/Components/Charts/Utils/chartUtilFunctions.js
index 70f5ac9c3..d8ec6cdb6 100644
--- a/Client/src/Components/Charts/Utils/chartUtilFunctions.js
+++ b/client/src/Components/Charts/Utils/chartUtilFunctions.js
@@ -13,6 +13,7 @@ export const tooltipDateFormatLookup = (dateRange) => {
export const tickDateFormatLookup = (dateRange) => {
const tickFormatLookup = {
+ recent: "h:mm A",
day: "h:mm A",
week: "MM/D, h:mm A",
month: "ddd. M/D",
diff --git a/Client/src/Components/Charts/Utils/chartUtils.jsx b/client/src/Components/Charts/Utils/chartUtils.jsx
similarity index 100%
rename from Client/src/Components/Charts/Utils/chartUtils.jsx
rename to client/src/Components/Charts/Utils/chartUtils.jsx
diff --git a/Client/src/Components/Charts/Utils/gradientUtils.jsx b/client/src/Components/Charts/Utils/gradientUtils.jsx
similarity index 100%
rename from Client/src/Components/Charts/Utils/gradientUtils.jsx
rename to client/src/Components/Charts/Utils/gradientUtils.jsx
diff --git a/Client/src/Components/Check/Check.jsx b/client/src/Components/Check/Check.jsx
similarity index 100%
rename from Client/src/Components/Check/Check.jsx
rename to client/src/Components/Check/Check.jsx
diff --git a/Client/src/Components/Check/check.css b/client/src/Components/Check/check.css
similarity index 100%
rename from Client/src/Components/Check/check.css
rename to client/src/Components/Check/check.css
diff --git a/client/src/Components/CircularCount/index.jsx b/client/src/Components/CircularCount/index.jsx
new file mode 100644
index 000000000..8350a8c44
--- /dev/null
+++ b/client/src/Components/CircularCount/index.jsx
@@ -0,0 +1,29 @@
+import { Box } from "@mui/material";
+import PropTypes from "prop-types";
+import { useTheme } from "@emotion/react";
+const CircularCount = ({ count }) => {
+ const theme = useTheme();
+ return (
+
+ {count}
+
+ );
+};
+
+CircularCount.propTypes = {
+ count: PropTypes.number,
+};
+
+export default CircularCount;
diff --git a/client/src/Components/Common/AppBar.jsx b/client/src/Components/Common/AppBar.jsx
new file mode 100644
index 000000000..df0660cf5
--- /dev/null
+++ b/client/src/Components/Common/AppBar.jsx
@@ -0,0 +1,216 @@
+import { useState } from "react";
+import { styled, alpha } from "@mui/material/styles";
+import Box from "@mui/material/Box";
+import AppBar from "@mui/material/AppBar";
+import Toolbar from "@mui/material/Toolbar";
+import Button from "@mui/material/Button";
+import IconButton from "@mui/material/IconButton";
+import Container from "@mui/material/Container";
+import MenuItem from "@mui/material/MenuItem";
+import Drawer from "@mui/material/Drawer";
+import MenuIcon from "@mui/icons-material/Menu";
+import CloseRoundedIcon from "@mui/icons-material/CloseRounded";
+import ThemeSwitch from "../ThemeSwitch";
+import { useTheme } from "@mui/material/styles";
+import { useSelector } from "react-redux";
+import { useLocation, useNavigate } from "react-router-dom";
+
+const StyledToolbar = styled(Toolbar)(({ theme, mode }) => ({
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ flexShrink: 0,
+ borderRadius: `calc(${theme.shape.borderRadius}px + 4px)`,
+ backdropFilter: "blur(24px)",
+ border: "1px solid",
+ borderColor:
+ mode === "light"
+ ? alpha(theme.palette.common.black, 0.1)
+ : alpha(theme.palette.common.white, 0.1),
+ backgroundColor:
+ mode === "light"
+ ? alpha(theme.palette.common.white, 0.4)
+ : alpha(theme.palette.common.black, 0.4),
+ boxShadow: theme.shadows[3],
+ padding: "8px 12px",
+}));
+
+const StyledMenuItem = styled(MenuItem)(({ theme }) => ({
+ fontSize: "1.1rem",
+ margin: theme.spacing(4, 2),
+}));
+
+const AppAppBar = () => {
+ const [open, setOpen] = useState(false);
+ const theme = useTheme();
+ const mode = useSelector((state) => state.ui.mode);
+ const location = useLocation();
+ const navigate = useNavigate();
+
+ // Debugging: Log the current theme mode
+ console.log("Current theme mode:", mode);
+
+ const logoSrc =
+ mode === "light" ? "/images/prism-black.png" : "/images/prism-white.png";
+
+ const toggleDrawer = (newOpen) => () => {
+ setOpen(newOpen);
+ };
+
+ const handleScroll = (id) => {
+ if (location.pathname === "/") {
+ const element = document.getElementById(id);
+ if (element) {
+ element.scrollIntoView({ behavior: "smooth" });
+ }
+ } else {
+ navigate(`/#${id}`);
+ }
+ };
+
+ return (
+
+
+
+
+
+
+ handleScroll("features")}
+ >
+ Features
+
+ handleScroll("highlights")}
+ >
+ Highlights
+
+ handleScroll("faq")}
+ >
+ FAQ
+
+
+ Blog
+
+
+
+
+ {/*
+ Sign in
+
+
+ Sign up
+ */}
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Features
+ Testimonials
+ Highlights
+ FAQ
+
+ Blog
+
+ {/*
+
+ Sign up
+
+
+
+
+ Sign in
+
+ */}
+
+
+
+
+
+
+
+ );
+};
+
+export default AppAppBar;
diff --git a/client/src/Components/Common/Footer.jsx b/client/src/Components/Common/Footer.jsx
new file mode 100644
index 000000000..4c33512be
--- /dev/null
+++ b/client/src/Components/Common/Footer.jsx
@@ -0,0 +1,214 @@
+import * as React from 'react';
+import Box from '@mui/material/Box';
+import Container from '@mui/material/Container';
+import IconButton from '@mui/material/IconButton';
+import Link from '@mui/material/Link';
+import Stack from '@mui/material/Stack';
+import Typography from '@mui/material/Typography';
+import { FaFacebook, FaLinkedin, FaGithub, FaTwitter, FaEnvelope } from 'react-icons/fa';
+
+
+function Copyright() {
+ return (
+
+ {'Copyright © '}
+
+ UpRock
+
+
+ {new Date().getFullYear()}
+
+ );
+}
+
+export default function Footer() {
+ return (
+
+
+
+
+
+ Privacy Policy
+
+
+ •
+
+
+ Terms of Service
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Made with ❤️ by
+
+ UpRock
+
+ &
+
+ Bluewave Labs
+
+
+
+
+ Built on
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Solana
+
+
+
+
+ );
+}
diff --git a/Client/src/Components/ConfigBox/index.jsx b/client/src/Components/ConfigBox/index.jsx
similarity index 92%
rename from Client/src/Components/ConfigBox/index.jsx
rename to client/src/Components/ConfigBox/index.jsx
index 8f7eb7b24..9b64712fc 100644
--- a/Client/src/Components/ConfigBox/index.jsx
+++ b/client/src/Components/ConfigBox/index.jsx
@@ -29,10 +29,7 @@ const ConfigBox = styled(Stack)(({ theme }) => ({
},
"& h1, & h2": {
color: theme.palette.primary.contrastTextSecondary,
- },
- "& p": {
- color: theme.palette.primary.contrastTextTertiary,
- },
+ }
}));
export default ConfigBox;
diff --git a/client/src/Components/ConfigRow/index.jsx b/client/src/Components/ConfigRow/index.jsx
new file mode 100644
index 000000000..c19d9ac5a
--- /dev/null
+++ b/client/src/Components/ConfigRow/index.jsx
@@ -0,0 +1,49 @@
+import { Box, Stack, Typography } from "@mui/material";
+import PropTypes from "prop-types";
+import { useTheme } from "@emotion/react";
+import ConfigBox from "../ConfigBox";
+
+/**
+ * ConfigRow is a styled container used to layout content in a row format with specific padding, border, and spacing.
+ * It serves as the wrapper for ConfigBox, with the left section displaying the title and description,
+ * and the right section displaying the children.
+ *
+ * @component
+ * @example
+ * return (
+ *
+ * Left content (Title + Description)
+ * Right content (Children)
+ *
+ * );
+ */
+
+const ConfigRow = ({ title, description, children }) => {
+ const theme = useTheme();
+
+ return (
+
+
+
+ {title}
+
+ {description && (
+
+ {description}
+
+ )}
+
+
+ {children}
+
+
+ );
+};
+
+ConfigRow.propTypes = {
+ title: PropTypes.string.isRequired,
+ description: PropTypes.string,
+ children: PropTypes.node,
+};
+
+export default ConfigRow;
diff --git a/Client/src/Components/Dialog/genericDialog.jsx b/client/src/Components/Dialog/genericDialog.jsx
similarity index 98%
rename from Client/src/Components/Dialog/genericDialog.jsx
rename to client/src/Components/Dialog/genericDialog.jsx
index 871b3f329..b2cbe1299 100644
--- a/Client/src/Components/Dialog/genericDialog.jsx
+++ b/client/src/Components/Dialog/genericDialog.jsx
@@ -21,7 +21,7 @@ const GenericDialog = ({ title, description, open, onClose, theme, children }) =
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
- width: 400,
+ minWidth: 400,
bgcolor: theme.palette.primary.main,
border: 1,
borderColor: theme.palette.primary.lowContrast,
diff --git a/Client/src/Components/Dialog/index.jsx b/client/src/Components/Dialog/index.jsx
similarity index 80%
rename from Client/src/Components/Dialog/index.jsx
rename to client/src/Components/Dialog/index.jsx
index 97d822e84..e07597df4 100644
--- a/Client/src/Components/Dialog/index.jsx
+++ b/client/src/Components/Dialog/index.jsx
@@ -1,18 +1,21 @@
import PropTypes from "prop-types";
-import LoadingButton from "@mui/lab/LoadingButton";
import { Button, Stack } from "@mui/material";
import { GenericDialog } from "./genericDialog";
+import { useTheme } from "@emotion/react";
+import { useTranslation } from "react-i18next";
const Dialog = ({
title,
description,
open,
- theme,
onCancel,
confirmationButtonLabel,
onConfirm,
isLoading,
}) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+
return (
- Cancel
+ {t("cancel", "Cancel")}
-
{confirmationButtonLabel}
-
+
);
@@ -51,7 +54,6 @@ Dialog.propTypes = {
title: PropTypes.string.isRequired,
description: PropTypes.string,
open: PropTypes.bool.isRequired,
- theme: PropTypes.object.isRequired,
onCancel: PropTypes.func.isRequired,
confirmationButtonLabel: PropTypes.string.isRequired,
onConfirm: PropTypes.func.isRequired,
diff --git a/client/src/Components/Dot/index.jsx b/client/src/Components/Dot/index.jsx
new file mode 100644
index 000000000..0676d0a6f
--- /dev/null
+++ b/client/src/Components/Dot/index.jsx
@@ -0,0 +1,24 @@
+import PropTypes from "prop-types";
+
+const Dot = ({ color = "gray", size = "4px", style }) => {
+ return (
+
+ );
+};
+
+Dot.propTypes = {
+ color: PropTypes.string,
+ size: PropTypes.string,
+};
+
+export default Dot;
diff --git a/Client/src/Components/Fallback/index.css b/client/src/Components/Fallback/index.css
similarity index 66%
rename from Client/src/Components/Fallback/index.css
rename to client/src/Components/Fallback/index.css
index 9b4d6f653..cad46300b 100644
--- a/Client/src/Components/Fallback/index.css
+++ b/client/src/Components/Fallback/index.css
@@ -19,6 +19,22 @@
font-size: var(--env-var-font-size-medium);
}
+[class*="fallback__"] .background-pattern-svg {
+ position: absolute;
+ top: 0;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ z-index: 0;
+
+ width: 100%;
+ max-width: 800px;
+ height: 100%;
+ max-height: 800px;
+
+ background-position: center;
+ background-size: cover;
+ background-repeat: no-repeat;
+}
.fallback__status > .MuiStack-root {
margin-left: var(--env-var-spacing-2);
}
diff --git a/client/src/Components/Fallback/index.jsx b/client/src/Components/Fallback/index.jsx
new file mode 100644
index 000000000..b00ddbecc
--- /dev/null
+++ b/client/src/Components/Fallback/index.jsx
@@ -0,0 +1,186 @@
+import PropTypes from "prop-types";
+import { useTheme } from "@emotion/react";
+import { Box, Button, Stack, Typography, Link } from "@mui/material";
+import { Link as RouterLink } from "react-router-dom";
+import Skeleton from "../../assets/Images/create-placeholder.svg?react";
+import SkeletonDark from "../../assets/Images/create-placeholder-dark.svg?react";
+import Background from "../../assets/Images/background-grid.svg?react";
+import Check from "../Check/Check";
+import { useNavigate } from "react-router-dom";
+import { useSelector } from "react-redux";
+import Alert from "../Alert";
+import { useTranslation } from "react-i18next";
+import "./index.css";
+import { useFetchSettings } from "../../Hooks/useFetchSettings";
+import { useState } from "react";
+/**
+ * Fallback component to display a fallback UI with a title, a list of checks, and a navigation button.
+ *
+ * @param {Object} props - The component props.
+ * @param {string} props.title - The title to be displayed in the fallback UI.
+ * @param {Array} props.checks - An array of strings representing the checks to display.
+ * @param {string} [props.link="/"] - The link to navigate to.
+ * @param {boolean} [props.vowelStart=false] - Whether the title starts with a vowel.
+ * @param {boolean} [props.showPageSpeedWarning=false] - Whether to show the PageSpeed API warning.
+ * @returns {JSX.Element} The rendered fallback UI.
+ */
+
+const Fallback = ({
+ title,
+ checks,
+ link = "/",
+ isAdmin,
+ vowelStart = false,
+ showPageSpeedWarning = false,
+}) => {
+ const theme = useTheme();
+ const navigate = useNavigate();
+ const mode = useSelector((state) => state.ui.mode);
+ const { t } = useTranslation();
+ const [settingsData, setSettingsData] = useState(undefined);
+
+ const [isLoading, error] = useFetchSettings({ setSettingsData });
+ // Custom warning message with clickable link
+ const renderWarningMessage = () => {
+ return (
+ <>
+ {t("pageSpeedWarning")}{" "}
+
+ {t("pageSpeedLearnMoreLink")}
+ {" "}
+ {t("pageSpeedAddApiKey")}
+ >
+ );
+ };
+
+ return (
+
+
+ {mode === "light" ? (
+
+ ) : (
+
+ )}
+
+
+
+
+
+ {vowelStart ? "An" : "A"} {title} is used to:
+
+ {checks?.map((check, index) => (
+
+ ))}
+
+ {/* TODO - display a different fallback if user is not an admin*/}
+ {isAdmin && (
+ <>
+ navigate(link)}
+ >
+ Let's create your first {title}
+
+ {/* Bulk create of uptime monitors */}
+ {title === "uptime monitor" && (
+ navigate("/uptime/bulk-import")}
+ >
+ {t("bulkImport.fallbackPage")}
+
+ )}
+
+ {/* Warning box for PageSpeed monitor */}
+ {title === "pagespeed monitor" && showPageSpeedWarning && (
+
+ svg": {
+ color: theme.palette.warningSecondary.contrastText,
+ },
+ },
+ }}
+ >
+ {settingsData?.pagespeedKeySet === false && (
+
+ )}
+
+
+ )}
+ >
+ )}
+
+
+ );
+};
+
+Fallback.propTypes = {
+ title: PropTypes.string.isRequired,
+ checks: PropTypes.arrayOf(PropTypes.string).isRequired,
+ link: PropTypes.string,
+ isAdmin: PropTypes.bool,
+ vowelStart: PropTypes.bool,
+ showPageSpeedWarning: PropTypes.bool,
+};
+
+export default Fallback;
diff --git a/client/src/Components/FilterHeader/index.jsx b/client/src/Components/FilterHeader/index.jsx
new file mode 100644
index 000000000..de438da96
--- /dev/null
+++ b/client/src/Components/FilterHeader/index.jsx
@@ -0,0 +1,95 @@
+import { Checkbox, FormControl, ListItemText, MenuItem, Select } from "@mui/material";
+import { useTheme } from "@emotion/react";
+import PropTypes from "prop-types";
+import AddCircleOutlineIcon from "@mui/icons-material/AddCircleOutline";
+
+/**
+ * A reusable filter header component that displays a dropdown menu with selectable options.
+ *
+ * @component
+ * @param {Object} props - The component props.
+ * @param {string} props.header - The header text to display when no options are selected.
+ * @param {Array} props.options - An array of options to display in the dropdown menu. Each option should have a `value` and `label`.
+ * @param {Array} [props.value] - The currently selected values.
+ * @param {Function} props.onChange - The callback function to handle changes in the selected values.
+ * @param {boolean} [props.multiple=true] - Whether multiple options can be selected.
+ * @returns {JSX.Element} The rendered FilterHeader component.
+ */
+
+const FilterHeader = ({ header, options, value, onChange, multiple = true }) => {
+ const theme = useTheme();
+
+ const controlledValue = value === undefined ? [] : value; // Ensure value is always treated as an array for controlled component purposes
+
+ return (
+
+ (
+
+ )}
+ displayEmpty
+ value={controlledValue}
+ onChange={onChange}
+ renderValue={(selected) => {
+ if (!selected?.length) {
+ return header;
+ }
+
+ return header + " | " + selected
+ .map((value) => options.find((option) => option.value === value)?.label)
+ .filter(Boolean)
+ .join(", ");
+ }}
+ MenuProps={{
+ anchorOrigin: {
+ vertical: "bottom",
+ horizontal: "left",
+ },
+ transformOrigin: {
+ vertical: "top",
+ horizontal: "left",
+ },
+ }}
+ >
+ {options.map((option) => (
+
+
+
+
+ ))}
+
+
+ );
+};
+
+FilterHeader.propTypes = {
+ header: PropTypes.string.isRequired,
+ options: PropTypes.arrayOf(
+ PropTypes.shape({
+ value: PropTypes.string.isRequired,
+ label: PropTypes.string.isRequired,
+ })
+ ).isRequired,
+ value: PropTypes.arrayOf(PropTypes.string),
+ onChange: PropTypes.func.isRequired,
+ multiple: PropTypes.bool,
+};
+
+export default FilterHeader;
diff --git a/client/src/Components/GenericFallback/NetworkError.jsx b/client/src/Components/GenericFallback/NetworkError.jsx
new file mode 100644
index 000000000..b26037a57
--- /dev/null
+++ b/client/src/Components/GenericFallback/NetworkError.jsx
@@ -0,0 +1,20 @@
+import { Typography } from "@mui/material";
+import { useTheme } from "@emotion/react";
+
+const NetworkError = () => {
+ const theme = useTheme();
+ return (
+ <>
+
+ Network error
+
+ Please check your connection
+ >
+ );
+};
+
+export default NetworkError;
diff --git a/client/src/Components/GenericFallback/index.jsx b/client/src/Components/GenericFallback/index.jsx
new file mode 100644
index 000000000..af9ed2ea4
--- /dev/null
+++ b/client/src/Components/GenericFallback/index.jsx
@@ -0,0 +1,78 @@
+import { useTheme } from "@emotion/react";
+import { Box, Stack } from "@mui/material";
+import Skeleton from "../../assets/Images/create-placeholder.svg?react";
+import SkeletonDark from "../../assets/Images/create-placeholder-dark.svg?react";
+import Background from "../../assets/Images/background-grid.svg?react";
+import { useSelector } from "react-redux";
+
+/**
+ * Fallback component to display a fallback UI for network errors
+ *
+ * @returns {JSX.Element} The rendered fallback UI.
+ */
+
+const GenericFallback = ({ children }) => {
+ const theme = useTheme();
+ const mode = useSelector((state) => state.ui.mode);
+
+ return (
+
+
+ {mode === "light" ? (
+
+ ) : (
+
+ )}
+
+
+
+
+ {children}
+
+
+
+ );
+};
+
+export default GenericFallback;
diff --git a/Client/src/Components/HOC/withAdminCheck.jsx b/client/src/Components/HOC/withAdminCheck.jsx
similarity index 100%
rename from Client/src/Components/HOC/withAdminCheck.jsx
rename to client/src/Components/HOC/withAdminCheck.jsx
diff --git a/Client/src/Components/Heading/index.jsx b/client/src/Components/Heading/index.jsx
similarity index 100%
rename from Client/src/Components/Heading/index.jsx
rename to client/src/Components/Heading/index.jsx
diff --git a/Client/src/Pages/Uptime/Home/host.jsx b/client/src/Components/Host/index.jsx
similarity index 52%
rename from Client/src/Pages/Uptime/Home/host.jsx
rename to client/src/Components/Host/index.jsx
index ec78875f4..051e60331 100644
--- a/Client/src/Pages/Uptime/Home/host.jsx
+++ b/client/src/Components/Host/index.jsx
@@ -1,5 +1,7 @@
-import { Box, Typography } from "@mui/material";
+import { Stack, Typography } from "@mui/material";
import PropTypes from "prop-types";
+import { useTheme } from "@emotion/react";
+import Dot from "../Dot";
/**
* Host component.
* This subcomponent receives a params object and displays the host details.
@@ -13,44 +15,33 @@ import PropTypes from "prop-types";
* @returns {React.ElementType} Returns a div element with the host details.
*/
const Host = ({ url, title, percentageColor, percentage }) => {
- const noTitle = title === undefined || title === url;
+ const theme = useTheme();
return (
-
-
+
{title}
-
- {percentageColor && percentage && (
-
- {percentage}%
-
- )}
- {!noTitle && {url} }
-
+ {percentageColor && percentage && (
+ <>
+
+
+ {percentage}%
+
+ >
+ )}
+
+ {url}
+
);
};
diff --git a/Client/src/Components/HttpStatusLabel/index.jsx b/client/src/Components/HttpStatusLabel/index.jsx
similarity index 100%
rename from Client/src/Components/HttpStatusLabel/index.jsx
rename to client/src/Components/HttpStatusLabel/index.jsx
diff --git a/Client/src/Components/IconBox/index.jsx b/client/src/Components/IconBox/index.jsx
similarity index 100%
rename from Client/src/Components/IconBox/index.jsx
rename to client/src/Components/IconBox/index.jsx
diff --git a/client/src/Components/Image/index.jsx b/client/src/Components/Image/index.jsx
new file mode 100644
index 000000000..8f30f8a9e
--- /dev/null
+++ b/client/src/Components/Image/index.jsx
@@ -0,0 +1,72 @@
+import { Box } from "@mui/material";
+import PropTypes from "prop-types";
+
+const isValidBase64Image = (data) => {
+ return /^[A-Za-z0-9+/=]+$/.test(data);
+};
+
+const Image = ({
+ shouldRender = true,
+ src,
+ alt,
+ width = "auto",
+ height = "auto",
+ minWidth = "auto",
+ minHeight = "auto",
+ maxWidth = "auto",
+ maxHeight = "auto",
+ base64,
+ placeholder,
+ sx,
+}) => {
+ if (shouldRender === false) {
+ return null;
+ }
+
+ if (typeof src !== "undefined" && typeof base64 !== "undefined") {
+ console.warn("base64 takes precedence over src and overwrites it");
+ }
+
+ if (typeof base64 !== "undefined" && isValidBase64Image(base64)) {
+ src = `data:image/png;base64,${base64}`;
+ }
+
+ if (
+ typeof src === "undefined" &&
+ typeof base64 === "undefined" &&
+ typeof placeholder !== "undefined"
+ ) {
+ src = placeholder;
+ }
+
+ return (
+
+ );
+};
+
+Image.propTypes = {
+ shouldRender: PropTypes.bool,
+ src: PropTypes.string,
+ alt: PropTypes.string.isRequired,
+ width: PropTypes.string,
+ height: PropTypes.string,
+ minWidth: PropTypes.string,
+ minHeight: PropTypes.string,
+ maxWidth: PropTypes.string,
+ maxHeight: PropTypes.string,
+ base64: PropTypes.string,
+ sx: PropTypes.object,
+};
+
+export default Image;
diff --git a/client/src/Components/InfoBox/index.jsx b/client/src/Components/InfoBox/index.jsx
new file mode 100644
index 000000000..6797d6c9c
--- /dev/null
+++ b/client/src/Components/InfoBox/index.jsx
@@ -0,0 +1,42 @@
+import { RowContainer } from "../StandardContainer";
+import { Stack, Typography } from "@mui/material";
+import Image from "../Image";
+
+import { useTheme } from "@mui/material/styles";
+
+const InfoBox = ({
+ img,
+ icon: Icon,
+ alt,
+ heading,
+ headingLevel = 2,
+ subHeading,
+ subHeadingLevel = "",
+ sx,
+}) => {
+ const theme = useTheme();
+ return (
+
+ {img && (
+
+ )}
+ {Icon && (
+
+ )}
+
+ {heading}
+
+ {subHeading}
+
+
+
+ );
+};
+
+export default InfoBox;
diff --git a/Client/src/Components/Inputs/Checkbox/index.css b/client/src/Components/Inputs/Checkbox/index.css
similarity index 100%
rename from Client/src/Components/Inputs/Checkbox/index.css
rename to client/src/Components/Inputs/Checkbox/index.css
diff --git a/Client/src/Components/Inputs/Checkbox/index.jsx b/client/src/Components/Inputs/Checkbox/index.jsx
similarity index 98%
rename from Client/src/Components/Inputs/Checkbox/index.jsx
rename to client/src/Components/Inputs/Checkbox/index.jsx
index b3a036d57..58b83c7c7 100644
--- a/Client/src/Components/Inputs/Checkbox/index.jsx
+++ b/client/src/Components/Inputs/Checkbox/index.jsx
@@ -75,7 +75,6 @@ const Checkbox = ({
sx={{
"&:hover": { backgroundColor: "transparent" },
"& svg": { width: sizes[size], height: sizes[size] },
- alignSelf: "flex-start",
}}
/>
}
@@ -111,7 +110,7 @@ Checkbox.propTypes = {
label: PropTypes.oneOfType([PropTypes.string, PropTypes.node]).isRequired,
size: PropTypes.oneOf(["small", "medium", "large"]),
isChecked: PropTypes.bool.isRequired,
- value: PropTypes.string,
+ value: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
onChange: PropTypes.func,
isDisabled: PropTypes.bool,
};
diff --git a/client/src/Components/Inputs/ColorPicker/index.jsx b/client/src/Components/Inputs/ColorPicker/index.jsx
new file mode 100644
index 000000000..e64c936fc
--- /dev/null
+++ b/client/src/Components/Inputs/ColorPicker/index.jsx
@@ -0,0 +1,63 @@
+import PropTypes from "prop-types";
+import { Stack, Typography } from "@mui/material";
+import { useTheme } from "@emotion/react";
+import { MuiColorInput } from "mui-color-input";
+
+/**
+ *
+ * @param {*} id The ID of the component
+ * @param {*} value The color value of the component
+ * @param {*} error The error of the component
+ * @param {*} onChange The Change handler function
+ * @param {*} onBlur The Blur handler function
+ * @returns The ColorPicker component
+ * Example usage:
+ *
+ *
+ */
+const ColorPicker = ({ id, name, value, error, onChange, onBlur }) => {
+ const theme = useTheme();
+ return (
+
+ onChange({ target: { name, value: color } })}
+ onBlur={onBlur}
+ />
+ {error && (
+
+ {error}
+
+ )}
+
+ );
+};
+
+ColorPicker.propTypes = {
+ id: PropTypes.string.isRequired,
+ value: PropTypes.string,
+ error: PropTypes.string,
+ onChange: PropTypes.func.isRequired,
+ onBlur: PropTypes.func,
+ name: PropTypes.string,
+};
+
+export default ColorPicker;
diff --git a/client/src/Components/Inputs/ImageUpload/index.jsx b/client/src/Components/Inputs/ImageUpload/index.jsx
new file mode 100644
index 000000000..a49dc4860
--- /dev/null
+++ b/client/src/Components/Inputs/ImageUpload/index.jsx
@@ -0,0 +1,243 @@
+// Components
+import { Box, Stack, Typography } from "@mui/material";
+import CloudUploadIcon from "@mui/icons-material/CloudUpload";
+import Image from "../../../Components/Image";
+import TextField from "@mui/material/TextField";
+import IconButton from "@mui/material/IconButton";
+import ProgressUpload from "../../ProgressBars";
+import ImageIcon from "@mui/icons-material/Image";
+
+// Utils
+import PropTypes from "prop-types";
+import { useCallback, useState, useRef, useEffect } from "react";
+import { useTheme } from "@emotion/react";
+import { useTranslation } from "react-i18next";
+
+/**
+ * ImageUpload component allows users to upload images with drag-and-drop functionality.
+ * It supports file size and format validation.
+ *
+ * @component
+ * @param {Object} props - Component props
+ * @param {boolean} [props.previewIsRound=false] - Determines if the image preview should be round
+ * @param {string} [props.src] - Source URL of the image to display
+ * @param {function} props.onChange - Callback function to handle file change, takes a file as an argument
+ * @param {number} [props.maxSize=3145728] - Maximum file size allowed in bytes (default is 3MB)
+ * @param {Array} [props.accept=['jpg', 'jpeg', 'png']] - Array of accepted file formats
+ * @param {Object} [props.errors] - Object containing error messages
+ * @returns {JSX.Element} The rendered component
+ */
+const ImageUpload = ({
+ previewIsRound = false,
+ src,
+ onChange,
+ maxSize = 3 * 1024 * 1024,
+ accept = ["jpg", "jpeg", "png"],
+ error,
+}) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ const [uploadComplete, setUploadComplete] = useState(false);
+ const [completedFile, setCompletedFile] = useState(null);
+ const [file, setFile] = useState(null);
+ const [progress, setProgress] = useState({ value: 0, isLoading: false });
+ const intervalRef = useRef(null);
+ const [localError, setLocalError] = useState(null);
+ const [isDragging, setIsDragging] = useState(false);
+
+ const roundStyle = previewIsRound ? { borderRadius: "50%" } : {};
+
+ const handleImageChange = useCallback(
+ (file) => {
+ if (!file) return;
+
+ const isValidType = accept.some((type) =>
+ file.type.includes(type)
+ );
+ const isValidSize = file.size <= maxSize;
+
+ if (!isValidType) {
+ setLocalError(t('invalidFileFormat'));
+ return;
+ }
+ if (!isValidSize) {
+ setLocalError(t('invalidFileSize'));
+ return;
+ }
+
+ setLocalError(null);
+
+ const previewFile = {
+ src: URL.createObjectURL(file),
+ name: file.name,
+ file,
+ };
+
+ setFile(previewFile);
+ setProgress({ value: 0, isLoading: true });
+
+ intervalRef.current = setInterval(() => {
+ setProgress((prev) => {
+ const buffer = 12;
+ if (prev.value + buffer >= 100) {
+ clearInterval(intervalRef.current);
+ setUploadComplete(true);
+ setCompletedFile(previewFile);
+ return { value: 100, isLoading: false };
+ }
+ return { value: prev.value + buffer, isLoading: true };
+ });
+ }, 120);
+ },
+ [maxSize, accept]
+ );
+
+ useEffect(() => {
+ if (uploadComplete && completedFile) {
+ onChange?.(completedFile);
+ setUploadComplete(false);
+ setCompletedFile(null);
+ }
+ }, [uploadComplete, completedFile, onChange]);
+
+
+ return (
+ <>
+ {src ? (
+
+
+
+ ) : (
+ <>
+ setIsDragging(true)}
+ onDragLeave={() => setIsDragging(false)}
+ onDrop={() => setIsDragging(false)}
+ sx={{
+ position: "relative",
+ height: "fit-content",
+ border: "dashed",
+ borderRadius: theme.shape.borderRadius,
+ borderColor: isDragging
+ ? theme.palette.primary.main
+ : theme.palette.primary.lowContrast,
+ backgroundColor: isDragging
+ ? "hsl(215, 87%, 51%, 0.05)"
+ : "transparent",
+ borderWidth: "2px",
+ transition: "0.2s",
+ "&:hover": {
+ borderColor: theme.palette.primary.main,
+ backgroundColor: "hsl(215, 87%, 51%, 0.05)",
+ },
+ }}
+ >
+ handleImageChange(e?.target?.files?.[0])}
+ sx={{
+ width: "100%",
+ "& .MuiInputBase-input[type='file']": {
+ opacity: 0,
+ cursor: "pointer",
+ maxWidth: "500px",
+ minHeight: "175px",
+ zIndex: 1,
+ },
+ "& fieldset": {
+ padding: 0,
+ border: "none",
+ },
+ }}
+ />
+
+
+
+
+
+
+ {t('ClickUpload')}
+ {" "}
+ or {t('DragandDrop')}
+
+ ({t('MaxSize')}: {Math.round(maxSize / 1024 / 1024)}MB)
+
+
+
+ {(localError || progress.isLoading || progress.value !== 0) && (
+ }
+ label={file?.name || "Upload failed"}
+ size={file?.size}
+ progress={progress.value}
+ onClick={() => {
+ clearInterval(intervalRef.current);
+ setFile(null);
+ setProgress({ value: 0, isLoading: false });
+ setLocalError(null);
+ onChange(undefined);
+ }}
+ error={localError || error}
+ />
+ )}
+
+ {t('SupportedFormats')}: {accept.join(", ").toUpperCase()}
+
+ >
+ )}
+ >
+ );
+};
+
+ImageUpload.propTypes = {
+ previewIsRound: PropTypes.bool,
+ src: PropTypes.string,
+ onChange: PropTypes.func,
+ maxSize: PropTypes.number,
+ accept: PropTypes.array,
+ error: PropTypes.string,
+};
+
+export default ImageUpload;
\ No newline at end of file
diff --git a/Client/src/Components/Inputs/Radio/index.css b/client/src/Components/Inputs/Radio/index.css
similarity index 100%
rename from Client/src/Components/Inputs/Radio/index.css
rename to client/src/Components/Inputs/Radio/index.css
diff --git a/Client/src/Components/Inputs/Radio/index.jsx b/client/src/Components/Inputs/Radio/index.jsx
similarity index 100%
rename from Client/src/Components/Inputs/Radio/index.jsx
rename to client/src/Components/Inputs/Radio/index.jsx
diff --git a/Client/src/Components/Inputs/Search/index.jsx b/client/src/Components/Inputs/Search/index.jsx
similarity index 83%
rename from Client/src/Components/Inputs/Search/index.jsx
rename to client/src/Components/Inputs/Search/index.jsx
index 1dff6b532..a3b75161c 100644
--- a/Client/src/Components/Inputs/Search/index.jsx
+++ b/client/src/Components/Inputs/Search/index.jsx
@@ -12,6 +12,7 @@ import SearchIcon from "../../../assets/icons/search.svg?react";
* @param {string} props.filteredBy - Key to access the option label from the options
* @param {string} props.value - Current input value for the Autocomplete
* @param {Function} props.handleChange - Function to call when the input changes
+ * @param {Function} Prop.onBlur - Function to call when the input is blured
* @param {Object} props.sx - Additional styles to apply to the component
* @returns {JSX.Element} The rendered Search component
*/
@@ -54,10 +55,14 @@ const Search = ({
isAdorned = true,
error,
disabled,
+ startAdornment,
+ endAdornment,
+ onBlur,
}) => {
const theme = useTheme();
return (
{
- handleChange && handleChange(newValue);
+ handleChange(newValue);
}}
fullWidth
freeSolo
@@ -74,6 +79,7 @@ const Search = ({
disableClearable
options={options}
getOptionLabel={(option) => option[filteredBy]}
+ isOptionEqualToValue={(option, value) => option._id === value._id} // Compare by unique identifier
renderInput={(params) => (
}),
+ slotProps={{
+ input: {
+ ...params.InputProps,
+ ...(isAdorned && { startAdornment: }),
+ ...(startAdornment && { startAdornment: startAdornment }),
+ ...(endAdornment && { endAdornment: endAdornment }),
+ },
}}
sx={{
"& fieldset": {
@@ -118,7 +128,7 @@ const Search = ({
option.id}
+ getOptionKey={(option) => {
+ return option._id;
+ }}
renderOption={(props, option) => {
const { key, ...optionProps } = props;
+ const hasSecondaryLabel = secondaryLabel && option[secondaryLabel] !== undefined;
return (
- {option[filteredBy] + (secondaryLabel ? ` (${option[secondaryLabel]})` : "")}
+ {option[filteredBy] +
+ (hasSecondaryLabel ? ` (${option[secondaryLabel]})` : "")}
);
}}
@@ -176,8 +190,8 @@ const Search = ({
color: "red",
},
"& li.MuiAutocomplete-option:hover:not([aria-selected='true'])": {
- color: theme.palette.primary.main,
- backgroundColor: theme.palette.primary.contrastTextSecondary,
+ color: theme.palette.secondary.contrastText,
+ backgroundColor: theme.palette.secondary.main,
},
"& .MuiAutocomplete-noOptions": {
px: theme.spacing(6),
@@ -196,6 +210,7 @@ const Search = ({
};
Search.propTypes = {
+ label: PropTypes.string,
id: PropTypes.string,
multiple: PropTypes.bool,
options: PropTypes.array.isRequired,
@@ -209,6 +224,9 @@ Search.propTypes = {
sx: PropTypes.object,
error: PropTypes.string,
disabled: PropTypes.bool,
+ startAdornment: PropTypes.object,
+ endAdornment: PropTypes.object,
+ onBlur: PropTypes.func,
};
export default Search;
diff --git a/Client/src/Components/Inputs/Select/index.css b/client/src/Components/Inputs/Select/index.css
similarity index 100%
rename from Client/src/Components/Inputs/Select/index.css
rename to client/src/Components/Inputs/Select/index.css
diff --git a/Client/src/Components/Inputs/Select/index.jsx b/client/src/Components/Inputs/Select/index.jsx
similarity index 79%
rename from Client/src/Components/Inputs/Select/index.jsx
rename to client/src/Components/Inputs/Select/index.jsx
index f0a1d11c0..927247d77 100644
--- a/Client/src/Components/Inputs/Select/index.jsx
+++ b/client/src/Components/Inputs/Select/index.jsx
@@ -18,6 +18,7 @@ import "./index.css";
* @param {string} props.items.name - The display name of each item.
* @param {function} props.onChange - The function to handle onChange event.
* @param {object} props.sx - The custom styles object for MUI Select component.
+ * @param {number} props.maxWidth - Maximum width in pixels for the select component. Enables responsive text truncation.
* @returns {JSX.Element}
*
* @example
@@ -50,6 +51,7 @@ const Select = ({
sx,
name = "",
labelControlSpacing = 2,
+ maxWidth,
}) => {
const theme = useTheme();
const itemStyles = {
@@ -59,6 +61,13 @@ const Select = ({
margin: theme.spacing(2),
};
+ const responsiveMaxWidth = {
+ xs: `${maxWidth * 0.5}px`,
+ sm: `${maxWidth * 0.75}px`,
+ md: `${maxWidth * 0.9}px`,
+ lg: `${maxWidth}px`,
+ };
+
return (
{
+ const selectedItem = items.find((item) => item._id === selected);
+ const displayName = selectedItem ? selectedItem.name : placeholder;
+ return (
+
+ {displayName}
+
+ );
+ }}
>
{placeholder && (
{
const theme = useTheme();
return (
@@ -23,7 +25,7 @@ export const HttpAdornment = ({ https }) => {
color={theme.palette.primary.contrastTextSecondary}
sx={{ lineHeight: 1, opacity: 0.8 }}
>
- {https ? "https" : "http"}://
+ {https ? "https" : "http"}
);
@@ -31,6 +33,7 @@ export const HttpAdornment = ({ https }) => {
HttpAdornment.propTypes = {
https: PropTypes.bool.isRequired,
+ prefix: PropTypes.string,
};
export const PasswordEndAdornment = ({ fieldType, setFieldType }) => {
diff --git a/Client/src/Components/Inputs/TextInput/index.jsx b/client/src/Components/Inputs/TextInput/index.jsx
similarity index 86%
rename from Client/src/Components/Inputs/TextInput/index.jsx
rename to client/src/Components/Inputs/TextInput/index.jsx
index 38a6b6161..bb2df5d21 100644
--- a/Client/src/Components/Inputs/TextInput/index.jsx
+++ b/client/src/Components/Inputs/TextInput/index.jsx
@@ -6,18 +6,6 @@ import PropTypes from "prop-types";
const getSx = (theme, type, maxWidth) => {
const sx = {
maxWidth: maxWidth,
- "& .MuiOutlinedInput-root ": {
- "&:hover .MuiOutlinedInput-notchedOutline": {
- borderColor: theme.palette.primary.contrastText, // Adjust hover border color
- },
- "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
- borderColor: theme.palette.accent.main, // Adjust focus border color
- },
- "&.Mui-disabled .MuiOutlinedInput-notchedOutline": {
- borderColor: theme.palette.primary.contrastText, // CAIO_REVIEW
- opacity: 0.5,
- },
- },
"& .MuiFormHelperText-root": {
position: "absolute",
@@ -116,6 +104,7 @@ const TextInput = forwardRef(
fontSize={"var(--env-var-font-size-medium)"}
color={theme.palette.primary.contrastTextSecondary}
fontWeight={500}
+ mb={theme.spacing(2)}
>
{label}
{isRequired && }
@@ -152,9 +141,9 @@ TextInput.displayName = "TextInput";
TextInput.propTypes = {
type: PropTypes.string,
- id: PropTypes.string.isRequired,
+ id: PropTypes.string,
name: PropTypes.string,
- value: PropTypes.string,
+ value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
placeholder: PropTypes.string,
isRequired: PropTypes.bool,
isOptional: PropTypes.bool,
diff --git a/Client/src/Components/Label/index.css b/client/src/Components/Label/index.css
similarity index 100%
rename from Client/src/Components/Label/index.css
rename to client/src/Components/Label/index.css
diff --git a/Client/src/Components/Label/index.jsx b/client/src/Components/Label/index.jsx
similarity index 94%
rename from Client/src/Components/Label/index.jsx
rename to client/src/Components/Label/index.jsx
index c651b93e7..6ba55e81c 100644
--- a/Client/src/Components/Label/index.jsx
+++ b/client/src/Components/Label/index.jsx
@@ -114,7 +114,7 @@ ColoredLabel.propTypes = {
/**
* @component
* @param {Object} props
- * @param { 'up' | 'down' | 'cannot resolve'} props.status - The status for the label
+ * @param {'up' | 'down' | 'paused' | 'pending' | 'cannot resolve' | 'published' | 'unpublished'} props.status - The status for the label
* @param {string} props.text - The text of the label
* @returns {JSX.Element}
* @example
@@ -128,6 +128,8 @@ const statusToTheme = {
paused: "warning",
pending: "warning",
"cannot resolve": "error",
+ published: "success",
+ unpublished: "error",
};
const StatusLabel = ({ status, text, customStyles }) => {
@@ -156,7 +158,7 @@ const StatusLabel = ({ status, text, customStyles }) => {
};
StatusLabel.propTypes = {
- status: PropTypes.oneOf(["up", "down", "paused", "pending", "cannot resolve"]),
+ status: PropTypes.oneOf(["up", "down", "paused", "pending", "cannot resolve", "published", "unpublished"]),
text: PropTypes.string,
customStyles: PropTypes.object,
};
diff --git a/client/src/Components/LanguageSelector.jsx b/client/src/Components/LanguageSelector.jsx
new file mode 100644
index 000000000..70c41e640
--- /dev/null
+++ b/client/src/Components/LanguageSelector.jsx
@@ -0,0 +1,136 @@
+import { useTranslation } from "react-i18next";
+import { Box, MenuItem, Select, Stack } from "@mui/material";
+import { useTheme } from "@emotion/react";
+import "flag-icons/css/flag-icons.min.css";
+import { useSelector } from "react-redux";
+
+const LanguageSelector = () => {
+ const { i18n } = useTranslation();
+ const theme = useTheme();
+ const { language } = useSelector((state) => state.ui);
+
+ const handleChange = (event) => {
+ const newLang = event.target.value;
+ i18n.changeLanguage(newLang);
+ };
+
+ const languages = Object.keys(i18n.options.resources || {});
+
+ return (
+
+ {languages.map((lang) => {
+ const flag = lang ? `fi fi-${lang}` : null;
+
+ return (
+
+
+
+ {flag && }
+
+
+ {lang}
+
+
+
+ );
+ })}
+
+ );
+};
+
+export default LanguageSelector;
diff --git a/Client/src/Components/Layouts/HomeLayout/index.css b/client/src/Components/Layouts/HomeLayout/index.css
similarity index 56%
rename from Client/src/Components/Layouts/HomeLayout/index.css
rename to client/src/Components/Layouts/HomeLayout/index.css
index e08904f8e..28ac340f8 100644
--- a/Client/src/Components/Layouts/HomeLayout/index.css
+++ b/client/src/Components/Layouts/HomeLayout/index.css
@@ -1,9 +1,8 @@
.home-layout {
position: relative;
min-height: 100vh;
- max-width: 1400px;
margin: 0 auto;
- padding: var(--env-var-spacing-2);
+ padding: 0;
}
/* TODO go for this approach for responsiveness. The aside needs to be taken care of */
@@ -15,10 +14,9 @@
.home-layout aside {
position: sticky;
- top: var(--env-var-spacing-2);
+ top: 0;
left: 0;
-
- height: calc(100vh - var(--env-var-spacing-2) * 2);
+ height: 100vh;
max-width: var(--env-var-side-bar-width);
}
@@ -27,19 +25,9 @@
flex: 1;
}
-.home-layout > div:has(> [class*="fallback__"]) .background-pattern-svg {
- position: absolute;
- top: 0;
- left: 50%;
- transform: translate(-50%, -50%);
- z-index: 0;
-
- width: 100%;
- max-width: 800px;
- height: 100%;
- max-height: 800px;
-
- background-position: center;
- background-size: cover;
- background-repeat: no-repeat;
-}
+.home-content-wrapper {
+ padding: var(--env-var-spacing-2);
+ max-width: 1400px;
+ margin: 0 auto;
+ flex: 1;
+}
\ No newline at end of file
diff --git a/Client/src/Components/Layouts/HomeLayout/index.jsx b/client/src/Components/Layouts/HomeLayout/index.jsx
similarity index 81%
rename from Client/src/Components/Layouts/HomeLayout/index.jsx
rename to client/src/Components/Layouts/HomeLayout/index.jsx
index b605a0d53..55b612522 100644
--- a/Client/src/Components/Layouts/HomeLayout/index.jsx
+++ b/client/src/Components/Layouts/HomeLayout/index.jsx
@@ -12,7 +12,9 @@ const HomeLayout = () => {
gap={14}
>
-
+
+
+
);
};
diff --git a/Client/src/Components/Link/index.jsx b/client/src/Components/Link/index.jsx
similarity index 89%
rename from Client/src/Components/Link/index.jsx
rename to client/src/Components/Link/index.jsx
index 6a317502b..7a623a3b0 100644
--- a/Client/src/Components/Link/index.jsx
+++ b/client/src/Components/Link/index.jsx
@@ -14,7 +14,14 @@ const Link = ({ level, label, url }) => {
const theme = useTheme();
const levelConfig = {
- primary: {},
+ primary: {
+ color: theme.palette.primary.contrastTextTertiary,
+ sx: {
+ ":hover": {
+ color: theme.palette.primary.contrastTextSecondary,
+ },
+ },
+ },
secondary: {
color: theme.palette.primary.contrastTextSecondary,
sx: {
diff --git a/Client/src/Components/Link/link.css b/client/src/Components/Link/link.css
similarity index 100%
rename from Client/src/Components/Link/link.css
rename to client/src/Components/Link/link.css
diff --git a/client/src/Components/MonitorCountHeader/index.jsx b/client/src/Components/MonitorCountHeader/index.jsx
new file mode 100644
index 000000000..0b3478df5
--- /dev/null
+++ b/client/src/Components/MonitorCountHeader/index.jsx
@@ -0,0 +1,52 @@
+import { Stack, Typography } from "@mui/material";
+import PropTypes from "prop-types";
+import { useTheme } from "@emotion/react";
+import SkeletonLayout from "./skeleton";
+
+const MonitorCountHeader = ({
+ shouldRender = true,
+ monitorCount,
+ heading = "monitors",
+ sx,
+ children,
+}) => {
+ const theme = useTheme();
+ if (!shouldRender) return ;
+
+ if (monitorCount === 1) {
+ heading = "monitor";
+ }
+
+ return (
+
+ {monitorCount} {heading}
+ {children}
+
+ );
+};
+
+MonitorCountHeader.propTypes = {
+ shouldRender: PropTypes.bool,
+ monitorCount: PropTypes.number,
+ heading: PropTypes.string,
+ children: PropTypes.node,
+ sx: PropTypes.object,
+};
+
+export default MonitorCountHeader;
diff --git a/client/src/Components/MonitorCountHeader/skeleton.jsx b/client/src/Components/MonitorCountHeader/skeleton.jsx
new file mode 100644
index 000000000..9b4971c32
--- /dev/null
+++ b/client/src/Components/MonitorCountHeader/skeleton.jsx
@@ -0,0 +1,26 @@
+import { Stack, Skeleton } from "@mui/material";
+import { useTheme } from "@emotion/react";
+
+const SkeletonLayout = () => {
+ const theme = useTheme();
+ return (
+
+
+
+
+ );
+};
+
+export default SkeletonLayout;
diff --git a/client/src/Components/MonitorCreateHeader/index.jsx b/client/src/Components/MonitorCreateHeader/index.jsx
new file mode 100644
index 000000000..15d6d5c0f
--- /dev/null
+++ b/client/src/Components/MonitorCreateHeader/index.jsx
@@ -0,0 +1,61 @@
+import { Stack, Button } from "@mui/material";
+import { useNavigate } from "react-router-dom";
+import PropTypes from "prop-types";
+import { useTranslation } from "react-i18next";
+import { useTheme } from "@emotion/react";
+
+const CreateMonitorHeader = ({
+ isAdmin,
+ label,
+ isLoading = true,
+ path,
+ bulkPath,
+}) => {
+ const navigate = useNavigate();
+ const { t } = useTranslation();
+ const theme = useTheme();
+
+ // Use the provided label or fall back to the translated default
+
+ if (!isAdmin) return null;
+
+ return (
+
+ navigate(path)}
+ >
+ {label || t("createNew")}
+
+ {bulkPath && (
+ {
+ navigate(`${bulkPath}`);
+ }}
+ >
+ {t("bulkImport.title")}
+
+ )}
+
+ );
+};
+
+export default CreateMonitorHeader;
+
+CreateMonitorHeader.propTypes = {
+ isAdmin: PropTypes.bool.isRequired,
+ isLoading: PropTypes.bool,
+ path: PropTypes.string.isRequired,
+ label: PropTypes.string,
+ bulkPath: PropTypes.string,
+};
diff --git a/client/src/Components/MonitorCreateHeader/skeleton.jsx b/client/src/Components/MonitorCreateHeader/skeleton.jsx
new file mode 100644
index 000000000..7583f7849
--- /dev/null
+++ b/client/src/Components/MonitorCreateHeader/skeleton.jsx
@@ -0,0 +1,19 @@
+import { Stack, Skeleton } from "@mui/material";
+
+const SkeletonLayout = () => {
+ return (
+
+
+
+ );
+};
+
+export default SkeletonLayout;
diff --git a/client/src/Components/MonitorStatusHeader/ConfigButton/index.jsx b/client/src/Components/MonitorStatusHeader/ConfigButton/index.jsx
new file mode 100644
index 000000000..c966abf33
--- /dev/null
+++ b/client/src/Components/MonitorStatusHeader/ConfigButton/index.jsx
@@ -0,0 +1,41 @@
+import { Button, Box } from "@mui/material";
+import { useTheme } from "@emotion/react";
+import { useNavigate } from "react-router-dom";
+import SettingsIcon from "../../../assets/icons/settings-bold.svg?react";
+import PropTypes from "prop-types";
+const ConfigButton = ({ shouldRender = true, monitorId, path }) => {
+ const theme = useTheme();
+ const navigate = useNavigate();
+
+ if (!shouldRender) return null;
+
+ return (
+
+ navigate(`/${path}/configure/${monitorId}`)}
+ sx={{
+ px: theme.spacing(5),
+ "& svg": {
+ mr: theme.spacing(3),
+ "& path": {
+ /* Should always be contrastText for the button color */
+ stroke: theme.palette.secondary.contrastText,
+ },
+ },
+ }}
+ >
+ Configure
+
+
+ );
+};
+
+ConfigButton.propTypes = {
+ shouldRender: PropTypes.bool,
+ monitorId: PropTypes.string.isRequired,
+ path: PropTypes.string.isRequired,
+};
+
+export default ConfigButton;
diff --git a/client/src/Components/MonitorStatusHeader/index.jsx b/client/src/Components/MonitorStatusHeader/index.jsx
new file mode 100644
index 000000000..a3cb5edfe
--- /dev/null
+++ b/client/src/Components/MonitorStatusHeader/index.jsx
@@ -0,0 +1,58 @@
+import { Stack, Typography } from "@mui/material";
+import PulseDot from "../Animated/PulseDot";
+import Dot from "../Dot";
+import { useTheme } from "@emotion/react";
+import useUtils from "../../Pages/Uptime/Monitors/Hooks/useUtils";
+import { formatDurationRounded } from "../../Utils/timeUtils";
+import ConfigButton from "./ConfigButton";
+import SkeletonLayout from "./skeleton";
+import PropTypes from "prop-types";
+
+const MonitorStatusHeader = ({ path, isLoading = false, isAdmin, monitor }) => {
+ const theme = useTheme();
+ const { statusColor, determineState } = useUtils();
+ if (isLoading) {
+ return ;
+ }
+
+ return (
+
+
+ {monitor?.name}
+
+
+
+ {monitor?.url?.replace(/^https?:\/\//, "") || "..."}
+
+
+
+ Checking every {formatDurationRounded(monitor?.interval)}.
+
+
+
+
+
+ );
+};
+
+MonitorStatusHeader.propTypes = {
+ path: PropTypes.string.isRequired,
+ isLoading: PropTypes.bool,
+ isAdmin: PropTypes.bool,
+ monitor: PropTypes.object,
+};
+
+export default MonitorStatusHeader;
diff --git a/client/src/Components/MonitorStatusHeader/skeleton.jsx b/client/src/Components/MonitorStatusHeader/skeleton.jsx
new file mode 100644
index 000000000..64dc0547f
--- /dev/null
+++ b/client/src/Components/MonitorStatusHeader/skeleton.jsx
@@ -0,0 +1,23 @@
+import { Stack, Skeleton } from "@mui/material";
+
+const SkeletonLayout = () => {
+ return (
+
+
+
+
+ );
+};
+
+export default SkeletonLayout;
diff --git a/client/src/Components/MonitorTimeFrameHeader/index.jsx b/client/src/Components/MonitorTimeFrameHeader/index.jsx
new file mode 100644
index 000000000..3958d507c
--- /dev/null
+++ b/client/src/Components/MonitorTimeFrameHeader/index.jsx
@@ -0,0 +1,85 @@
+import { Stack, Typography, Button, ButtonGroup } from "@mui/material";
+import { useTheme } from "@emotion/react";
+import SkeletonLayout from "./skeleton";
+import PropTypes from "prop-types";
+
+const MonitorTimeFrameHeader = ({
+ isLoading = false,
+ hasDateRange = true,
+ dateRange,
+ setDateRange,
+}) => {
+ const theme = useTheme();
+
+ if (isLoading) {
+ return ;
+ }
+
+ let timeFramePicker = null;
+
+ if (hasDateRange) {
+ timeFramePicker = (
+
+ setDateRange("recent")}
+ >
+ Recent
+
+ setDateRange("day")}
+ >
+ Day
+
+ setDateRange("week")}
+ >
+ Week
+
+ setDateRange("month")}
+ >
+ Month
+
+
+ );
+ }
+
+ return (
+
+
+ Showing statistics for past{" "}
+ {dateRange === "recent"
+ ? "2 hours"
+ : dateRange === "day"
+ ? "24 hours"
+ : dateRange === "week"
+ ? "7 days"
+ : "30 days"}
+ .
+
+ {timeFramePicker}
+
+ );
+};
+
+MonitorTimeFrameHeader.propTypes = {
+ isLoading: PropTypes.bool,
+ hasDateRange: PropTypes.bool,
+ dateRange: PropTypes.string,
+ setDateRange: PropTypes.func,
+};
+
+export default MonitorTimeFrameHeader;
diff --git a/client/src/Components/MonitorTimeFrameHeader/skeleton.jsx b/client/src/Components/MonitorTimeFrameHeader/skeleton.jsx
new file mode 100644
index 000000000..d7c395d54
--- /dev/null
+++ b/client/src/Components/MonitorTimeFrameHeader/skeleton.jsx
@@ -0,0 +1,23 @@
+import { Stack, Skeleton } from "@mui/material";
+
+const SkeletonLayout = () => {
+ return (
+
+
+
+
+ );
+};
+
+export default SkeletonLayout;
diff --git a/client/src/Components/NotificationIntegrationModal/Components/NotificationIntegrationModal.jsx b/client/src/Components/NotificationIntegrationModal/Components/NotificationIntegrationModal.jsx
new file mode 100644
index 000000000..dc94ee731
--- /dev/null
+++ b/client/src/Components/NotificationIntegrationModal/Components/NotificationIntegrationModal.jsx
@@ -0,0 +1,419 @@
+import { useState, useMemo, useEffect, useCallback } from "react";
+import { useTranslation } from "react-i18next";
+import PropTypes from "prop-types";
+
+import {
+ Dialog,
+ DialogContent,
+ DialogActions,
+ Button,
+ Typography,
+ Box,
+ Tabs,
+ Tab,
+ Stack,
+} from "@mui/material";
+import { useTheme } from "@emotion/react";
+import TabPanel from "./TabPanel";
+import TabComponent from "./TabComponent";
+import useNotifications from "../Hooks/useNotification";
+
+// Define constants for notification types to avoid magic values
+const NOTIFICATION_TYPES = {
+ SLACK: "slack",
+ DISCORD: "discord",
+ TELEGRAM: "telegram",
+ WEBHOOK: "webhook",
+};
+
+// Define constants for field IDs
+const FIELD_IDS = {
+ WEBHOOK: "webhook",
+ TOKEN: "token",
+ CHAT_ID: "chatId",
+ URL: "url",
+};
+
+const NotificationIntegrationModal = ({
+ open,
+ onClose,
+ monitor,
+ setMonitor,
+ // Optional prop to configure available notification types
+ notificationTypes = null,
+}) => {
+ const { t } = useTranslation();
+ const theme = useTheme();
+ const [tabValue, setTabValue] = useState(0);
+
+ const [loading, _, sendTestNotification] = useNotifications();
+
+ // Helper to get the field state key with error handling
+ const getFieldKey = useCallback(
+ (typeId, fieldId) => {
+ if (typeof typeId !== "string" || typeId === "") {
+ throw new Error(t("errorInvalidTypeId"));
+ }
+
+ if (typeof fieldId !== "string" || fieldId === "") {
+ throw new Error(t("errorInvalidFieldId"));
+ }
+
+ return `${typeId}${fieldId.charAt(0).toUpperCase() + fieldId.slice(1)}`;
+ },
+ [t]
+ );
+
+ // Define notification types
+ const DEFAULT_NOTIFICATION_TYPES = [
+ {
+ id: NOTIFICATION_TYPES.SLACK,
+ label: t("notifications.slack.label"),
+ description: t("notifications.slack.description"),
+ fields: [
+ {
+ id: FIELD_IDS.WEBHOOK,
+ label: t("notifications.slack.webhookLabel"),
+ placeholder: t("notifications.slack.webhookPlaceholder"),
+ type: "text",
+ },
+ ],
+ },
+ {
+ id: NOTIFICATION_TYPES.DISCORD,
+ label: t("notifications.discord.label"),
+ description: t("notifications.discord.description"),
+ fields: [
+ {
+ id: FIELD_IDS.WEBHOOK,
+ label: t("notifications.discord.webhookLabel"),
+ placeholder: t("notifications.discord.webhookPlaceholder"),
+ type: "text",
+ },
+ ],
+ },
+ {
+ id: NOTIFICATION_TYPES.TELEGRAM,
+ label: t("notifications.telegram.label"),
+ description: t("notifications.telegram.description"),
+ fields: [
+ {
+ id: FIELD_IDS.TOKEN,
+ label: t("notifications.telegram.tokenLabel"),
+ placeholder: t("notifications.telegram.tokenPlaceholder"),
+ type: "text",
+ },
+ {
+ id: FIELD_IDS.CHAT_ID,
+ label: t("notifications.telegram.chatIdLabel"),
+ placeholder: t("notifications.telegram.chatIdPlaceholder"),
+ type: "text",
+ },
+ ],
+ },
+ {
+ id: NOTIFICATION_TYPES.WEBHOOK,
+ label: t("notifications.webhook.label"),
+ description: t("notifications.webhook.description"),
+ fields: [
+ {
+ id: FIELD_IDS.URL,
+ label: t("notifications.webhook.urlLabel"),
+ placeholder: t("notifications.webhook.urlPlaceholder"),
+ type: "text",
+ },
+ ],
+ },
+ ];
+
+ // Use provided notification types or default to our translated ones
+ const activeNotificationTypes = notificationTypes || DEFAULT_NOTIFICATION_TYPES;
+
+ // Memoized function to initialize integrations state
+ const initialIntegrationsState = useMemo(() => {
+ const state = {};
+
+ activeNotificationTypes.forEach((type) => {
+ // Add enabled flag for each notification type
+ state[type.id] = false;
+
+ // Add state for each field in the notification type
+ type.fields.forEach((field) => {
+ const fieldKey = getFieldKey(type.id, field.id);
+ state[fieldKey] = "";
+ });
+ });
+
+ return state;
+ }, [activeNotificationTypes, getFieldKey]); // Only recompute when these dependencies change
+
+ const [integrations, setIntegrations] = useState(initialIntegrationsState);
+
+ useEffect(() => {
+ if (open) {
+ const extractNotificationValues = () => {
+ const values = {};
+
+ if (!monitor?.notifications || !Array.isArray(monitor.notifications)) {
+ return values;
+ }
+
+ monitor.notifications.forEach((notification) => {
+ // Handle notification based on its structure
+ if (notification.type === "webhook" && notification.platform) {
+ if (typeof notification.config === "undefined") return;
+ const platform = notification.platform;
+ values[platform] = true; // Set platform as enabled
+
+ // Extract configuration based on platform
+ switch (platform) {
+ case NOTIFICATION_TYPES.SLACK:
+ case NOTIFICATION_TYPES.DISCORD:
+ if (notification.config.webhookUrl) {
+ values[getFieldKey(platform, FIELD_IDS.WEBHOOK)] =
+ notification.config.webhookUrl;
+ }
+ break;
+ case NOTIFICATION_TYPES.TELEGRAM:
+ if (notification.config.botToken) {
+ values[getFieldKey(platform, FIELD_IDS.TOKEN)] =
+ notification.config.botToken;
+ }
+ if (notification.config.chatId) {
+ values[getFieldKey(platform, FIELD_IDS.CHAT_ID)] =
+ notification.config.chatId;
+ }
+ break;
+ case NOTIFICATION_TYPES.WEBHOOK:
+ if (notification.config.webhookUrl) {
+ values[getFieldKey(platform, FIELD_IDS.URL)] =
+ notification.config.webhookUrl;
+ }
+ break;
+ }
+ }
+ });
+
+ return values;
+ };
+
+ const extractedValues = extractNotificationValues();
+ setIntegrations((prev) => ({
+ ...prev,
+ ...extractedValues,
+ }));
+ }
+ }, [open, monitor, getFieldKey]);
+
+ const handleChangeTab = (event, newValue) => {
+ setTabValue(newValue);
+ };
+
+ const handleIntegrationChange = (type, checked) => {
+ setIntegrations((prev) => ({
+ ...prev,
+ [type]: checked,
+ }));
+ };
+
+ const handleInputChange = (type, value) => {
+ setIntegrations((prev) => ({
+ ...prev,
+ [type]: value,
+ }));
+ };
+
+ const handleTestNotification = async (type) => {
+ // Get the notification type details
+ const notificationType = activeNotificationTypes.find((t) => t.id === type);
+
+ if (typeof notificationType === "undefined") {
+ return;
+ }
+
+ // Prepare config object based on notification type
+ const config = {};
+
+ // Add each field value to the config object
+ notificationType.fields.forEach((field) => {
+ const fieldKey = getFieldKey(type, field.id);
+ config[field.id] = integrations[fieldKey];
+ });
+
+ await sendTestNotification(type, config);
+ };
+
+ // In NotificationIntegrationModal.jsx, update the handleSave function:
+
+ const handleSave = () => {
+ // Get existing notifications
+ const notifications = [...(monitor?.notifications || [])];
+
+ // Get all notification types IDs
+ const existingTypes = activeNotificationTypes.map((type) => type.id);
+
+ // Filter out notifications that are configurable in this modal
+ const filteredNotifications = notifications.filter((notification) => {
+ if (notification.platform) {
+ return !existingTypes.includes(notification.platform);
+ }
+
+ return !existingTypes.includes(notification.type);
+ });
+
+ // Add each enabled notification with its configured fields
+ activeNotificationTypes.forEach((type) => {
+ if (integrations[type.id]) {
+ let notificationObject = {
+ type: "webhook",
+ platform: type.id, // Set platform to identify the specific service
+ config: {},
+ };
+
+ // Configure based on notification type
+ switch (type.id) {
+ case "slack":
+ case "discord":
+ notificationObject.config.webhookUrl =
+ integrations[getFieldKey(type.id, "webhook")];
+ break;
+ case "telegram":
+ notificationObject.config.botToken =
+ integrations[getFieldKey(type.id, "token")];
+ notificationObject.config.chatId =
+ integrations[getFieldKey(type.id, "chatId")];
+ break;
+ case "webhook":
+ notificationObject.config.webhookUrl =
+ integrations[getFieldKey(type.id, "url")];
+ break;
+ }
+
+ filteredNotifications.push(notificationObject);
+ }
+ });
+
+ // Update monitor with new notifications
+ setMonitor((prev) => ({
+ ...prev,
+ notifications: filteredNotifications,
+ }));
+
+ onClose();
+ };
+
+ return (
+
+
+
+ {/* Left sidebar with tabs */}
+
+
+ {t("notifications.addOrEditNotifications")}
+
+
+
+ {activeNotificationTypes.map((type) => (
+
+ ))}
+
+
+
+ {/* Right side content */}
+
+ {activeNotificationTypes.map((type, index) => (
+
+
+
+ ))}
+
+
+
+
+
+ {t("commonSave")}
+
+
+
+ );
+};
+
+NotificationIntegrationModal.propTypes = {
+ open: PropTypes.bool.isRequired,
+ onClose: PropTypes.func.isRequired,
+ monitor: PropTypes.object.isRequired,
+ setMonitor: PropTypes.func.isRequired,
+ notificationTypes: PropTypes.array,
+};
+
+export default NotificationIntegrationModal;
diff --git a/client/src/Components/NotificationIntegrationModal/Components/TabComponent.jsx b/client/src/Components/NotificationIntegrationModal/Components/TabComponent.jsx
new file mode 100644
index 000000000..e46a8cdd5
--- /dev/null
+++ b/client/src/Components/NotificationIntegrationModal/Components/TabComponent.jsx
@@ -0,0 +1,109 @@
+import React from "react";
+import {
+ Typography,
+ Box,
+ Button,
+ CircularProgress
+} from "@mui/material";
+import { useTranslation } from "react-i18next";
+import { useTheme } from "@emotion/react";
+import TextInput from "../../../Components/Inputs/TextInput";
+import Checkbox from "../../../Components/Inputs/Checkbox";
+
+const TabComponent = ({
+ type,
+ integrations,
+ handleIntegrationChange,
+ handleInputChange,
+ handleTestNotification,
+ isLoading
+}) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+
+ // Helper to get the field state key (e.g., slackWebhook, telegramToken)
+ const getFieldKey = (typeId, fieldId) => {
+ return `${typeId}${fieldId.charAt(0).toUpperCase() + fieldId.slice(1)}`;
+ };
+
+ // Check if all fields have values to enable test button
+ const areAllFieldsFilled = () => {
+ return type.fields.every(field => {
+ const fieldKey = getFieldKey(type.id, field.id);
+ return integrations[fieldKey];
+ });
+ };
+
+ return (
+ <>
+
+ {type.label}
+
+
+
+ {type.description}
+
+
+
+ handleIntegrationChange(type.id, e.target.checked)}
+ disabled={isLoading}
+ />
+
+
+ {type.fields.map(field => {
+ const fieldKey = getFieldKey(type.id, field.id);
+
+ return (
+
+
+ {field.label}
+
+
+ handleInputChange(fieldKey, e.target.value)}
+ disabled={!integrations[type.id] || isLoading}
+ />
+
+ );
+ })}
+
+
+ handleTestNotification(type.id)}
+ disabled={!integrations[type.id] || !areAllFieldsFilled() || isLoading}
+ >
+ {isLoading ? (
+
+ ) : null}
+ {t('notifications.testNotification')}
+
+
+ >
+ );
+};
+
+export default TabComponent;
\ No newline at end of file
diff --git a/client/src/Components/NotificationIntegrationModal/Components/TabPanel.jsx b/client/src/Components/NotificationIntegrationModal/Components/TabPanel.jsx
new file mode 100644
index 000000000..a9252e710
--- /dev/null
+++ b/client/src/Components/NotificationIntegrationModal/Components/TabPanel.jsx
@@ -0,0 +1,46 @@
+import React from "react";
+import PropTypes from "prop-types";
+import { Box } from "@mui/material";
+import { useTheme } from "@emotion/react";
+
+/**
+ * TabPanel component that displays content for the selected tab.
+ *
+ * @component
+ * @param {Object} props - The component props.
+ * @param {React.ReactNode} props.children - The content to be displayed when this tab panel is selected.
+ * @param {number} props.value - The currently selected tab value.
+ * @param {number} props.index - The index of this specific tab panel.
+ * @param {Object} props.other - Any additional props to be spread to the root element.
+ * @returns {React.ReactElement|null} The rendered tab panel or null if not selected.
+ */
+function TabPanel({ children, value, index, ...other }) {
+ const theme = useTheme();
+
+ return (
+
+ {value === index && (
+
+ {children}
+
+ )}
+
+ );
+}
+
+TabPanel.propTypes = {
+
+ children: PropTypes.node,
+
+ index: PropTypes.number.isRequired,
+
+ value: PropTypes.number.isRequired
+};
+
+export default TabPanel;
\ No newline at end of file
diff --git a/client/src/Components/NotificationIntegrationModal/Hooks/useNotification.js b/client/src/Components/NotificationIntegrationModal/Hooks/useNotification.js
new file mode 100644
index 000000000..3547873e8
--- /dev/null
+++ b/client/src/Components/NotificationIntegrationModal/Hooks/useNotification.js
@@ -0,0 +1,128 @@
+import { useState } from 'react';
+import { useTranslation } from "react-i18next";
+import { networkService } from '../../../Utils/NetworkService';
+import { createToast } from '../../../Utils/toastUtils';
+
+// Define constants for notification types to avoid magic values
+const NOTIFICATION_TYPES = {
+ SLACK: 'slack',
+ DISCORD: 'discord',
+ TELEGRAM: 'telegram',
+ WEBHOOK: 'webhook'
+};
+
+// Define constants for field IDs
+const FIELD_IDS = {
+ WEBHOOK: 'webhook',
+ TOKEN: 'token',
+ CHAT_ID: 'chatId',
+ URL: 'url'
+};
+
+/**
+ * Custom hook for notification-related operations
+ */
+const useNotifications = () => {
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState(undefined);
+ const { t } = useTranslation();
+
+ /**
+ * Send a test notification
+ * @param {string} type - The notification type (slack, discord, telegram, webhook)
+ * @param {object} config - Configuration object with necessary params
+ */
+ const sendTestNotification = async (type, config) => {
+ setLoading(true);
+ setError(undefined);
+
+ // Validation based on notification type
+ let payload = { platform: type };
+ let isValid = true;
+ let errorMessage = '';
+
+ switch(type) {
+ case NOTIFICATION_TYPES.SLACK:
+ payload.webhookUrl = config.webhook;
+ if (typeof payload.webhookUrl === 'undefined' || payload.webhookUrl === '') {
+ isValid = false;
+ errorMessage = t('notifications.slack.webhookRequired');
+ }
+ break;
+
+ case NOTIFICATION_TYPES.DISCORD:
+ payload.webhookUrl = config.webhook;
+ if (typeof payload.webhookUrl === 'undefined' || payload.webhookUrl === '') {
+ isValid = false;
+ errorMessage = t('notifications.discord.webhookRequired');
+ }
+ break;
+
+ case NOTIFICATION_TYPES.TELEGRAM:
+ payload.botToken = config.token;
+ payload.chatId = config.chatId;
+ if (typeof payload.botToken === 'undefined' || payload.botToken === '' ||
+ typeof payload.chatId === 'undefined' || payload.chatId === '') {
+ isValid = false;
+ errorMessage = t('notifications.telegram.fieldsRequired');
+ }
+ break;
+
+ case NOTIFICATION_TYPES.WEBHOOK:
+ payload.webhookUrl = config.url;
+ payload.platform = NOTIFICATION_TYPES.SLACK;
+ if (typeof payload.webhookUrl === 'undefined' || payload.webhookUrl === '') {
+ isValid = false;
+ errorMessage = t('notifications.webhook.urlRequired');
+ }
+ break;
+
+ default:
+ isValid = false;
+ errorMessage = t('notifications.unsupportedType');
+ }
+
+ // If validation fails, show error and return
+ if (isValid === false) {
+ createToast({
+ body: errorMessage,
+ variant: "error"
+ });
+ setLoading(false);
+ return;
+ }
+
+ try {
+ const response = await networkService.testNotification({
+ platform: type,
+ payload: payload
+ });
+
+ if (response.data.success === true) {
+ createToast({
+ body: t('notifications.testSuccess'),
+ variant: "info"
+ });
+ } else {
+ throw new Error(response.data.msg || t('notifications.testFailed'));
+ }
+ } catch (error) {
+ const errorMsg = error.response?.data?.msg || error.message || t('notifications.networkError');
+ createToast({
+ body: `${t('notifications.testFailed')}: ${errorMsg}`,
+ variant: "error"
+ });
+ setError(errorMsg);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return [
+ loading,
+ error,
+ sendTestNotification
+ ];
+};
+
+export default useNotifications;
\ No newline at end of file
diff --git a/Client/src/Components/ProgressBars/index.css b/client/src/Components/ProgressBars/index.css
similarity index 100%
rename from Client/src/Components/ProgressBars/index.css
rename to client/src/Components/ProgressBars/index.css
diff --git a/Client/src/Components/ProgressBars/index.jsx b/client/src/Components/ProgressBars/index.jsx
similarity index 97%
rename from Client/src/Components/ProgressBars/index.jsx
rename to client/src/Components/ProgressBars/index.jsx
index abb896844..4f5515d3a 100644
--- a/Client/src/Components/ProgressBars/index.jsx
+++ b/client/src/Components/ProgressBars/index.jsx
@@ -93,6 +93,7 @@ const ProgressUpload = ({ icon, label, size, progress = 0, onClick, error }) =>
{error ? error : label}
@@ -168,7 +169,7 @@ const ProgressUpload = ({ icon, label, size, progress = 0, onClick, error }) =>
ProgressUpload.propTypes = {
icon: PropTypes.element, // JSX element for the icon (optional)
- label: PropTypes.string.isRequired, // Label text for the progress item
+ label: PropTypes.string, // Label text for the progress item
size: PropTypes.string.isRequired, // Size information for the progress item
progress: PropTypes.number.isRequired, // Current progress value (0-100)
onClick: PropTypes.func.isRequired, // Function to handle click events on the remove button
diff --git a/Client/src/Components/ProgressStepper/index.css b/client/src/Components/ProgressStepper/index.css
similarity index 100%
rename from Client/src/Components/ProgressStepper/index.css
rename to client/src/Components/ProgressStepper/index.css
diff --git a/Client/src/Components/ProgressStepper/index.jsx b/client/src/Components/ProgressStepper/index.jsx
similarity index 100%
rename from Client/src/Components/ProgressStepper/index.jsx
rename to client/src/Components/ProgressStepper/index.jsx
diff --git a/client/src/Components/ProtectedDistributedUptimeRoute/index.jsx b/client/src/Components/ProtectedDistributedUptimeRoute/index.jsx
new file mode 100644
index 000000000..4a59859fe
--- /dev/null
+++ b/client/src/Components/ProtectedDistributedUptimeRoute/index.jsx
@@ -0,0 +1,30 @@
+import { Navigate } from "react-router-dom";
+import { useSelector } from "react-redux";
+import PropTypes from "prop-types";
+
+/**
+ * @param {Object} props - The props passed to the ProtectedDistributedUptimeRoute component.
+ * @param {React.ReactNode} props.children - The children to render if the user is authenticated.
+ * @returns {React.ReactElement} The children wrapped in a protected route or a redirect to the login page.
+ */
+
+const ProtectedDistributedUptimeRoute = ({ children }) => {
+ const distributedUptimeEnabled = useSelector(
+ (state) => state.ui.distributedUptimeEnabled
+ );
+
+ return distributedUptimeEnabled === true ? (
+ children
+ ) : (
+
+ );
+};
+
+ProtectedDistributedUptimeRoute.propTypes = {
+ children: PropTypes.node.isRequired,
+};
+
+export default ProtectedDistributedUptimeRoute;
diff --git a/Client/src/Components/ProtectedRoute/index.jsx b/client/src/Components/ProtectedRoute/index.jsx
similarity index 100%
rename from Client/src/Components/ProtectedRoute/index.jsx
rename to client/src/Components/ProtectedRoute/index.jsx
diff --git a/client/src/Components/ShareComponent/index.jsx b/client/src/Components/ShareComponent/index.jsx
new file mode 100644
index 000000000..073ed2243
--- /dev/null
+++ b/client/src/Components/ShareComponent/index.jsx
@@ -0,0 +1,67 @@
+import html2canvas from "html2canvas";
+import ShareIcon from "@mui/icons-material/Share";
+import { Button } from "@mui/material";
+import { useTheme } from "@emotion/react";
+
+const ShareComponent = ({ elementToCapture, fileName = "screenshot" }) => {
+ const theme = useTheme();
+ const captureAndShare = async () => {
+ try {
+ // Temporarily apply styles directly to the element
+ const originalBackground = elementToCapture.current.style.background;
+ const originalPadding = elementToCapture.current.style.padding;
+
+ elementToCapture.current.style.background = `radial-gradient(circle, ${theme.palette.gradient.color1}, ${theme.palette.gradient.color2}, ${theme.palette.gradient.color3}, ${theme.palette.gradient.color4}, ${theme.palette.gradient.color5})`;
+ elementToCapture.current.style.padding = `${theme.spacing(20)}`;
+
+ // Capture the element directly
+ const canvas = await html2canvas(elementToCapture.current, {
+ useCORS: true,
+ scale: 2,
+ allowTaint: true,
+ backgroundColor: null,
+ });
+
+ // Restore original styles
+ elementToCapture.current.style.background = originalBackground;
+ elementToCapture.current.style.padding = originalPadding;
+
+ const imageBlob = await new Promise((resolve) =>
+ canvas.toBlob(resolve, "image/png")
+ );
+
+ const file = new File([imageBlob], `${fileName}.png`, {
+ type: "image/png",
+ });
+
+ if (navigator.share) {
+ await navigator.share({
+ files: [file],
+ title: "Screenshot",
+ text: "Check out this screenshot!",
+ });
+ } else {
+ const url = URL.createObjectURL(imageBlob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `${fileName}.png`;
+ a.click();
+ URL.revokeObjectURL(url);
+ }
+ } catch (error) {
+ console.error(error);
+ }
+ };
+ return (
+ }
+ color="success"
+ onClick={captureAndShare}
+ >
+ Share
+
+ );
+};
+
+export default ShareComponent;
diff --git a/Client/src/Components/Sidebar/index.css b/client/src/Components/Sidebar/index.css
similarity index 91%
rename from Client/src/Components/Sidebar/index.css
rename to client/src/Components/Sidebar/index.css
index 58805c7f8..ef921acca 100644
--- a/Client/src/Components/Sidebar/index.css
+++ b/client/src/Components/Sidebar/index.css
@@ -79,6 +79,17 @@ aside .MuiListSubheader-root {
transition: padding 200ms ease;
}
+.sidebar-delay-fade {
+ opacity: 0;
+ visibility: hidden;
+ transition: opacity 0.3s ease;
+}
+
+aside.expanded.sidebar-ready .sidebar-delay-fade {
+ opacity: 1;
+ visibility: visible;
+}
+
@keyframes fadeIn {
0% {
opacity: 0;
diff --git a/Client/src/Components/Sidebar/index.jsx b/client/src/Components/Sidebar/index.jsx
similarity index 52%
rename from Client/src/Components/Sidebar/index.jsx
rename to client/src/Components/Sidebar/index.jsx
index 3821306ad..b0f99cd2f 100644
--- a/Client/src/Components/Sidebar/index.jsx
+++ b/client/src/Components/Sidebar/index.jsx
@@ -1,4 +1,4 @@
-import React, { useEffect, useState } from "react";
+import React, { useEffect, useState, useRef } from "react";
import {
Box,
Collapse,
@@ -15,14 +15,9 @@ import {
Tooltip,
Typography,
} from "@mui/material";
-import { useLocation, useNavigate } from "react-router";
-import { useTheme } from "@emotion/react";
-import { useDispatch, useSelector } from "react-redux";
-import { clearAuthState } from "../../Features/Auth/authSlice";
-import { toggleSidebar } from "../../Features/UI/uiSlice";
-import { clearUptimeMonitorState } from "../../Features/UptimeMonitors/uptimeMonitorsSlice";
import ThemeSwitch from "../ThemeSwitch";
import Avatar from "../Avatar";
+import StarPrompt from "../StarPrompt";
import LockSvg from "../../assets/icons/lock.svg?react";
import UserSvg from "../../assets/icons/user.svg?react";
import TeamSvg from "../../assets/icons/user-two.svg?react";
@@ -43,46 +38,56 @@ import DotsVertical from "../../assets/icons/dots-vertical.svg?react";
import ChangeLog from "../../assets/icons/changeLog.svg?react";
import Docs from "../../assets/icons/docs.svg?react";
import Folder from "../../assets/icons/folder.svg?react";
-import ChatBubbleOutlineRoundedIcon from "@mui/icons-material/ChatBubbleOutlineRounded";
-
+import StatusPages from "../../assets/icons/status-pages.svg?react";
+import Discussions from "../../assets/icons/discussions.svg?react";
+import DistributedUptimeIcon from "../../assets/icons/distributed-uptime.svg?react";
import "./index.css";
-const menu = [
- { name: "Uptime", path: "uptime", icon: },
- { name: "Pagespeed", path: "pagespeed", icon: },
- { name: "Infrastructure", path: "infrastructure", icon: },
- { name: "Incidents", path: "incidents", icon: },
- // { name: "Status pages", path: "status", icon: },
- { name: "Maintenance", path: "maintenance", icon: },
- // { name: "Integrations", path: "integrations", icon: },
+// Utils
+import { useLocation, useNavigate } from "react-router";
+import { useTheme } from "@emotion/react";
+import { useDispatch, useSelector } from "react-redux";
+import { useTranslation } from "react-i18next";
+import { clearAuthState } from "../../Features/Auth/authSlice";
+import { toggleSidebar } from "../../Features/UI/uiSlice";
+import { clearUptimeMonitorState } from "../../Features/UptimeMonitors/uptimeMonitorsSlice";
+
+const getMenu = (t) => [
+ { name: t("menu.uptime"), path: "uptime", icon: },
+ { name: t("menu.pagespeed"), path: "pagespeed", icon: },
+ { name: t("menu.infrastructure"), path: "infrastructure", icon: },
{
- name: "Account",
- icon: ,
- nested: [
- { name: "Profile", path: "account/profile", icon: },
- { name: "Password", path: "account/password", icon: },
- { name: "Team", path: "account/team", icon: },
- ],
+ name: t("menu.distributedUptime"),
+ path: "distributed-uptime",
+ icon: ,
},
+ { name: t("menu.incidents"), path: "incidents", icon: },
+
+ { name: t("menu.statusPages"), path: "status", icon: },
+ { name: t("menu.maintenance"), path: "maintenance", icon: },
+ // { name: t("menu.integrations"), path: "integrations", icon: },
{
- name: "Settings",
+ name: t("menu.settings"),
icon: ,
path: "settings",
},
+];
+
+const getOtherMenuItems = (t) => [
+ { name: t("menu.support"), path: "support", icon: },
{
- name: "Other",
- icon: ,
- nested: [
- { name: "Support", path: "support", icon: },
- {
- name: "Discussions",
- path: "discussions",
- icon: ,
- },
- { name: "Docs", path: "docs", icon: },
- { name: "Changelog", path: "changelog", icon: },
- ],
+ name: t("menu.discussions"),
+ path: "discussions",
+ icon: ,
},
+ { name: t("menu.docs"), path: "docs", icon: },
+ { name: t("menu.changelog"), path: "changelog", icon: },
+];
+
+const getAccountMenuItems = (t) => [
+ { name: t("menu.profile"), path: "account/profile", icon: },
+ { name: t("menu.password"), path: "account/password", icon: },
+ { name: t("menu.team"), path: "account/team", icon: },
];
/* TODO this could be a key in nested Path would be the link */
@@ -97,6 +102,7 @@ const PATH_MAP = {
monitors: "Dashboard",
pagespeed: "Dashboard",
infrastructure: "Dashboard",
+ ["distributed-uptime"]: "Dashboard",
account: "Account",
settings: "Settings",
};
@@ -113,19 +119,71 @@ function Sidebar() {
const navigate = useNavigate();
const location = useLocation();
const dispatch = useDispatch();
+ const { t } = useTranslation();
const authState = useSelector((state) => state.auth);
+
+ const menu = getMenu(t);
+ const otherMenuItems = getOtherMenuItems(t);
+ const accountMenuItems = getAccountMenuItems(t);
const collapsed = useSelector((state) => state.ui.sidebar.collapsed);
const [open, setOpen] = useState({ Dashboard: false, Account: false, Other: false });
const [anchorEl, setAnchorEl] = useState(null);
const [popup, setPopup] = useState();
const { user } = useSelector((state) => state.auth);
+ const distributedUptimeEnabled = useSelector(
+ (state) => state.ui.distributedUptimeEnabled
+ );
+ const sidebarRef = useRef(null);
+ const [sidebarReady, setSidebarReady] = useState(false);
+ const TRANSITION_DURATION = 200;
- const accountMenuItem = menu.find((item) => item.name === "Account");
- if (user.role?.includes("demo") && accountMenuItem) {
- accountMenuItem.nested = accountMenuItem.nested.filter((item) => {
- return item.name !== "Password";
- });
- }
+ useEffect(() => {
+ if (!collapsed) {
+ setSidebarReady(false);
+ const timeout = setTimeout(() => {
+ setSidebarReady(true);
+ }, TRANSITION_DURATION);
+ return () => clearTimeout(timeout);
+ } else {
+ setSidebarReady(false);
+ }
+ }, [collapsed]);
+
+ const renderAccountMenuItems = () => {
+ let filteredAccountMenuItems = [...accountMenuItems];
+
+ // If the user is in demo mode, remove the "Password" option
+ if (user.role?.includes("demo")) {
+ filteredAccountMenuItems = filteredAccountMenuItems.filter(
+ (item) => item.name !== "Password"
+ );
+ }
+
+ // If the user is NOT a superadmin, remove the "Team" option
+ if (user.role && !user.role.includes("superadmin")) {
+ filteredAccountMenuItems = filteredAccountMenuItems.filter(
+ (item) => item.name !== "Team"
+ );
+ }
+
+ return filteredAccountMenuItems.map((item) => (
+ {
+ closePopup()
+ navigate(item.path)
+ }}
+ sx={{
+ gap: theme.spacing(2),
+ borderRadius: theme.shape.borderRadius,
+ pl: theme.spacing(4),
+ }}
+ >
+ {item.icon}
+ {item.name}
+
+ ));
+ };
const openPopup = (event, id) => {
setAnchorEl(event.currentTarget);
@@ -157,12 +215,14 @@ function Sidebar() {
}, [location]);
const iconColor = theme.palette.primary.contrastTextTertiary;
+ const sidebarClassName = `${collapsed ? "collapsed" : "expanded"} ${sidebarReady ? "sidebar-ready" : ""}`;
/* TODO refactor this, there are a some ternaries and comments in the return */
return (
{collapsed ? : }
-
{/* TODO Alignment done using padding. Use single source of truth to that*/}
-
{
component="h1"
width="20ch"
>
- New password
+ {t("passwordPanel.newPassword", "New password")}
{
component="h1"
width="20ch"
>
- Confirm new password
+ {t("passwordPanel.confirmNewPassword", "Confirm new password")}
{
)}
@@ -226,12 +227,12 @@ const PasswordPanel = () => {
direction="row"
justifyContent="flex-end"
>
- 0 ||
Object.values(localData).filter((value) => value === "").length > 0
@@ -241,8 +242,8 @@ const PasswordPanel = () => {
mt: theme.spacing(20),
}}
>
- Save
-
+ {t("commonSave", "Save")}
+
diff --git a/Client/src/Components/TabPanels/Account/ProfilePanel.jsx b/client/src/Components/TabPanels/Account/ProfilePanel.jsx
similarity index 68%
rename from Client/src/Components/TabPanels/Account/ProfilePanel.jsx
rename to client/src/Components/TabPanels/Account/ProfilePanel.jsx
index e20cb13a4..bdf52de3a 100644
--- a/Client/src/Components/TabPanels/Account/ProfilePanel.jsx
+++ b/client/src/Components/TabPanels/Account/ProfilePanel.jsx
@@ -1,22 +1,19 @@
import { useTheme } from "@emotion/react";
-import { useRef, useState } from "react";
+import { useState } from "react";
import TabPanel from "@mui/lab/TabPanel";
import { Box, Button, Divider, Stack, Typography } from "@mui/material";
import Avatar from "../../Avatar";
import TextInput from "../../Inputs/TextInput";
-import ImageField from "../../Inputs/Image";
-import { credentials, imageValidation } from "../../../Validation/validation";
+import ImageUpload from "../../Inputs/ImageUpload";
+import { credentials } from "../../../Validation/validation";
import { useDispatch, useSelector } from "react-redux";
import { clearAuthState, deleteUser, update } from "../../../Features/Auth/authSlice";
-import ImageIcon from "@mui/icons-material/Image";
-import ProgressUpload from "../../ProgressBars";
-import { formatBytes } from "../../../Utils/fileUtils";
import { clearUptimeMonitorState } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
import { createToast } from "../../../Utils/toastUtils";
import { logger } from "../../../Utils/Logger";
-import LoadingButton from "@mui/lab/LoadingButton";
import { GenericDialog } from "../../Dialog/genericDialog";
import Dialog from "../../Dialog";
+import { useTranslation } from "react-i18next";
/**
* ProfilePanel component displays a form for editing user profile information
@@ -29,11 +26,11 @@ import Dialog from "../../Dialog";
const ProfilePanel = () => {
const theme = useTheme();
const dispatch = useDispatch();
-
+ const { t } = useTranslation();
const SPACING_GAP = theme.spacing(12);
//redux state
- const { user, authToken, isLoading } = useSelector((state) => state.auth);
+ const { user, isLoading } = useSelector((state) => state.auth);
const idToName = {
"edit-first-name": "firstName",
@@ -50,8 +47,6 @@ const ProfilePanel = () => {
});
const [errors, setErrors] = useState({});
const [file, setFile] = useState();
- const intervalRef = useRef(null);
- const [progress, setProgress] = useState({ value: 0, isLoading: false });
// Handles input field changes and performs validation
const handleChange = (event) => {
@@ -66,33 +61,6 @@ const ProfilePanel = () => {
validateField({ [name]: value }, credentials, name);
};
- // Handles image file
- const handlePicture = (event) => {
- const pic = event.target.files[0];
- let error = validateField({ type: pic.type, size: pic.size }, imageValidation);
- if (error) return;
-
- setProgress((prev) => ({ ...prev, isLoading: true }));
- setFile({
- src: URL.createObjectURL(pic),
- name: pic.name,
- size: formatBytes(pic.size),
- delete: false,
- });
-
- //TODO - potentitally remove, will revisit in the future
- intervalRef.current = setInterval(() => {
- const buffer = 12;
- setProgress((prev) => {
- if (prev.value + buffer >= 100) {
- clearInterval(intervalRef.current);
- return { value: 100, isLoading: false };
- }
- return { ...prev, value: prev.value + buffer };
- });
- }, 120);
- };
-
// Validates input against provided schema and updates error state
const validateField = (toValidate, schema, name = "picture") => {
const { error } = schema.validate(toValidate, { abortEarly: false });
@@ -117,55 +85,58 @@ const ProfilePanel = () => {
// Resets picture-related states and clears interval
const removePicture = () => {
errors["picture"] && clearError("picture");
- setFile({ delete: true });
- clearInterval(intervalRef.current); // interrupt interval if image upload is canceled prior to completing the process
- setProgress({ value: 0, isLoading: false });
- };
+ setFile(undefined);
+ setLocalData((prev) => ({
+ ...prev,
+ file: undefined,
+ deleteProfileImage: true,
+ }));
+ };
// Opens the picture update modal
const openPictureModal = () => {
setIsOpen("picture");
- setFile({ delete: localData.deleteProfileImage });
+ setFile(undefined);
};
// Closes the picture update modal and resets related states
const closePictureModal = () => {
- errors["picture"] && clearError("picture");
- setFile(); //reset file
- clearInterval(intervalRef.current); // interrupt interval if image upload is canceled prior to completing the process
- setProgress({ value: 0, isLoading: false });
- setIsOpen("");
- };
+ if (errors["picture"]) clearError("picture");
+ setFile(undefined);
+ setIsOpen("");
+ };
// Updates profile image displayed on UI
const handleUpdatePicture = () => {
- setProgress({ value: 0, isLoading: false });
setLocalData((prev) => ({
...prev,
- file: file.src,
+ file: file?.src,
deleteProfileImage: false,
}));
setIsOpen("");
- errors["unchanged"] && clearError("unchanged");
+ if (errors["unchanged"]) clearError("unchanged");
};
-
+
// Handles form submission to update user profile
const handleSaveProfile = async (event) => {
event.preventDefault();
- if (
- localData.firstName === user.firstName &&
- localData.lastName === user.lastName &&
- localData.deleteProfileImage === undefined &&
- localData.file === undefined
- ) {
- createToast({
- body: "Unable to update profile — no changes detected.",
- });
- setErrors({ unchanged: "unable to update profile" });
- return;
+ const nameChanged =
+ localData.firstName !== user.firstName ||
+ localData.lastName !== user.lastName;
+
+ const avatarChanged =
+ localData.deleteProfileImage === true ||
+ (localData.file && localData.file !== `data:image/png;base64,${user.avatarImage}`);
+
+ if (!nameChanged && !avatarChanged) {
+ createToast({
+ body: "Unable to update profile — no changes detected.",
+ });
+ setErrors({ unchanged: "unable to update profile" });
+ return;
}
- const action = await dispatch(update({ authToken, localData }));
+ const action = await dispatch(update({ localData }));
if (action.payload.success) {
createToast({
body: "Your profile data was changed successfully.",
@@ -183,12 +154,13 @@ const ProfilePanel = () => {
...prev,
deleteProfileImage: true,
}));
+ setFile(undefined);
errors["unchanged"] && clearError("unchanged");
};
// Initiates the account deletion process
const handleDeleteAccount = async () => {
- const action = await dispatch(deleteUser(authToken));
+ const action = await dispatch(deleteUser());
if (action.payload.success) {
dispatch(clearAuthState());
dispatch(clearUptimeMonitorState());
@@ -233,7 +205,7 @@ const ProfilePanel = () => {
>
{/* This 0.9 is a bit magic numbering, refactor */}
- First name
+ {t('FirstName')}
{
gap={SPACING_GAP}
>
- Last name
+ {t('LastName')}
{
gap={SPACING_GAP}
>
- Email
+ {t('email')}
- This is your current email address — it cannot be changed.
+ {t('EmailDescriptionText')}
{
gap={SPACING_GAP}
>
- Your photo
+ {t('YourPhoto')}
- This photo will be displayed in your profile page.
+ {t('PhotoDescriptionText')}
{
color="error"
onClick={handleDeletePicture}
>
- Delete
+ {t('delete')}
- Update
+ {t('update')}
@@ -344,7 +316,7 @@ const ProfilePanel = () => {
justifyContent="flex-end"
>
- {
disabled={Object.keys(errors).length !== 0 && !errors?.picture && true}
sx={{ px: theme.spacing(12) }}
>
- Save
-
+ {t('save')}
+
@@ -372,13 +344,12 @@ const ProfilePanel = () => {
spellCheck="false"
>
- Delete account
+ {t('DeleteAccountTitle')}
- Note that deleting your account will remove all data from the server. This
- is permanent and non-recoverable.
+ {t('DeleteDescriptionText')}
{
color="error"
onClick={() => setIsOpen("delete")}
>
- Delete account
+ {t('DeleteAccountButton')}
)}
setIsOpen("")}
- confirmationButtonLabel={"Delete account"}
+ confirmationButtonLabel={t('DeleteAccountButton')}
onConfirm={handleDeleteAccount}
isLoading={isLoading}
/>
@@ -409,34 +378,27 @@ const ProfilePanel = () => {
onClose={closePictureModal}
theme={theme}
>
- {
+ if (newFile) {
+ setFile(newFile);
+ clearError("unchanged");
+ }
+ }}
+ previewIsRound
+ maxSize={3 * 1024 * 1024}
/>
- {progress.isLoading || progress.value !== 0 || errors["picture"] ? (
- }
- label={file?.name}
- size={file?.size}
- progress={progress.value}
- onClick={removePicture}
- error={errors["picture"]}
- />
- ) : (
- ""
- )}
{
color="info"
onClick={removePicture}
>
- Remove
+ {t('remove')}
- Update
+ {t('update')}
diff --git a/Client/src/Components/TabPanels/Account/TeamPanel.jsx b/client/src/Components/TabPanels/Account/TeamPanel.jsx
similarity index 75%
rename from Client/src/Components/TabPanels/Account/TeamPanel.jsx
rename to client/src/Components/TabPanels/Account/TeamPanel.jsx
index 7b8143356..fe4b201dd 100644
--- a/Client/src/Components/TabPanels/Account/TeamPanel.jsx
+++ b/client/src/Components/TabPanels/Account/TeamPanel.jsx
@@ -2,15 +2,15 @@ import { useTheme } from "@emotion/react";
import TabPanel from "@mui/lab/TabPanel";
import { Button, ButtonGroup, Stack, Typography } from "@mui/material";
import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
import TextInput from "../../Inputs/TextInput";
import { credentials } from "../../../Validation/validation";
import { networkService } from "../../../main";
import { createToast } from "../../../Utils/toastUtils";
-import { useSelector } from "react-redux";
import Select from "../../Inputs/Select";
-import LoadingButton from "@mui/lab/LoadingButton";
import { GenericDialog } from "../../Dialog/genericDialog";
import DataTable from "../../Table/";
+import { useGetInviteToken } from "../../../Hooks/inviteHooks";
/**
* TeamPanel component manages the organization and team members,
* providing functionalities like renaming the organization, managing team members,
@@ -21,13 +21,12 @@ import DataTable from "../../Table/";
const TeamPanel = () => {
const theme = useTheme();
-
+ const { t } = useTranslation();
const SPACING_GAP = theme.spacing(12);
- const { authToken } = useSelector((state) => state.auth);
const [toInvite, setToInvite] = useState({
email: "",
- role: ["0"],
+ role: ["user"],
});
const [data, setData] = useState([]);
const [members, setMembers] = useState([]);
@@ -36,10 +35,12 @@ const TeamPanel = () => {
const [errors, setErrors] = useState({});
const [isSendingInvite, setIsSendingInvite] = useState(false);
+ const [getInviteToken, clearToken, isLoading, error, token] = useGetInviteToken();
+
const headers = [
{
id: "name",
- content: "Name",
+ content: t("teamPanel.table.name"),
render: (row) => {
return (
@@ -47,16 +48,16 @@ const TeamPanel = () => {
{row.firstName + " " + row.lastName}
- Created {new Date(row.createdAt).toLocaleDateString()}
+ {t("teamPanel.table.created")} {new Date(row.createdAt).toLocaleDateString()}
);
},
},
- { id: "email", content: "Email", render: (row) => row.email },
+ { id: "email", content: t("teamPanel.table.email"), render: (row) => row.email },
{
id: "role",
- content: "Role",
+ content: t("teamPanel.table.role"),
render: (row) => row.role,
},
];
@@ -64,9 +65,7 @@ const TeamPanel = () => {
useEffect(() => {
const fetchTeam = async () => {
try {
- const response = await networkService.getAllUsers({
- authToken: authToken,
- });
+ const response = await networkService.getAllUsers();
setMembers(response.data.data);
} catch (error) {
createToast({
@@ -76,14 +75,14 @@ const TeamPanel = () => {
};
fetchTeam();
- }, [authToken]);
+ }, []);
useEffect(() => {
const ROLE_MAP = {
- superadmin: "Super admin",
- admin: "Admin",
- user: "Team member",
- demo: "Demo User",
+ superadmin: t("roles.superAdmin"),
+ admin: t("roles.admin"),
+ user: t("roles.teamMember"),
+ demo: t("roles.demoUser"),
};
let team = members;
if (filter !== "all")
@@ -100,7 +99,7 @@ const TeamPanel = () => {
role: member.role.map((role) => ROLE_MAP[role]).join(","),
}));
setData(team);
- }, [filter, members]);
+ }, [members, filter, t]);
useEffect(() => {
setIsDisabled(Object.keys(errors).length !== 0 || toInvite.email === "");
@@ -109,12 +108,13 @@ const TeamPanel = () => {
const handleChange = (event) => {
const { value } = event.target;
+ const newEmail = value?.toLowerCase() || value;
setToInvite((prev) => ({
...prev,
- email: value,
+ email: newEmail,
}));
- const validation = credentials.validate({ email: value }, { abortEarly: false });
+ const validation = credentials.validate({ email: newEmail }, { abortEarly: false });
setErrors((prev) => {
const updatedErrors = { ...prev };
@@ -128,6 +128,10 @@ const TeamPanel = () => {
});
};
+ const handleGetToken = async () => {
+ await getInviteToken({ email: toInvite.email, role: toInvite.role });
+ };
+
const handleInviteMember = async () => {
if (!toInvite.email) {
setErrors((prev) => ({ ...prev, email: "Email is required." }));
@@ -150,8 +154,7 @@ const TeamPanel = () => {
}
try {
- await networkService.requestInvitationToken({
- authToken: authToken,
+ await networkService.sendInvitationToken({
email: toInvite.email,
role: toInvite.role,
});
@@ -170,6 +173,7 @@ const TeamPanel = () => {
const closeInviteModal = () => {
setIsOpen(false);
+ clearToken();
setToInvite({ email: "", role: ["0"] });
setErrors({});
};
@@ -194,7 +198,7 @@ const TeamPanel = () => {
spellCheck="false"
gap={SPACING_GAP}
>
- Team members
+ {t("teamPanel.teamMembers")}
{
filled={(filter === "all").toString()}
onClick={() => setFilter("all")}
>
- All
+ {t("teamPanel.filter.all")}
setFilter("admin")}
>
- Super admin
+ {t("roles.superAdmin")}
setFilter("user")}
>
- Member
+ {t("teamPanel.filter.member")}
- setIsOpen(true)}
>
- Invite a team member
-
+ {t("teamPanel.inviteTeamMember")}
+
{
marginBottom={SPACING_GAP}
type="email"
id="input-team-member"
- placeholder="Email"
+ placeholder={t("teamPanel.email")}
value={toInvite.email}
onChange={handleChange}
error={errors.email ? true : false}
@@ -267,7 +268,7 @@ const TeamPanel = () => {
/>
@@ -277,33 +278,49 @@ const TeamPanel = () => {
}))
}
items={[
- { _id: "admin", name: "Admin" },
- { _id: "user", name: "User" },
+ { _id: "admin", name: t("roles.admin") },
+ { _id: "user", name: t("roles.teamMember") },
]}
/>
+ {token && {t("teamPanel.inviteLink")} }
+ {token && (
+
+ )}
-
- Cancel
-
-
+
+ {t("teamPanel.getToken")}
+
+
- Send invite
-
+ {t("teamPanel.emailToken")}
+
diff --git a/Client/src/Components/Table/TablePagination/Actions/index.jsx b/client/src/Components/Table/TablePagination/Actions/index.jsx
similarity index 93%
rename from Client/src/Components/Table/TablePagination/Actions/index.jsx
rename to client/src/Components/Table/TablePagination/Actions/index.jsx
index c607fcb8b..1b654fe9b 100644
--- a/Client/src/Components/Table/TablePagination/Actions/index.jsx
+++ b/client/src/Components/Table/TablePagination/Actions/index.jsx
@@ -4,6 +4,7 @@ import LeftArrowDouble from "../../../../assets/icons/left-arrow-double.svg?reac
import RightArrowDouble from "../../../../assets/icons/right-arrow-double.svg?react";
import LeftArrow from "../../../../assets/icons/left-arrow.svg?react";
import RightArrow from "../../../../assets/icons/right-arrow.svg?react";
+import { useTheme } from "@emotion/react";
TablePaginationActions.propTypes = {
count: PropTypes.number.isRequired,
@@ -39,8 +40,10 @@ function TablePaginationActions({ count, page, rowsPerPage, onPageChange }) {
onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1));
};
+ const theme = useTheme();
+
return (
-
+
{
+ return Math.ceil(itemCount / rowsPerPage) > 1;
+};
+
+// Empty action component for pagination (no-op component)
+const EmptyPaginationActions = () =>
;
+
/**
* Pagination component for table navigation with customized styling and behavior.
*
@@ -28,9 +37,9 @@ const ROWS_PER_PAGE_OPTIONS = [5, 10, 15, 25];
*/
function Pagination({
paginationLabel,
- itemCount,
- page,
- rowsPerPage,
+ itemCount = 0,
+ page = 0,
+ rowsPerPage = 5,
handleChangePage,
handleChangeRowsPerPage,
}) {
@@ -40,6 +49,8 @@ function Pagination({
const end = Math.min(page * rowsPerPage + rowsPerPage, itemCount);
const range = `${start} - ${end}`;
+ const showPaginationButtons = shouldShowPaginationButtons(itemCount, rowsPerPage);
+
return (
`Page ${page + 1} of ${Math.max(0, Math.ceil(count / rowsPerPage))}`
diff --git a/Client/src/Components/Table/index.jsx b/client/src/Components/Table/index.jsx
similarity index 81%
rename from Client/src/Components/Table/index.jsx
rename to client/src/Components/Table/index.jsx
index 7a7048ab8..b6d31bebe 100644
--- a/Client/src/Components/Table/index.jsx
+++ b/client/src/Components/Table/index.jsx
@@ -7,6 +7,7 @@ import {
TableHead,
TableRow,
} from "@mui/material";
+import SkeletonLayout from "./skeleton";
import PropTypes from "prop-types";
import { useTheme } from "@emotion/react";
@@ -14,6 +15,8 @@ import { useTheme } from "@emotion/react";
* @typedef {Object} Header
* @property {number|string} id - The unique identifier for the header.
* @property {React.ReactNode} content - The content to display in the header cell.
+ * @property {Function} onClick - A function to be called when this cell is clicked, receiving the event and row data as an argument.
+ * @property {Object} getCellSx - Function that takes a row and returns a style object for the table cell.
* @property {Function} render - A function to render the cell content for a given row.
*/
@@ -32,8 +35,20 @@ import { useTheme } from "@emotion/react";
* @returns {JSX.Element} The rendered table component.
*/
-const DataTable = ({ headers, data, config = { emptyView: "No data" } }) => {
+const DataTable = ({
+ shouldRender = true,
+ headers = [],
+ data = [],
+ config = {
+ emptyView: "No data",
+ onRowClick: () => {},
+ },
+}) => {
const theme = useTheme();
+ if (!shouldRender) {
+ return ;
+ }
+
if ((headers?.length ?? 0) === 0) {
return "No data";
}
@@ -50,7 +65,6 @@ const DataTable = ({ headers, data, config = { emptyView: "No data" } }) => {
backgroundColor: theme.palette.secondary.main,
color: theme.palette.secondary.contrastText,
fontWeight: 600,
- fontSize: "12px",
},
"& :is(td)": {
backgroundColor: theme.palette.primary.main,
@@ -94,6 +108,8 @@ const DataTable = ({ headers, data, config = { emptyView: "No data" } }) => {
header.onClick(e, row) : null}
+ sx={header.getCellSx ? header.getCellSx(row) : {}}
>
{header.render(row)}
@@ -110,6 +126,7 @@ const DataTable = ({ headers, data, config = { emptyView: "No data" } }) => {
};
DataTable.propTypes = {
+ shouldRender: PropTypes.bool,
headers: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
@@ -117,9 +134,9 @@ DataTable.propTypes = {
render: PropTypes.func.isRequired,
})
).isRequired,
- data: PropTypes.array.isRequired,
+ data: PropTypes.array,
config: PropTypes.shape({
- onRowClick: PropTypes.func.isRequired,
+ onRowClick: PropTypes.func,
rowSX: PropTypes.object,
emptyView: PropTypes.node,
}),
diff --git a/client/src/Components/Table/skeleton.jsx b/client/src/Components/Table/skeleton.jsx
new file mode 100644
index 000000000..062d39156
--- /dev/null
+++ b/client/src/Components/Table/skeleton.jsx
@@ -0,0 +1,14 @@
+import { Skeleton } from "@mui/material";
+
+const TableSkeleton = () => {
+ return (
+
+ );
+};
+
+export default TableSkeleton;
diff --git a/Client/src/Components/ThemeSwitch/SunAndMoonIcon.jsx b/client/src/Components/ThemeSwitch/SunAndMoonIcon.jsx
similarity index 100%
rename from Client/src/Components/ThemeSwitch/SunAndMoonIcon.jsx
rename to client/src/Components/ThemeSwitch/SunAndMoonIcon.jsx
diff --git a/Client/src/Components/ThemeSwitch/index.css b/client/src/Components/ThemeSwitch/index.css
similarity index 100%
rename from Client/src/Components/ThemeSwitch/index.css
rename to client/src/Components/ThemeSwitch/index.css
diff --git a/Client/src/Components/ThemeSwitch/index.jsx b/client/src/Components/ThemeSwitch/index.jsx
similarity index 100%
rename from Client/src/Components/ThemeSwitch/index.jsx
rename to client/src/Components/ThemeSwitch/index.jsx
diff --git a/client/src/Components/WalletProvider/index.css b/client/src/Components/WalletProvider/index.css
new file mode 100644
index 000000000..15fb9d816
--- /dev/null
+++ b/client/src/Components/WalletProvider/index.css
@@ -0,0 +1,51 @@
+.wallet-adapter-dropdown {
+ width: 100%;
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ align-items: center;
+ gap: var(--env-var-spacing-1);
+}
+
+.wallet-adapter-button {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: auto;
+ height: var(--env-var-height-2) !important;
+ font-size: var(--env-var-font-size-medium-plus) !important;
+ font-weight: 500 !important;
+ margin: 0;
+ padding: calc((var(--env-var-height-2) - var(--env-var-font-size-medium-plus) * 1.2) / 2) var(--env-var-spacing-1);
+ white-space: nowrap;
+}
+
+.wallet-adapter-modal-title {
+ font-size: var(--font-size-h5) !important;
+}
+
+/* Separator styling */
+.wallet-adapter-modal-divider {
+ background-color: var(--border-color) !important;
+ margin: var(--spacing-md) 0 !important;
+}
+
+/* Responsive fixes */
+@media (max-width: 1200px) {
+ .wallet-adapter-button {
+ font-size: var(--env-var-font-size-medium) !important;
+ padding: calc((var(--env-var-height-2) - var(--env-var-font-size-medium) * 1.2) / 2)
+ var(--env-var-spacing-1-minus) !important;
+
+ }
+}
+
+@media (max-width: 900px) {
+ .wallet-adapter-modal-wrapper {
+ flex-direction: column !important;
+ }
+
+ .wallet-adapter-modal-divider {
+ margin: var(--spacing-sm) 0 !important;
+ }
+}
\ No newline at end of file
diff --git a/client/src/Components/WalletProvider/index.jsx b/client/src/Components/WalletProvider/index.jsx
new file mode 100644
index 000000000..13cc83b07
--- /dev/null
+++ b/client/src/Components/WalletProvider/index.jsx
@@ -0,0 +1,50 @@
+// import { useMemo } from "react";
+// import { ConnectionProvider, WalletProvider } from "@solana/wallet-adapter-react";
+// import { WalletAdapterNetwork } from "@solana/wallet-adapter-base";
+// import {
+// UnsafeBurnerWalletAdapter,
+// PhantomWalletAdapter,
+// } from "@solana/wallet-adapter-wallets";
+
+// import { WalletModalProvider } from "@solana/wallet-adapter-react-ui";
+// import { clusterApiUrl } from "@solana/web3.js";
+// import PropTypes from "prop-types";
+// import "./index.css";
+
+// // Default styles that can be overridden by your app
+// import "@solana/wallet-adapter-react-ui/styles.css";
+
+// export const Wallet = ({ children }) => {
+// // The network can be set to 'devnet', 'testnet', or 'mainnet-beta'.
+// const network = WalletAdapterNetwork.Mainnet;
+
+// // You can also provide a custom RPC endpoint.
+// const endpoint = useMemo(() => clusterApiUrl(network), [network]);
+
+// const wallets = useMemo(
+// () => [new PhantomWalletAdapter()],
+// // eslint-disable-next-line react-hooks/exhaustive-deps
+// [network]
+// );
+
+// return (
+//
+//
+// {children}
+//
+//
+// );
+// };
+
+// Wallet.propTypes = {
+// children: PropTypes.node,
+// };
+
+const Wallet = ({ children }) => {
+ return children;
+};
+
+export default Wallet;
diff --git a/Client/src/Features/Auth/authSlice.js b/client/src/Features/Auth/authSlice.js
similarity index 95%
rename from Client/src/Features/Auth/authSlice.js
rename to client/src/Features/Auth/authSlice.js
index 31c8cb89f..2fde49202 100644
--- a/Client/src/Features/Auth/authSlice.js
+++ b/client/src/Features/Auth/authSlice.js
@@ -1,6 +1,5 @@
import { networkService } from "../../main";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
-import { jwtDecode } from "jwt-decode";
import axios from "axios";
const initialState = {
@@ -44,8 +43,8 @@ export const login = createAsyncThunk("auth/login", async (form, thunkApi) => {
});
export const update = createAsyncThunk("auth/update", async (data, thunkApi) => {
- const { authToken: token, localData: form } = data;
- const user = jwtDecode(token);
+ const { localData: form } = data;
+ const user = thunkApi.getState().auth.user;
try {
const fd = new FormData();
form.firstName && fd.append("firstName", form.firstName);
@@ -61,7 +60,6 @@ export const update = createAsyncThunk("auth/update", async (data, thunkApi) =>
form.deleteProfileImage && fd.append("deleteProfileImage", form.deleteProfileImage);
const res = await networkService.updateUser({
- authToken: token,
userId: user._id,
form: fd,
});
@@ -78,14 +76,11 @@ export const update = createAsyncThunk("auth/update", async (data, thunkApi) =>
}
});
-export const deleteUser = createAsyncThunk("auth/delete", async (data, thunkApi) => {
- const user = jwtDecode(data);
+export const deleteUser = createAsyncThunk("auth/delete", async (_, thunkApi) => {
+ const user = thunkApi.getState().auth.user;
try {
- const res = await networkService.deleteUser({
- authToken: data,
- userId: user._id,
- });
+ const res = await networkService.deleteUser({ userId: user._id });
return res.data;
} catch (error) {
if (error.response && error.response.data) {
diff --git a/Client/src/Features/InfrastructureMonitors/infrastructureMonitorsSlice.js b/client/src/Features/InfrastructureMonitors/infrastructureMonitorsSlice.js
similarity index 89%
rename from Client/src/Features/InfrastructureMonitors/infrastructureMonitorsSlice.js
rename to client/src/Features/InfrastructureMonitors/infrastructureMonitorsSlice.js
index f0282b28b..62bdf4811 100644
--- a/Client/src/Features/InfrastructureMonitors/infrastructureMonitorsSlice.js
+++ b/client/src/Features/InfrastructureMonitors/infrastructureMonitorsSlice.js
@@ -1,5 +1,4 @@
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
-import { jwtDecode } from "jwt-decode";
import { networkService } from "../../main";
const initialState = {
isLoading: false,
@@ -12,11 +11,8 @@ export const createInfrastructureMonitor = createAsyncThunk(
"infrastructureMonitors/createMonitor",
async (data, thunkApi) => {
try {
- const { authToken, monitor } = data;
- const res = await networkService.createMonitor({
- authToken: authToken,
- monitor: monitor,
- });
+ const { monitor } = data;
+ const res = await networkService.createMonitor({ monitor: monitor });
return res.data;
} catch (error) {
if (error.response && error.response.data) {
@@ -35,10 +31,8 @@ export const checkInfrastructureEndpointResolution = createAsyncThunk(
"infrastructureMonitors/CheckEndpoint",
async (data, thunkApi) => {
try {
- const { authToken, monitorURL } = data;
-
+ const { monitorURL } = data;
const res = await networkService.checkEndpointResolution({
- authToken: authToken,
monitorURL: monitorURL,
});
return res.data;
@@ -59,11 +53,8 @@ export const getInfrastructureMonitorById = createAsyncThunk(
"infrastructureMonitors/getMonitorById",
async (data, thunkApi) => {
try {
- const { authToken, monitorId } = data;
- const res = await networkService.getMonitorById({
- authToken: authToken,
- monitorId: monitorId,
- });
+ const { monitorId } = data;
+ const res = await networkService.getMonitorById({ monitorId: monitorId });
return res.data;
} catch (error) {
if (error.response && error.response.data) {
@@ -80,11 +71,10 @@ export const getInfrastructureMonitorById = createAsyncThunk(
export const getInfrastructureMonitorsByTeamId = createAsyncThunk(
"infrastructureMonitors/getMonitorsByTeamId",
- async (token, thunkApi) => {
- const user = jwtDecode(token);
+ async (_, thunkApi) => {
+ const user = thunkApi.getState().auth.user;
try {
const res = await networkService.getMonitorsAndSummaryByTeamId({
- authToken: token,
teamId: user.teamId,
types: ["hardware"],
limit: 1,
@@ -106,20 +96,20 @@ export const getInfrastructureMonitorsByTeamId = createAsyncThunk(
export const updateInfrastructureMonitor = createAsyncThunk(
"infrastructureMonitors/updateMonitor",
- async (data, thunkApi) => {
+ async ({ monitorId, monitor }, thunkApi) => {
try {
- const { authToken, monitor } = data;
const updatedFields = {
name: monitor.name,
description: monitor.description,
interval: monitor.interval,
notifications: monitor.notifications,
- threshold: monitor.threshold,
+ thresholds: monitor.thresholds,
+ secret: monitor.secret,
};
const res = await networkService.updateMonitor({
- authToken: authToken,
- monitorId: monitor._id,
- updatedFields: updatedFields,
+ monitorId,
+ monitor,
+ updatedFields,
});
return res.data;
} catch (error) {
@@ -139,11 +129,8 @@ export const deleteInfrastructureMonitor = createAsyncThunk(
"infrastructureMonitors/deleteMonitor",
async (data, thunkApi) => {
try {
- const { authToken, monitor } = data;
- const res = await networkService.deleteMonitorById({
- authToken: authToken,
- monitorId: monitor._id,
- });
+ const { monitor } = data;
+ const res = await networkService.deleteMonitorById({ monitorId: monitor._id });
return res.data;
} catch (error) {
if (error.response && error.response.data) {
@@ -162,11 +149,8 @@ export const pauseInfrastructureMonitor = createAsyncThunk(
"infrastructureMonitors/pauseMonitor",
async (data, thunkApi) => {
try {
- const { authToken, monitorId } = data;
- const res = await networkService.pauseMonitorById({
- authToken: authToken,
- monitorId: monitorId,
- });
+ const { monitorId } = data;
+ const res = await networkService.pauseMonitorById({ monitorId: monitorId });
return res.data;
} catch (error) {
if (error.response && error.response.data) {
@@ -185,11 +169,8 @@ export const deleteInfrastructureMonitorChecksByTeamId = createAsyncThunk(
"infrastructureMonitors/deleteChecksByTeamId",
async (data, thunkApi) => {
try {
- const { authToken, teamId } = data;
- const res = await networkService.deleteChecksByTeamId({
- authToken: authToken,
- teamId: teamId,
- });
+ const { teamId } = data;
+ const res = await networkService.deleteChecksByTeamId({ teamId: teamId });
return res.data;
} catch (error) {
if (error.response && error.response.data) {
@@ -208,10 +189,7 @@ export const deleteAllInfrastructureMonitors = createAsyncThunk(
"infrastructureMonitors/deleteAllMonitors",
async (data, thunkApi) => {
try {
- const { authToken } = data;
- const res = await networkService.deleteAllMonitors({
- authToken: authToken,
- });
+ const res = await networkService.deleteAllMonitors();
return res.data;
} catch (error) {
if (error.response && error.response.data) {
diff --git a/Client/src/Features/PageSpeedMonitor/pageSpeedMonitorSlice.js b/client/src/Features/PageSpeedMonitor/pageSpeedMonitorSlice.js
similarity index 90%
rename from Client/src/Features/PageSpeedMonitor/pageSpeedMonitorSlice.js
rename to client/src/Features/PageSpeedMonitor/pageSpeedMonitorSlice.js
index b2da2cbe6..3ed2da13f 100644
--- a/Client/src/Features/PageSpeedMonitor/pageSpeedMonitorSlice.js
+++ b/client/src/Features/PageSpeedMonitor/pageSpeedMonitorSlice.js
@@ -1,5 +1,4 @@
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
-import { jwtDecode } from "jwt-decode";
import { networkService } from "../../main";
const initialState = {
isLoading: false,
@@ -12,11 +11,8 @@ export const createPageSpeed = createAsyncThunk(
"pageSpeedMonitors/createPageSpeed",
async (data, thunkApi) => {
try {
- const { authToken, monitor } = data;
- const res = await networkService.createMonitor({
- authToken: authToken,
- monitor: monitor,
- });
+ const { monitor } = data;
+ const res = await networkService.createMonitor({ monitor: monitor });
return res.data;
} catch (error) {
if (error.response && error.response.data) {
@@ -35,10 +31,8 @@ export const checkEndpointResolution = createAsyncThunk(
"monitors/checkEndpoint",
async (data, thunkApi) => {
try {
- const { authToken, monitorURL } = data;
-
+ const { monitorURL } = data;
const res = await networkService.checkEndpointResolution({
- authToken: authToken,
monitorURL: monitorURL,
});
return res.data;
@@ -59,11 +53,8 @@ export const getPagespeedMonitorById = createAsyncThunk(
"monitors/getMonitorById",
async (data, thunkApi) => {
try {
- const { authToken, monitorId } = data;
- const res = await networkService.getMonitorById({
- authToken: authToken,
- monitorId: monitorId,
- });
+ const { monitorId } = data;
+ const res = await networkService.getMonitorById({ monitorId: monitorId });
return res.data;
} catch (error) {
if (error.response && error.response.data) {
@@ -80,11 +71,10 @@ export const getPagespeedMonitorById = createAsyncThunk(
export const getPageSpeedByTeamId = createAsyncThunk(
"pageSpeedMonitors/getPageSpeedByTeamId",
- async (token, thunkApi) => {
- const user = jwtDecode(token);
+ async (_, thunkApi) => {
+ const user = thunkApi.getState().auth.user;
try {
const res = await networkService.getMonitorsAndSummaryByTeamId({
- authToken: token,
teamId: user.teamId,
types: ["pagespeed"],
});
@@ -106,15 +96,14 @@ export const updatePageSpeed = createAsyncThunk(
"pageSpeedMonitors/updatePageSpeed",
async (data, thunkApi) => {
try {
- const { authToken, monitor } = data;
+ const { monitor } = data;
const updatedFields = {
name: monitor.name,
description: monitor.description,
interval: monitor.interval,
- // notifications: monitor.notifications,
+ notifications: monitor.notifications,
};
const res = await networkService.updateMonitor({
- authToken: authToken,
monitorId: monitor._id,
updatedFields: updatedFields,
});
@@ -136,11 +125,8 @@ export const deletePageSpeed = createAsyncThunk(
"pageSpeedMonitors/deletePageSpeed",
async (data, thunkApi) => {
try {
- const { authToken, monitor } = data;
- const res = await networkService.deleteMonitorById({
- authToken: authToken,
- monitorId: monitor._id,
- });
+ const { monitor } = data;
+ const res = await networkService.deleteMonitorById({ monitorId: monitor._id });
return res.data;
} catch (error) {
if (error.response && error.response.data) {
@@ -158,11 +144,8 @@ export const pausePageSpeed = createAsyncThunk(
"pageSpeedMonitors/pausePageSpeed",
async (data, thunkApi) => {
try {
- const { authToken, monitorId } = data;
- const res = await networkService.pauseMonitorById({
- authToken: authToken,
- monitorId: monitorId,
- });
+ const { monitorId } = data;
+ const res = await networkService.pauseMonitorById({ monitorId: monitorId });
return res.data;
} catch (error) {
if (error.response && error.response.data) {
diff --git a/Client/src/Features/Settings/settingsSlice.js b/client/src/Features/Settings/settingsSlice.js
similarity index 75%
rename from Client/src/Features/Settings/settingsSlice.js
rename to client/src/Features/Settings/settingsSlice.js
index 283a8502d..02724af02 100644
--- a/Client/src/Features/Settings/settingsSlice.js
+++ b/client/src/Features/Settings/settingsSlice.js
@@ -5,15 +5,15 @@ const initialState = {
isLoading: false,
apiBaseUrl: "",
logLevel: "debug",
+ language: "gb",
+ pagespeedApiKey: "",
};
export const getAppSettings = createAsyncThunk(
"settings/getSettings",
async (data, thunkApi) => {
try {
- const res = await networkService.getAppSettings({
- authToken: data.authToken,
- });
+ const res = await networkService.getAppSettings();
return res.data;
} catch (error) {
if (error.response.data) {
@@ -30,29 +30,13 @@ export const getAppSettings = createAsyncThunk(
export const updateAppSettings = createAsyncThunk(
"settings/updateSettings",
- async ({ settings, authToken }, thunkApi) => {
- networkService.setBaseUrl(settings.apiBaseUrl);
+ async ({ settings }, thunkApi) => {
try {
const parsedSettings = {
- apiBaseUrl: settings.apiBaseUrl,
- logLevel: settings.logLevel,
- clientHost: settings.clientHost,
- jwtSecret: settings.jwtSecret,
- dbType: settings.dbType,
- dbConnectionString: settings.dbConnectionString,
- redisHost: settings.redisHost,
- redisPort: settings.redisPort,
- jwtTTL: settings.jwtTTL,
+ language: settings.language,
pagespeedApiKey: settings.pagespeedApiKey,
- systemEmailHost: settings.systemEmailHost,
- systemEmailPort: settings.systemEmailPort,
- systemEmailAddress: settings.systemEmailAddress,
- systemEmailPassword: settings.systemEmailPassword,
};
- const res = await networkService.updateAppSettings({
- settings: parsedSettings,
- authToken,
- });
+ const res = await networkService.updateAppSettings({ settings: parsedSettings });
return res.data;
} catch (error) {
if (error.response && error.response.data) {
@@ -73,6 +57,8 @@ const handleGetSettingsFulfilled = (state, action) => {
state.msg = action.payload.msg;
state.apiBaseUrl = action.payload.data.apiBaseUrl;
state.logLevel = action.payload.data.logLevel;
+ state.language = action.payload.data.language;
+ state.pagespeedApiKey = action.payload.data.pagespeedApiKey;
};
const handleGetSettingsRejected = (state, action) => {
state.isLoading = false;
diff --git a/Client/src/Features/UI/uiSlice.js b/client/src/Features/UI/uiSlice.js
similarity index 63%
rename from Client/src/Features/UI/uiSlice.js
rename to client/src/Features/UI/uiSlice.js
index 872691bbf..f20115b92 100644
--- a/Client/src/Features/UI/uiSlice.js
+++ b/client/src/Features/UI/uiSlice.js
@@ -1,6 +1,8 @@
import { createSlice } from "@reduxjs/toolkit";
-const initialMode = window?.matchMedia?.('(prefers-color-scheme: dark)')?.matches ? "dark" : "light";
+const initialMode = window?.matchMedia?.("(prefers-color-scheme: dark)")?.matches
+ ? "dark"
+ : "light";
// Initial state for UI settings.
// Add more settings as needed (e.g., theme preferences, user settings)
@@ -20,12 +22,18 @@ const initialState = {
mode: initialMode,
greeting: { index: 0, lastUpdate: null },
timezone: "America/Toronto",
+ distributedUptimeEnabled: false,
+ language: "gb",
+ starPromptOpen: true,
};
const uiSlice = createSlice({
name: "ui",
initialState,
reducers: {
+ setDistributedUptimeEnabled: (state, action) => {
+ state.distributedUptimeEnabled = action.payload;
+ },
setRowsPerPage: (state, action) => {
const { table, value } = action.payload;
if (state[table]) {
@@ -45,9 +53,23 @@ const uiSlice = createSlice({
setTimezone(state, action) {
state.timezone = action.payload.timezone;
},
+ setLanguage(state, action) {
+ state.language = action.payload;
+ },
+ setStarPromptOpen: (state, action) => {
+ state.starPromptOpen = action.payload;
+ },
},
});
export default uiSlice.reducer;
-export const { setRowsPerPage, toggleSidebar, setMode, setGreeting, setTimezone } =
- uiSlice.actions;
+export const {
+ setRowsPerPage,
+ toggleSidebar,
+ setMode,
+ setGreeting,
+ setTimezone,
+ setDistributedUptimeEnabled,
+ setLanguage,
+ setStarPromptOpen,
+} = uiSlice.actions;
diff --git a/Client/src/Features/UptimeMonitors/uptimeMonitorsSlice.js b/client/src/Features/UptimeMonitors/uptimeMonitorsSlice.js
similarity index 89%
rename from Client/src/Features/UptimeMonitors/uptimeMonitorsSlice.js
rename to client/src/Features/UptimeMonitors/uptimeMonitorsSlice.js
index 7ea34b9ea..74ad803d3 100644
--- a/Client/src/Features/UptimeMonitors/uptimeMonitorsSlice.js
+++ b/client/src/Features/UptimeMonitors/uptimeMonitorsSlice.js
@@ -1,5 +1,4 @@
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
-import { jwtDecode } from "jwt-decode";
import { networkService } from "../../main";
const initialState = {
isLoading: false,
@@ -12,11 +11,8 @@ export const createUptimeMonitor = createAsyncThunk(
"monitors/createMonitor",
async (data, thunkApi) => {
try {
- const { authToken, monitor } = data;
- const res = await networkService.createMonitor({
- authToken: authToken,
- monitor: monitor,
- });
+ const { monitor } = data;
+ const res = await networkService.createMonitor({ monitor: monitor });
return res.data;
} catch (error) {
if (error.response && error.response.data) {
@@ -35,10 +31,8 @@ export const checkEndpointResolution = createAsyncThunk(
"monitors/checkEndpoint",
async (data, thunkApi) => {
try {
- const { authToken, monitorURL } = data;
-
+ const { monitorURL } = data;
const res = await networkService.checkEndpointResolution({
- authToken: authToken,
monitorURL: monitorURL,
});
return res.data;
@@ -59,11 +53,8 @@ export const getUptimeMonitorById = createAsyncThunk(
"monitors/getMonitorById",
async (data, thunkApi) => {
try {
- const { authToken, monitorId } = data;
- const res = await networkService.getMonitorById({
- authToken: authToken,
- monitorId: monitorId,
- });
+ const { monitorId } = data;
+ const res = await networkService.getMonitorById({ monitorId: monitorId });
return res.data;
} catch (error) {
if (error.response && error.response.data) {
@@ -82,17 +73,21 @@ export const updateUptimeMonitor = createAsyncThunk(
"monitors/updateMonitor",
async (data, thunkApi) => {
try {
- const { authToken, monitor } = data;
+ const { monitor } = data;
const updatedFields = {
name: monitor.name,
description: monitor.description,
interval: monitor.interval,
notifications: monitor.notifications,
+ matchMethod: monitor.matchMethod,
+ expectedValue: monitor.expectedValue,
+ ignoreTlsErrors: monitor.ignoreTlsErrors,
+ jsonPath: monitor.jsonPath,
+ ...(monitor.type === "port" && { port: monitor.port }),
};
const res = await networkService.updateMonitor({
- authToken: authToken,
monitorId: monitor._id,
- updatedFields: updatedFields,
+ updatedFields,
});
return res.data;
} catch (error) {
@@ -112,11 +107,8 @@ export const deleteUptimeMonitor = createAsyncThunk(
"monitors/deleteMonitor",
async (data, thunkApi) => {
try {
- const { authToken, monitor } = data;
- const res = await networkService.deleteMonitorById({
- authToken: authToken,
- monitorId: monitor._id,
- });
+ const { monitor } = data;
+ const res = await networkService.deleteMonitorById({ monitorId: monitor._id });
return res.data;
} catch (error) {
if (error.response && error.response.data) {
@@ -135,11 +127,8 @@ export const pauseUptimeMonitor = createAsyncThunk(
"monitors/pauseMonitor",
async (data, thunkApi) => {
try {
- const { authToken, monitorId } = data;
- const res = await networkService.pauseMonitorById({
- authToken: authToken,
- monitorId: monitorId,
- });
+ const { monitorId } = data;
+ const res = await networkService.pauseMonitorById({ monitorId: monitorId });
return res.data;
} catch (error) {
if (error.response && error.response.data) {
@@ -158,11 +147,8 @@ export const deleteMonitorChecksByTeamId = createAsyncThunk(
"monitors/deleteChecksByTeamId",
async (data, thunkApi) => {
try {
- const { authToken, teamId } = data;
- const res = await networkService.deleteChecksByTeamId({
- authToken: authToken,
- teamId: teamId,
- });
+ const { teamId } = data;
+ const res = await networkService.deleteChecksByTeamId({ teamId: teamId });
return res.data;
} catch (error) {
if (error.response && error.response.data) {
@@ -180,10 +166,7 @@ export const addDemoMonitors = createAsyncThunk(
"monitors/addDemoMonitors",
async (data, thunkApi) => {
try {
- const { authToken } = data;
- const res = await networkService.addDemoMonitors({
- authToken: authToken,
- });
+ const res = await networkService.addDemoMonitors();
return res.data;
} catch (error) {
if (error.response && error.response.data) {
@@ -202,10 +185,7 @@ export const deleteAllMonitors = createAsyncThunk(
"monitors/deleteAllMonitors",
async (data, thunkApi) => {
try {
- const { authToken } = data;
- const res = await networkService.deleteAllMonitors({
- authToken: authToken,
- });
+ const res = await networkService.deleteAllMonitors();
return res.data;
} catch (error) {
if (error.response && error.response.data) {
diff --git a/client/src/Hooks/inviteHooks.js b/client/src/Hooks/inviteHooks.js
new file mode 100644
index 000000000..705906efa
--- /dev/null
+++ b/client/src/Hooks/inviteHooks.js
@@ -0,0 +1,46 @@
+import { useState } from "react";
+import { networkService } from "../main";
+import { useTranslation } from "react-i18next";
+
+const CLIENT_HOST = import.meta.env.VITE_APP_CLIENT_HOST;
+
+const useGetInviteToken = () => {
+ const { t } = useTranslation();
+
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState(undefined);
+ const [token, setToken] = useState(undefined);
+
+ const clearToken = () => {
+ setToken(undefined);
+ };
+
+ const getInviteToken = async ({ email, role }) => {
+ try {
+ const response = await networkService.requestInvitationToken({
+ email,
+ role,
+ });
+ const token = response?.data?.data?.token;
+ if (typeof token === "undefined") {
+ throw new Error(t("inviteNoTokenFound"));
+ }
+
+ let inviteLink = token;
+
+ if (typeof CLIENT_HOST !== "undefined") {
+ inviteLink = `${CLIENT_HOST}/register/${token}`;
+ }
+
+ setToken(inviteLink);
+ } catch (error) {
+ setError(error);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return [getInviteToken, clearToken, isLoading, error, token];
+};
+
+export { useGetInviteToken };
diff --git a/client/src/Hooks/useBulkMonitors.js b/client/src/Hooks/useBulkMonitors.js
new file mode 100644
index 000000000..0caa58b41
--- /dev/null
+++ b/client/src/Hooks/useBulkMonitors.js
@@ -0,0 +1,27 @@
+import { useState } from "react";
+import { networkService } from "../main";
+
+export const useBulkMonitors = () => {
+ const [isLoading, setIsLoading] = useState(false);
+
+ const createBulkMonitors = async (file, user) => {
+ setIsLoading(true);
+
+ const formData = new FormData();
+ formData.append("csvFile", file);
+ formData.append("userId", user._id);
+ formData.append("teamId", user.teamId);
+
+ try {
+ const response = await networkService.createBulkMonitors(formData);
+ return [true, response.data, null]; // [success, data, error]
+ } catch (err) {
+ const errorMessage = err?.response?.data?.msg || err.message;
+ return [false, null, errorMessage];
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return [createBulkMonitors, isLoading];
+};
diff --git a/client/src/Hooks/useDeleteMonitorStats.js b/client/src/Hooks/useDeleteMonitorStats.js
new file mode 100644
index 000000000..64138929f
--- /dev/null
+++ b/client/src/Hooks/useDeleteMonitorStats.js
@@ -0,0 +1,24 @@
+import { useState } from "react";
+import { networkService } from "../main";
+import { createToast } from "../Utils/toastUtils";
+import { useTranslation } from "react-i18next";
+
+const UseDeleteMonitorStats = () => {
+ const { t } = useTranslation();
+ const [isLoading, setIsLoading] = useState(false);
+ const deleteMonitorStats = async ({ teamId }) => {
+ setIsLoading(true);
+ try {
+ const res = await networkService.deleteChecksByTeamId({ teamId });
+ createToast({ body: t("settingsStatsCleared") });
+ } catch (error) {
+ createToast({ body: t("settingsFailedToClearStats") });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return [deleteMonitorStats, isLoading];
+};
+
+export { UseDeleteMonitorStats };
diff --git a/client/src/Hooks/useFetchDepinStatusPage.js b/client/src/Hooks/useFetchDepinStatusPage.js
new file mode 100644
index 000000000..cb436d6d6
--- /dev/null
+++ b/client/src/Hooks/useFetchDepinStatusPage.js
@@ -0,0 +1,58 @@
+import { useState, useEffect } from "react";
+import { networkService } from "../main";
+import { createToast } from "../Utils/toastUtils";
+import { useSelector } from "react-redux";
+import { useTheme } from "@emotion/react";
+import { useMonitorUtils } from "./useMonitorUtils";
+
+const useFetchDepinStatusPage = ({ url, timeFrame, isCreate = false }) => {
+ const [isLoading, setIsLoading] = useState(true);
+ const [networkError, setNetworkError] = useState(false);
+ const [statusPage, setStatusPage] = useState(undefined);
+ const [monitorId, setMonitorId] = useState(undefined);
+ const [isPublished, setIsPublished] = useState(false);
+ const { authToken } = useSelector((state) => state.auth);
+ const theme = useTheme();
+ const { getMonitorWithPercentage } = useMonitorUtils();
+
+ useEffect(() => {
+ if (isCreate) return;
+ const fetchStatusPageByUrl = async () => {
+ try {
+ const response = await networkService.getDistributedStatusPageByUrl({
+ authToken,
+ url,
+ type: "distributed",
+ timeFrame,
+ });
+ if (!response?.data?.data) return;
+ const statusPage = response.data.data;
+
+ const monitorsWithPercentage = statusPage?.subMonitors.map((monitor) =>
+ getMonitorWithPercentage(monitor, theme)
+ );
+
+ const statusPageWithSubmonitorPercentages = {
+ ...statusPage,
+ subMonitors: monitorsWithPercentage,
+ };
+ setStatusPage(statusPageWithSubmonitorPercentages);
+
+ setMonitorId(statusPage?.monitors[0]);
+ setIsPublished(statusPage?.isPublished);
+ } catch (error) {
+ setNetworkError(true);
+ createToast({
+ body: error.message,
+ });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+ fetchStatusPageByUrl();
+ }, [authToken, url, getMonitorWithPercentage, theme, timeFrame, isCreate]);
+
+ return [isLoading, networkError, statusPage, monitorId, isPublished];
+};
+
+export { useFetchDepinStatusPage };
diff --git a/client/src/Hooks/useFetchMonitorsWithChecks.js b/client/src/Hooks/useFetchMonitorsWithChecks.js
new file mode 100644
index 000000000..a6f0437b9
--- /dev/null
+++ b/client/src/Hooks/useFetchMonitorsWithChecks.js
@@ -0,0 +1,72 @@
+import { useEffect, useState } from "react";
+import { networkService } from "../main";
+import { createToast } from "../Utils/toastUtils";
+import { useTheme } from "@emotion/react";
+import { useMonitorUtils } from "./useMonitorUtils";
+
+export const useFetchMonitorsWithChecks = ({
+ teamId,
+ types,
+ limit,
+ page,
+ rowsPerPage,
+ filter,
+ field,
+ order,
+ monitorUpdateTrigger,
+}) => {
+ const [isLoading, setIsLoading] = useState(false);
+ const [count, setCount] = useState(undefined);
+ const [monitors, setMonitors] = useState(undefined);
+ const [networkError, setNetworkError] = useState(false);
+
+ const theme = useTheme();
+ const { getMonitorWithPercentage } = useMonitorUtils();
+ useEffect(() => {
+ const fetchMonitors = async () => {
+ try {
+ setIsLoading(true);
+ const res = await networkService.getMonitorsWithChecksByTeamId({
+ teamId,
+ limit,
+ types,
+ page,
+ rowsPerPage,
+ filter,
+ field,
+ order,
+ });
+ const { count, monitors } = res?.data?.data ?? {};
+ const mappedMonitors = monitors.map((monitor) =>
+ getMonitorWithPercentage(monitor, theme)
+ );
+ setMonitors(mappedMonitors);
+ setCount(count?.monitorsCount ?? 0);
+ } catch (error) {
+ console.error(error);
+ setNetworkError(true);
+ createToast({
+ body: error.message,
+ });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+ fetchMonitors();
+ }, [
+ field,
+ filter,
+ getMonitorWithPercentage,
+ limit,
+ order,
+ page,
+ rowsPerPage,
+ teamId,
+ theme,
+ types,
+ monitorUpdateTrigger,
+ ]);
+ return [monitors, count, isLoading, networkError];
+};
+
+export default useFetchMonitorsWithChecks;
diff --git a/client/src/Hooks/useFetchMonitorsWithSummary.js b/client/src/Hooks/useFetchMonitorsWithSummary.js
new file mode 100644
index 000000000..cd21271d4
--- /dev/null
+++ b/client/src/Hooks/useFetchMonitorsWithSummary.js
@@ -0,0 +1,37 @@
+import { useEffect, useState } from "react";
+import { networkService } from "../main";
+import { createToast } from "../Utils/toastUtils";
+
+export const useFetchMonitorsWithSummary = ({ teamId, types, monitorUpdateTrigger }) => {
+ const [isLoading, setIsLoading] = useState(false);
+ const [monitors, setMonitors] = useState(undefined);
+ const [monitorsSummary, setMonitorsSummary] = useState(undefined);
+ const [networkError, setNetworkError] = useState(false);
+
+ useEffect(() => {
+ const fetchMonitors = async () => {
+ try {
+ setIsLoading(true);
+ const res = await networkService.getMonitorsWithSummaryByTeamId({
+ teamId,
+ types,
+ });
+ const { monitors, summary } = res?.data?.data ?? {};
+ setMonitors(monitors);
+ setMonitorsSummary(summary);
+ } catch (error) {
+ console.error(error);
+ setNetworkError(true);
+ createToast({
+ body: error.message,
+ });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+ fetchMonitors();
+ }, [teamId, types, monitorUpdateTrigger]);
+ return [monitors, monitorsSummary, isLoading, networkError];
+};
+
+export default useFetchMonitorsWithSummary;
diff --git a/client/src/Hooks/useFetchSettings.js b/client/src/Hooks/useFetchSettings.js
new file mode 100644
index 000000000..f7651e789
--- /dev/null
+++ b/client/src/Hooks/useFetchSettings.js
@@ -0,0 +1,55 @@
+import { useState, useEffect } from "react";
+import { networkService } from "../main";
+import { createToast } from "../Utils/toastUtils";
+import { useTranslation } from "react-i18next";
+
+const useFetchSettings = ({ setSettingsData }) => {
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState(undefined);
+ useEffect(() => {
+ const fetchSettings = async () => {
+ setIsLoading(true);
+ try {
+ const response = await networkService.getAppSettings();
+ setSettingsData(response?.data?.data);
+ } catch (error) {
+ createToast({ body: "Failed to fetch settings" });
+ setError(error);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+ fetchSettings();
+ }, []);
+
+ return [isLoading, error];
+};
+
+const useSaveSettings = () => {
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState(undefined);
+ const { t } = useTranslation();
+
+ const saveSettings = async (settings) => {
+ setIsLoading(true);
+ try {
+ await networkService.updateAppSettings({ settings });
+ if (settings.checkTTL) {
+ await networkService.updateChecksTTL({
+ ttl: settings.checkTTL,
+ });
+ }
+ createToast({ body: t("settingsSuccessSaved") });
+ } catch (error) {
+ createToast({ body: t("settingsFailedToSave") });
+
+ setError(error);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return [isLoading, error, saveSettings];
+};
+
+export { useFetchSettings, useSaveSettings };
diff --git a/client/src/Hooks/useFetchUptimeMonitorDetails.js b/client/src/Hooks/useFetchUptimeMonitorDetails.js
new file mode 100644
index 000000000..c8cb81e65
--- /dev/null
+++ b/client/src/Hooks/useFetchUptimeMonitorDetails.js
@@ -0,0 +1,36 @@
+import { useEffect, useState } from "react";
+import { networkService } from "../main";
+import { useNavigate } from "react-router-dom";
+import { createToast } from "../Utils/toastUtils";
+
+export const useFetchUptimeMonitorDetails = ({ monitorId, dateRange }) => {
+ const [networkError, setNetworkError] = useState(false);
+ const [isLoading, setIsLoading] = useState(true);
+ const [monitor, setMonitor] = useState(undefined);
+ const [monitorStats, setMonitorStats] = useState(undefined);
+ const navigate = useNavigate();
+
+ useEffect(() => {
+ const fetchMonitors = async () => {
+ try {
+ const res = await networkService.getUptimeDetailsById({
+ monitorId: monitorId,
+ dateRange: dateRange,
+ normalize: true,
+ });
+ const { monitorData, monitorStats } = res?.data?.data ?? {};
+ setMonitor(monitorData);
+ setMonitorStats(monitorStats);
+ } catch (error) {
+ setNetworkError(true);
+ createToast({ body: error.message });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+ fetchMonitors();
+ }, [dateRange, monitorId, navigate]);
+ return [monitor, monitorStats, isLoading, networkError];
+};
+
+export default useFetchUptimeMonitorDetails;
diff --git a/Client/src/Hooks/useIsAdmin.js b/client/src/Hooks/useIsAdmin.js
similarity index 100%
rename from Client/src/Hooks/useIsAdmin.js
rename to client/src/Hooks/useIsAdmin.js
diff --git a/client/src/Hooks/useMonitorUtils.js b/client/src/Hooks/useMonitorUtils.js
new file mode 100644
index 000000000..fc1966b69
--- /dev/null
+++ b/client/src/Hooks/useMonitorUtils.js
@@ -0,0 +1,42 @@
+import { useCallback } from "react";
+
+const useMonitorUtils = () => {
+ const getMonitorWithPercentage = useCallback((monitor, theme) => {
+ let uptimePercentage = "";
+ let percentageColor = "";
+
+ if (monitor.uptimePercentage !== undefined) {
+ uptimePercentage =
+ monitor.uptimePercentage === 0
+ ? "0"
+ : (monitor.uptimePercentage * 100).toFixed(2);
+
+ percentageColor =
+ monitor.uptimePercentage < 0.25
+ ? theme.palette.error.main
+ : monitor.uptimePercentage < 0.5
+ ? theme.palette.warning.main
+ : monitor.uptimePercentage < 0.75
+ ? theme.palette.success.main
+ : theme.palette.success.main;
+ }
+
+ return {
+ ...monitor,
+ percentage: uptimePercentage,
+ percentageColor,
+ monitor: monitor,
+ };
+ }, []);
+
+ const determineState = useCallback((monitor) => {
+ if (typeof monitor === "undefined") return "pending";
+ if (monitor.isActive === false) return "paused";
+ if (monitor?.status === undefined) return "pending";
+ return monitor?.status == true ? "up" : "down";
+ }, []);
+
+ return { getMonitorWithPercentage, determineState };
+};
+
+export { useMonitorUtils };
diff --git a/client/src/Hooks/useSendTestEmail.js b/client/src/Hooks/useSendTestEmail.js
new file mode 100644
index 000000000..fef45c3ea
--- /dev/null
+++ b/client/src/Hooks/useSendTestEmail.js
@@ -0,0 +1,33 @@
+import { useState } from "react";
+import { networkService } from "../main";
+import { useSelector } from "react-redux";
+import { createToast } from "../Utils/toastUtils";
+
+const useSendTestEmail = () => {
+ const [isSending, setIsSending] = useState(false);
+ const [error, setError] = useState(null);
+ const user = useSelector((state) => state.auth.user);
+
+ const sendTestEmail = async () => {
+ try {
+ setIsSending(true);
+ setError(null);
+
+ const response = await networkService.sendTestEmail({ to: user.email });
+ if (typeof response?.data?.data?.messageId !== "undefined") {
+ createToast({
+ body: "Test email sent successfully",
+ });
+ } else {
+ throw new Error("Failed to send test email");
+ }
+ } catch (error) {
+ setError(error);
+ } finally {
+ setIsSending(false);
+ }
+ };
+ return [isSending, error, sendTestEmail];
+};
+
+export { useSendTestEmail };
diff --git a/client/src/Hooks/useSubscribeToDepinDetails.js b/client/src/Hooks/useSubscribeToDepinDetails.js
new file mode 100644
index 000000000..0e8c2744f
--- /dev/null
+++ b/client/src/Hooks/useSubscribeToDepinDetails.js
@@ -0,0 +1,96 @@
+import { useState, useEffect } from "react";
+import { networkService } from "../main";
+import { createToast } from "../Utils/toastUtils";
+
+const useSubscribeToDepinDetails = ({ monitorId, isPublic, isPublished, dateRange }) => {
+ const [isLoading, setIsLoading] = useState(true);
+ const [connectionStatus, setConnectionStatus] = useState(undefined);
+ const [retryCount, setRetryCount] = useState(0);
+ const [networkError, setNetworkError] = useState(false);
+ const [monitor, setMonitor] = useState(undefined);
+ const [lastUpdateTrigger, setLastUpdateTrigger] = useState(0);
+
+ useEffect(() => {
+ if (typeof monitorId === "undefined") {
+ return;
+ }
+ // If this page is public and not published, don't subscribe to details
+ if (isPublic && isPublished === false) {
+ return;
+ }
+
+ // Get initial data
+
+ const fetchInitialData = async () => {
+ try {
+ const res = await networkService.getDistributedUptimeDetails({
+ monitorId,
+ dateRange: dateRange,
+ normalize: true,
+ isPublic,
+ });
+ const responseData = res?.data?.data;
+
+ if (typeof responseData === "undefined") {
+ throw new Error("No data");
+ }
+ setConnectionStatus("up");
+ setLastUpdateTrigger(Date.now());
+ setMonitor(responseData);
+ } catch (error) {
+ setNetworkError(true);
+ setConnectionStatus("down");
+ createToast({
+ body: error.message,
+ });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ fetchInitialData();
+
+ try {
+ const cleanup = networkService.subscribeToDistributedUptimeDetails({
+ monitorId,
+ dateRange: dateRange,
+ normalize: true,
+ onUpdate: (data) => {
+ if (isLoading === true) {
+ setIsLoading(false);
+ }
+ if (networkError === true) {
+ setNetworkError(false);
+ }
+ setLastUpdateTrigger(Date.now());
+ setMonitor(data.monitor);
+ },
+ onOpen: () => {
+ setConnectionStatus("up");
+ setRetryCount(0); // Reset retry count on successful connection
+ },
+ onError: () => {
+ setIsLoading(false);
+ setNetworkError(true);
+ setConnectionStatus("down");
+ },
+ });
+ return cleanup;
+ } catch (error) {
+ setNetworkError(true);
+ }
+ }, [
+ dateRange,
+ monitorId,
+ retryCount,
+ setConnectionStatus,
+ networkError,
+ isLoading,
+ isPublic,
+ isPublished,
+ ]);
+
+ return [isLoading, networkError, connectionStatus, monitor, lastUpdateTrigger];
+};
+
+export { useSubscribeToDepinDetails };
diff --git a/client/src/Hooks/useSubscribeToDepinMonitors.js b/client/src/Hooks/useSubscribeToDepinMonitors.js
new file mode 100644
index 000000000..918ead6bc
--- /dev/null
+++ b/client/src/Hooks/useSubscribeToDepinMonitors.js
@@ -0,0 +1,95 @@
+import { useEffect, useState } from "react";
+import { networkService } from "../main";
+import { useSelector } from "react-redux";
+import { useTheme } from "@emotion/react";
+import { useMonitorUtils } from "./useMonitorUtils";
+import { createToast } from "../Utils/toastUtils";
+
+const useSubscribeToDepinMonitors = (page, rowsPerPage) => {
+ // Redux
+ const { user } = useSelector((state) => state.auth);
+
+ // Local state
+ const [isLoading, setIsLoading] = useState(true);
+ const [networkError, setNetworkError] = useState(false);
+ const [count, setCount] = useState(undefined);
+ const [monitors, setMonitors] = useState(undefined);
+
+ const theme = useTheme();
+ const { getMonitorWithPercentage } = useMonitorUtils();
+
+ useEffect(() => {
+ const fetchInitialData = async () => {
+ try {
+ const initialDataRes = await networkService.getDistributedUptimeMonitors({
+ teamId: user.teamId,
+ limit: 25,
+ types: ["distributed_http"],
+ page,
+ rowsPerPage,
+ });
+
+ const { count, monitors } = initialDataRes?.data?.data ?? {};
+ const responseData = initialDataRes?.data?.data;
+ if (typeof responseData === "undefined") throw new Error("No data");
+
+ const mappedMonitors = monitors?.map((monitor) =>
+ getMonitorWithPercentage(monitor, theme)
+ );
+
+ setMonitors(mappedMonitors);
+ setCount(count?.monitorsCount ?? 0);
+ } catch (error) {
+ setNetworkError(true);
+ createToast({
+ body: error.message,
+ });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ fetchInitialData();
+
+ try {
+ const cleanup = networkService.subscribeToDistributedUptimeMonitors({
+ teamId: user.teamId,
+ limit: 25,
+ types: [
+ typeof import.meta.env.VITE_DEPIN_TESTING === "undefined"
+ ? "distributed_http"
+ : "distributed_test",
+ ],
+ page,
+ rowsPerPage,
+ filter: null,
+ field: null,
+ order: null,
+ onUpdate: (data) => {
+ if (isLoading === true) {
+ setIsLoading(false);
+ }
+ const { count, monitors } = data;
+ const mappedMonitors = monitors.map((monitor) =>
+ getMonitorWithPercentage(monitor, theme)
+ );
+ setMonitors(mappedMonitors);
+ setCount(count?.monitorsCount ?? 0);
+ },
+ onError: () => {
+ setIsLoading(false);
+ setNetworkError(true);
+ },
+ });
+
+ return cleanup;
+ } catch (error) {
+ createToast({
+ body: error.message,
+ });
+ setNetworkError(true);
+ }
+ }, [user, getMonitorWithPercentage, theme, isLoading, page, rowsPerPage]);
+ return [monitors, count, isLoading, networkError];
+};
+export { useSubscribeToDepinMonitors };
diff --git a/client/src/Pages/About/index.jsx b/client/src/Pages/About/index.jsx
new file mode 100644
index 000000000..dcb9d3f43
--- /dev/null
+++ b/client/src/Pages/About/index.jsx
@@ -0,0 +1,18 @@
+import React from 'react';
+import AppBar from '../../Components/Common/AppBar';
+import Footer from '../../Components/Common/Footer';
+import { useTranslation } from "react-i18next";
+
+const AboutUs = () => {
+ const { t } = useTranslation();
+
+ return (
+
+ );
+};
+
+export default AboutUs;
diff --git a/Client/src/Pages/Account/index.css b/client/src/Pages/Account/index.css
similarity index 100%
rename from Client/src/Pages/Account/index.css
rename to client/src/Pages/Account/index.css
diff --git a/client/src/Pages/Account/index.jsx b/client/src/Pages/Account/index.jsx
new file mode 100644
index 000000000..0f17d2d01
--- /dev/null
+++ b/client/src/Pages/Account/index.jsx
@@ -0,0 +1,97 @@
+import { useState } from "react";
+import PropTypes from "prop-types";
+import { useNavigate } from "react-router";
+import { useSelector } from "react-redux";
+import { Box, Tab, useTheme } from "@mui/material";
+import CustomTabList from "../../Components/Tab";
+import TabContext from "@mui/lab/TabContext";
+import ProfilePanel from "../../Components/TabPanels/Account/ProfilePanel";
+import PasswordPanel from "../../Components/TabPanels/Account/PasswordPanel";
+import TeamPanel from "../../Components/TabPanels/Account/TeamPanel";
+import { useTranslation } from "react-i18next";
+import "./index.css";
+
+/**
+ * Account component renders a settings page with tabs for Profile, Password, and Team settings.
+ * @param {string} [props.open] - Specifies the initially open tab: 'profile', 'password', or 'team'.
+ * @returns {JSX.Element}
+ */
+const Account = ({ open = "profile" }) => {
+ const theme = useTheme();
+ const navigate = useNavigate();
+ const [focusedTab, setFocusedTab] = useState(null); // Track focused tab
+ const tab = open;
+ const handleTabChange = (event, newTab) => {
+ navigate(`/account/${newTab}`);
+ };
+ const { user } = useSelector((state) => state.auth);
+ const { t } = useTranslation();
+
+ const requiredRoles = ["superadmin", "admin"];
+ let tabList = [
+ { name: t("menu.profile"), value: "profile" },
+ { name: t("menu.password"), value: "password" },
+ { name: t("menu.team"), value: "team" }
+ ];
+ const hideTeams = !requiredRoles.some((role) => user.role.includes(role));
+ if (hideTeams) {
+ tabList = [
+ { name: t("menu.profile"), value: "profile" },
+ { name: t("menu.password"), value: "password" }
+ ];
+ }
+
+ // Remove password for demo
+ if (user.role.includes("demo")) {
+ tabList = [
+ { name: t("menu.profile"), value: "profile" }
+ ];
+ }
+
+ const handleKeyDown = (event) => {
+ const currentIndex = tabList.findIndex((item) => item.value === tab);
+ if (event.key === "Tab") {
+ const nextIndex = (currentIndex + 1) % tabList.length;
+ setFocusedTab(tabList[nextIndex].value);
+ } else if (event.key === "Enter") {
+ event.preventDefault();
+ navigate(`/account/${focusedTab}`);
+ }
+ };
+
+ const handleFocus = (tabName) => {
+ setFocusedTab(tabName);
+ };
+
+ return (
+
+
+
+ {tabList.map((item, index) => (
+ handleFocus(item.value)}
+ tabIndex={index}
+ />
+ ))}
+
+
+ {user.role.includes("superadmin") && }
+ {!hideTeams && }
+
+
+ );
+};
+
+Account.propTypes = {
+ open: PropTypes.oneOf(["profile", "password", "team"]),
+};
+
+export default Account;
diff --git a/Client/src/Pages/Auth/CheckEmail.jsx b/client/src/Pages/Auth/CheckEmail.jsx
similarity index 90%
rename from Client/src/Pages/Auth/CheckEmail.jsx
rename to client/src/Pages/Auth/CheckEmail.jsx
index 7d7a6af64..695be62b0 100644
--- a/Client/src/Pages/Auth/CheckEmail.jsx
+++ b/client/src/Pages/Auth/CheckEmail.jsx
@@ -5,6 +5,7 @@ import { useDispatch } from "react-redux";
import { useNavigate } from "react-router";
import { createToast } from "../../Utils/toastUtils";
import { forgotPassword } from "../../Features/Auth/authSlice";
+import { useTranslation } from "react-i18next";
import Background from "../../assets/Images/background-grid.svg?react";
import EmailIcon from "../../assets/icons/email.svg?react";
import Logo from "../../assets/icons/checkmate-icon.svg?react";
@@ -15,6 +16,7 @@ const CheckEmail = () => {
const theme = useTheme();
const navigate = useNavigate();
const dispatch = useDispatch();
+ const { t } = useTranslation();
const [email, setEmail] = useState();
const [disabled, setDisabled] = useState(false);
@@ -161,9 +163,9 @@ const CheckEmail = () => {
- Check your email
+ {t("authCheckEmailTitle")}
- We sent a password reset link to{" "}
+ {t("authCheckEmailDescription")}{" "}
{
maxWidth: 400,
}}
>
- Open email app
+ {t("authCheckEmailOpenEmailButton")}
- Didn't receive the email?{" "}
+ {t("authCheckEmailDidntReceiveEmail")}{" "}
- Click to resend
+ {t("authCheckEmailClickToResend")}
@@ -205,15 +207,15 @@ const CheckEmail = () => {
textAlign="center"
p={theme.spacing(12)}
>
- Go back to —
+ {t("goBackTo")}
- Log In
+ {t("authLoginTitle")}
diff --git a/Client/src/Pages/Auth/ForgotPassword.jsx b/client/src/Pages/Auth/ForgotPassword.jsx
similarity index 89%
rename from Client/src/Pages/Auth/ForgotPassword.jsx
rename to client/src/Pages/Auth/ForgotPassword.jsx
index 487a0e5e5..6a31092c9 100644
--- a/Client/src/Pages/Auth/ForgotPassword.jsx
+++ b/client/src/Pages/Auth/ForgotPassword.jsx
@@ -1,4 +1,4 @@
-import { Box, Stack, Typography } from "@mui/material";
+import { Box, Stack, Typography, Button } from "@mui/material";
import { useTheme } from "@emotion/react";
import { createToast } from "../../Utils/toastUtils";
import { useDispatch, useSelector } from "react-redux";
@@ -10,8 +10,8 @@ import TextInput from "../../Components/Inputs/TextInput";
import Logo from "../../assets/icons/checkmate-icon.svg?react";
import Key from "../../assets/icons/key.svg?react";
import Background from "../../assets/Images/background-grid.svg?react";
-import LoadingButton from "@mui/lab/LoadingButton";
import IconBox from "../../Components/IconBox";
+import { useTranslation } from "react-i18next";
import "./index.css";
const ForgotPassword = () => {
@@ -30,6 +30,8 @@ const ForgotPassword = () => {
email && setForm({ email: sessionStorage.getItem("email") });
}, []);
+ const { t } = useTranslation();
+
const handleSubmit = async (event) => {
event.preventDefault();
@@ -163,8 +165,8 @@ const ForgotPassword = () => {
- Forgot password?
- No worries, we'll send you reset instructions.
+ {t("authForgotPasswordTitle")}
+ {t("authForgotPasswordInstructions")}
{
- {
mt: theme.spacing(15),
}}
>
- Send instructions
-
+ {t("continue")}
+
@@ -205,15 +207,15 @@ const ForgotPassword = () => {
textAlign="center"
p={theme.spacing(12)}
>
- Go back to —
+ {t("goBackTo")}
- Log In
+ {t("authLoginTitle")}
diff --git a/Client/src/Pages/Auth/Login/Components/EmailStep.jsx b/client/src/Pages/Auth/Login/Components/EmailStep.jsx
similarity index 78%
rename from Client/src/Pages/Auth/Login/Components/EmailStep.jsx
rename to client/src/Pages/Auth/Login/Components/EmailStep.jsx
index b54f46d12..cea175da3 100644
--- a/Client/src/Pages/Auth/Login/Components/EmailStep.jsx
+++ b/client/src/Pages/Auth/Login/Components/EmailStep.jsx
@@ -3,6 +3,7 @@ import { Box, Button, Stack, Typography } from "@mui/material";
import { useTheme } from "@emotion/react";
import TextInput from "../../../../Components/Inputs/TextInput";
import PropTypes from "prop-types";
+import { useTranslation } from "react-i18next";
/**
* Renders the email step of the login process which includes an email field.
@@ -18,6 +19,7 @@ import PropTypes from "prop-types";
const EmailStep = ({ form, errors, onSubmit, onChange }) => {
const theme = useTheme();
const inputRef = useRef(null);
+ const { t } = useTranslation();
useEffect(() => {
if (inputRef.current) {
@@ -33,8 +35,8 @@ const EmailStep = ({ form, errors, onSubmit, onChange }) => {
position="relative"
>
- Log In
- Enter your email address
+ {t("authLoginTitle")}
+ {t("authLoginEnterEmail")}
{
{
onInput={(e) => (e.target.value = e.target.value.toLowerCase())}
onChange={onChange}
error={errors.email ? true : false}
- helperText={errors.email}
+ helperText={errors.email ? t(errors.email) : ""}
ref={inputRef}
/>
{
color="accent"
type="submit"
disabled={errors.email && true}
+ className="dashboard-style-button"
sx={{
width: "30%",
+ px: theme.spacing(6),
+ borderRadius: `${theme.shape.borderRadius}px !important`,
+ '&.MuiButtonBase-root': {
+ borderRadius: `${theme.shape.borderRadius}px !important`
+ },
+ '&.MuiButton-root': {
+ borderRadius: `${theme.shape.borderRadius}px !important`
+ },
"&.Mui-focusVisible": {
outline: `2px solid ${theme.palette.primary.main}`,
outlineOffset: `2px`,
@@ -77,7 +88,7 @@ const EmailStep = ({ form, errors, onSubmit, onChange }) => {
},
}}
>
- Continue
+ {t("continue")}
diff --git a/Client/src/Pages/Auth/Login/Components/ForgotPasswordLabel.jsx b/client/src/Pages/Auth/Login/Components/ForgotPasswordLabel.jsx
similarity index 78%
rename from Client/src/Pages/Auth/Login/Components/ForgotPasswordLabel.jsx
rename to client/src/Pages/Auth/Login/Components/ForgotPasswordLabel.jsx
index d7a80e5f5..a9cb17d7c 100644
--- a/Client/src/Pages/Auth/Login/Components/ForgotPasswordLabel.jsx
+++ b/client/src/Pages/Auth/Login/Components/ForgotPasswordLabel.jsx
@@ -1,10 +1,12 @@
import { Box, Typography, useTheme } from "@mui/material";
import PropTypes from "prop-types";
import { useNavigate } from "react-router";
+import { useTranslation } from "react-i18next";
const ForgotPasswordLabel = ({ email, errorEmail }) => {
const theme = useTheme();
const navigate = useNavigate();
+ const { t } = useTranslation();
const handleNavigate = () => {
if (email !== "" && !errorEmail) {
@@ -20,7 +22,7 @@ const ForgotPasswordLabel = ({ email, errorEmail }) => {
display="inline-block"
color={theme.palette.primary.main}
>
- Forgot password?
+ {t("authForgotPasswordTitle")}
{
sx={{ userSelect: "none" }}
onClick={handleNavigate}
>
- Reset password
+ {t("authForgotPasswordResetPassword")}
);
};
-ForgotPasswordLabel.proptype = {
+ForgotPasswordLabel.propTypes = {
email: PropTypes.string.isRequired,
- emailError: PropTypes.string.isRequired,
+ errorEmail: PropTypes.string.isRequired,
};
export default ForgotPasswordLabel;
diff --git a/Client/src/Pages/Auth/Login/Components/PasswordStep.jsx b/client/src/Pages/Auth/Login/Components/PasswordStep.jsx
similarity index 75%
rename from Client/src/Pages/Auth/Login/Components/PasswordStep.jsx
rename to client/src/Pages/Auth/Login/Components/PasswordStep.jsx
index 10ded02f5..a57246e23 100644
--- a/Client/src/Pages/Auth/Login/Components/PasswordStep.jsx
+++ b/client/src/Pages/Auth/Login/Components/PasswordStep.jsx
@@ -1,13 +1,12 @@
import { useRef, useEffect } from "react";
import { Box, Button, Stack, Typography } from "@mui/material";
import { useTheme } from "@emotion/react";
-import LoadingButton from "@mui/lab/LoadingButton";
import { useSelector } from "react-redux";
import TextInput from "../../../../Components/Inputs/TextInput";
import { PasswordEndAdornment } from "../../../../Components/Inputs/TextInput/Adornments";
import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";
import PropTypes from "prop-types";
-
+import { useTranslation } from "react-i18next";
/**
* Renders the password step of the login process, including a password input field.
*
@@ -23,6 +22,7 @@ const PasswordStep = ({ form, errors, onSubmit, onChange, onBack }) => {
const theme = useTheme();
const inputRef = useRef(null);
const authState = useSelector((state) => state.auth);
+ const { t } = useTranslation();
useEffect(() => {
if (inputRef.current) {
@@ -38,8 +38,8 @@ const PasswordStep = ({ form, errors, onSubmit, onChange, onBack }) => {
textAlign="center"
>
- Log In
- Enter your password
+ {t("authLoginTitle")}
+ {t("authLoginEnterPassword")}
{
{
variant="outlined"
color="info"
onClick={onBack}
+ className="dashboard-style-button"
sx={{
px: theme.spacing(5),
+ borderRadius: `${theme.shape.borderRadius}px !important`,
+ '&.MuiButtonBase-root': {
+ borderRadius: `${theme.shape.borderRadius}px !important`
+ },
+ '&.MuiButton-root': {
+ borderRadius: `${theme.shape.borderRadius}px !important`
+ },
"& svg.MuiSvgIcon-root": {
mr: theme.spacing(3),
},
@@ -87,25 +95,34 @@ const PasswordStep = ({ form, errors, onSubmit, onChange, onBack }) => {
}}
>
- Back
+ {t("commonBack")}{" "}
-
- Continue
-
+ {t("continue")}
+
diff --git a/Client/src/Pages/Auth/Login/Login.jsx b/client/src/Pages/Auth/Login/Login.jsx
similarity index 72%
rename from Client/src/Pages/Auth/Login/Login.jsx
rename to client/src/Pages/Auth/Login/Login.jsx
index 30743c60c..8ac831a40 100644
--- a/Client/src/Pages/Auth/Login/Login.jsx
+++ b/client/src/Pages/Auth/Login/Login.jsx
@@ -9,12 +9,13 @@ import { createToast } from "../../../Utils/toastUtils";
import { networkService } from "../../../main";
import Background from "../../../assets/Images/background-grid.svg?react";
import Logo from "../../../assets/icons/checkmate-icon.svg?react";
-import { logger } from "../../../Utils/Logger";
import "../index.css";
import EmailStep from "./Components/EmailStep";
import PasswordStep from "./Components/PasswordStep";
import ThemeSwitch from "../../../Components/ThemeSwitch";
import ForgotPasswordLabel from "./Components/ForgotPasswordLabel";
+import LanguageSelector from "../../../Components/LanguageSelector";
+import { useTranslation } from "react-i18next";
const DEMO = import.meta.env.VITE_APP_DEMO;
@@ -23,10 +24,10 @@ const DEMO = import.meta.env.VITE_APP_DEMO;
*/
const Login = () => {
- const dispatch = useDispatch();
- const navigate = useNavigate();
const theme = useTheme();
-
+ const dispatch = useDispatch();
+ const { t } = useTranslation();
+ const navigate = useNavigate();
const authState = useSelector((state) => state.auth);
const { authToken } = authState;
@@ -42,32 +43,28 @@ const Login = () => {
const [errors, setErrors] = useState({});
const [step, setStep] = useState(0);
+
+
useEffect(() => {
if (authToken) {
navigate("/uptime");
- return;
}
- networkService
- .doesSuperAdminExist()
- .then((response) => {
- if (response.data.data === false) {
- navigate("/register");
- }
- })
- .catch((error) => {
- logger.error(error);
- });
}, [authToken, navigate]);
const handleChange = (event) => {
const { value, id } = event.target;
const name = idMap[id];
+ const lowerCasedValue =
+ name === idMap["login-email-input"] ? value?.toLowerCase() || value : value;
setForm((prev) => ({
...prev,
- [name]: value,
+ [name]: lowerCasedValue,
}));
- const { error } = credentials.validate({ [name]: value }, { abortEarly: false });
+ const { error } = credentials.validate(
+ { [name]: lowerCasedValue },
+ { abortEarly: false }
+ );
setErrors((prev) => {
const prevErrors = { ...prev };
@@ -86,8 +83,10 @@ const Login = () => {
{ abortEarly: false }
);
if (error) {
- setErrors((prev) => ({ ...prev, email: error.details[0].message }));
- createToast({ body: error.details[0].message });
+ const errorMessage = error.details[0].message;
+ const translatedMessage = errorMessage.startsWith('auth') ? t(errorMessage) : errorMessage;
+ setErrors((prev) => ({ ...prev, email: translatedMessage }));
+ createToast({ body: translatedMessage });
} else {
setStep(1);
}
@@ -104,15 +103,15 @@ const Login = () => {
createToast({
body:
error.details && error.details.length > 0
- ? error.details[0].message
- : "Error validating data.",
+ ? (error.details[0].message.startsWith('auth') ? t(error.details[0].message) : error.details[0].message)
+ : t("Error validating data."),
});
} else {
const action = await dispatch(login(form));
if (action.payload.success) {
navigate("/uptime");
createToast({
- body: "Welcome back! You're successfully logged in.",
+ body: t("welcomeBack"),
});
} else {
if (action.payload) {
@@ -141,7 +140,7 @@ const Login = () => {
overflow="hidden"
sx={{
"& h1": {
- color: theme.palette.primary.main,
+ color: theme.palette.primary.contrastText,
fontWeight: 600,
fontSize: 28,
},
@@ -163,11 +162,26 @@ const Login = () => {
-
- Checkmate
+
+
+ Checkmate
+
+
+
+
+
{
email={form.email}
errorEmail={errors.email}
/>
-
-
+
+ {/* Registration link */}
+
+
+ {t("doNotHaveAccount")}
+
+ navigate("/register")}
+ >
+ {t("registerHere")}
+
diff --git a/Client/src/Pages/Auth/NewPasswordConfirmed.jsx b/client/src/Pages/Auth/NewPasswordConfirmed.jsx
similarity index 90%
rename from Client/src/Pages/Auth/NewPasswordConfirmed.jsx
rename to client/src/Pages/Auth/NewPasswordConfirmed.jsx
index 6258e0fa5..9c7734083 100644
--- a/Client/src/Pages/Auth/NewPasswordConfirmed.jsx
+++ b/client/src/Pages/Auth/NewPasswordConfirmed.jsx
@@ -8,12 +8,14 @@ import Background from "../../assets/Images/background-grid.svg?react";
import ConfirmIcon from "../../assets/icons/check-outlined.svg?react";
import Logo from "../../assets/icons/checkmate-icon.svg?react";
import IconBox from "../../Components/IconBox";
+import { useTranslation } from "react-i18next";
import "./index.css";
const NewPasswordConfirmed = () => {
const theme = useTheme();
const navigate = useNavigate();
const dispatch = useDispatch();
+ const { t } = useTranslation();
const handleNavigate = () => {
dispatch(clearAuthState());
@@ -97,9 +99,9 @@ const NewPasswordConfirmed = () => {
- Password reset
+ {t("passwordreset")}
- Your password has been successfully reset. Click below to log in magically.
+ {t("authNewPasswordConfirmed")}
{
maxWidth: 400,
}}
>
- Continue
+ {t("continue")}
@@ -118,15 +120,15 @@ const NewPasswordConfirmed = () => {
textAlign="center"
p={theme.spacing(12)}
>
- Go back to —
+ {t("goBackTo")}
- Log In
+ {t("authLoginTitle")}
diff --git a/Client/src/Pages/Auth/Register/Register.jsx b/client/src/Pages/Auth/Register/Register.jsx
similarity index 81%
rename from Client/src/Pages/Auth/Register/Register.jsx
rename to client/src/Pages/Auth/Register/Register.jsx
index 9e8248cf8..8017f306d 100644
--- a/Client/src/Pages/Auth/Register/Register.jsx
+++ b/client/src/Pages/Auth/Register/Register.jsx
@@ -15,7 +15,7 @@ import Background from "../../../assets/Images/background-grid.svg?react";
import Logo from "../../../assets/icons/checkmate-icon.svg?react";
import Mail from "../../../assets/icons/mail.svg?react";
import "../index.css";
-
+import { useTranslation, Trans } from "react-i18next";
/**
* Displays the initial landing page.
*
@@ -26,7 +26,7 @@ import "../index.css";
*/
const LandingPage = ({ isSuperAdmin, onSignup }) => {
const theme = useTheme();
-
+ const { t } = useTranslation();
return (
<>
{
textAlign="center"
>
- Sign Up
+ {t("signUp")}
- Create your {isSuperAdmin ? "Super admin " : ""}account to get started.
+ {isSuperAdmin
+ ? t("authRegisterCreateSuperAdminAccount")
+ : t("authRegisterCreateAccount")}
@@ -60,47 +62,52 @@ const LandingPage = ({ isSuperAdmin, onSignup }) => {
}}
>
- Sign up with Email
+ {t("authRegisterSignUpWithEmail")}
- By signing up, you agree to our{" "}
- {
- window.open(
- "https://bluewavelabs.ca/terms-of-service-open-source",
- "_blank",
- "noreferrer"
- );
+ {
+ window.open(
+ "https://bluewavelabs.ca/terms-of-service-open-source",
+ "_blank",
+ "noreferrer"
+ );
+ }}
+ />
+ ),
+ a2: (
+ {
+ window.open(
+ "https://bluewavelabs.ca/privacy-policy-open-source",
+ "_blank",
+ "noreferrer"
+ );
+ }}
+ />
+ )
}}
- sx={{
- "&:hover": {
- color: theme.palette.primary.contrastTextTertiary,
- },
- }}
- >
- Terms of Service
- {" "}
- and{" "}
- {
- window.open(
- "https://bluewavelabs.ca/privacy-policy-open-source",
- "_blank",
- "noreferrer"
- );
- }}
- sx={{
- "&:hover": {
- color: theme.palette.primary.contrastTextTertiary,
- },
- }}
- >
- Privacy Policy.
-
+ />
@@ -118,6 +125,7 @@ const Register = ({ isSuperAdmin }) => {
const navigate = useNavigate();
const { token } = useParams();
const theme = useTheme();
+ const { t } = useTranslation();
// TODO If possible, change the IDs of these fields to match the backend
const idMap = {
"register-firstname-input": "firstName",
@@ -145,8 +153,8 @@ const Register = ({ isSuperAdmin }) => {
try {
const res = await networkService.verifyInvitationToken(token);
const invite = res.data.data;
- const { role, email, teamId } = invite;
- setForm({ ...form, email, role, teamId });
+ const { email } = invite;
+ setForm({ ...form, email });
} catch (error) {
navigate("/register", { replace: true });
}
@@ -236,7 +244,6 @@ const Register = ({ isSuperAdmin }) => {
const action = await dispatch(register(registerForm));
if (action.payload.success) {
const authToken = action.payload.data;
- localStorage.setItem("token", authToken);
navigate("/uptime");
createToast({
body: "Welcome! Your account was created successfully.",
@@ -257,13 +264,15 @@ const Register = ({ isSuperAdmin }) => {
const handleChange = (event) => {
const { value, id } = event.target;
const name = idMap[id];
+ const lowerCasedValue =
+ name === idMap["register-email-input"] ? value?.toLowerCase() || value : value;
setForm((prev) => ({
...prev,
- [name]: value,
+ [name]: lowerCasedValue,
}));
const { error } = credentials.validate(
- { [name]: value },
+ { [name]: lowerCasedValue },
{ abortEarly: false, context: { password: form.password } }
);
@@ -281,7 +290,7 @@ const Register = ({ isSuperAdmin }) => {
overflow="hidden"
sx={{
"& h1": {
- color: theme.palette.primary.main,
+ color: theme.palette.primary.contrastText,
fontWeight: 600,
fontSize: 28,
},
@@ -307,7 +316,7 @@ const Register = ({ isSuperAdmin }) => {
gap={theme.spacing(4)}
>
- Checkmate
+ {t("commonAppName")}
{
textAlign="center"
p={theme.spacing(12)}
>
- Already have an account? —
+
+ {t("authRegisterAlreadyHaveAccount")}
+
{
navigate("/login");
}}
- sx={{ userSelect: "none", color: theme.palette.primary.main }}
+ sx={{ userSelect: "none", color: theme.palette.accent.main }}
>
- Log In
+ {t("authRegisterLoginLink")}
diff --git a/Client/src/Pages/Auth/Register/StepOne/index.jsx b/client/src/Pages/Auth/Register/StepOne/index.jsx
similarity index 90%
rename from Client/src/Pages/Auth/Register/StepOne/index.jsx
rename to client/src/Pages/Auth/Register/StepOne/index.jsx
index 42e547b62..cb66f6704 100644
--- a/Client/src/Pages/Auth/Register/StepOne/index.jsx
+++ b/client/src/Pages/Auth/Register/StepOne/index.jsx
@@ -4,6 +4,7 @@ import { useTheme } from "@emotion/react";
import { Box, Button, Stack, Typography } from "@mui/material";
import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";
import TextInput from "../../../../Components/Inputs/TextInput";
+import { useTranslation } from "react-i18next";
StepOne.propTypes = {
form: PropTypes.object,
@@ -28,6 +29,7 @@ StepOne.propTypes = {
function StepOne({ form, errors, onSubmit, onChange, onBack }) {
const theme = useTheme();
const inputRef = useRef(null);
+ const { t } = useTranslation();
useEffect(() => {
if (inputRef.current) {
@@ -43,8 +45,8 @@ function StepOne({ form, errors, onSubmit, onChange, onBack }) {
textAlign="center"
>
- Sign Up
- Enter your personal details
+ {t("signUp")}
+ {t("authRegisterStepOnePersonalDetails")}
- Back
+ {t("commonBack")}
- Continue
+ {t("continue")}
diff --git a/Client/src/Pages/Auth/Register/StepThree/index.jsx b/client/src/Pages/Auth/Register/StepThree/index.jsx
similarity index 77%
rename from Client/src/Pages/Auth/Register/StepThree/index.jsx
rename to client/src/Pages/Auth/Register/StepThree/index.jsx
index 6221a8ef1..1af8a60dc 100644
--- a/Client/src/Pages/Auth/Register/StepThree/index.jsx
+++ b/client/src/Pages/Auth/Register/StepThree/index.jsx
@@ -6,7 +6,7 @@ import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";
import TextInput from "../../../../Components/Inputs/TextInput";
import Check from "../../../../Components/Check/Check";
import { useValidatePassword } from "../../hooks/useValidatePassword";
-
+import { useTranslation } from "react-i18next";
StepThree.propTypes = {
onSubmit: PropTypes.func,
onBack: PropTypes.func,
@@ -23,6 +23,7 @@ StepThree.propTypes = {
function StepThree({ onSubmit, onBack }) {
const theme = useTheme();
const inputRef = useRef(null);
+ const { t } = useTranslation();
useEffect(() => {
if (inputRef.current) {
@@ -38,8 +39,8 @@ function StepThree({ onSubmit, onBack }) {
textAlign="center"
>
- Sign Up
- Create your password
+ {t("signUp")}
+ {t("createPassword")}
@@ -140,7 +141,7 @@ function StepThree({ onSubmit, onBack }) {
}}
>
- Back
+ {t("commonBack")}
- Continue
+ {t("continue")}
diff --git a/Client/src/Pages/Auth/Register/StepTwo/index.jsx b/client/src/Pages/Auth/Register/StepTwo/index.jsx
similarity index 85%
rename from Client/src/Pages/Auth/Register/StepTwo/index.jsx
rename to client/src/Pages/Auth/Register/StepTwo/index.jsx
index da247cdf9..a53e21575 100644
--- a/Client/src/Pages/Auth/Register/StepTwo/index.jsx
+++ b/client/src/Pages/Auth/Register/StepTwo/index.jsx
@@ -4,6 +4,7 @@ import { useTheme } from "@emotion/react";
import { Box, Button, Stack, Typography } from "@mui/material";
import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";
import TextInput from "../../../../Components/Inputs/TextInput";
+import { useTranslation } from "react-i18next";
StepTwo.propTypes = {
form: PropTypes.object,
@@ -27,6 +28,7 @@ StepTwo.propTypes = {
function StepTwo({ form, errors, onSubmit, onChange, onBack }) {
const theme = useTheme();
const inputRef = useRef(null);
+ const { t } = useTranslation();
useEffect(() => {
if (inputRef.current) {
@@ -41,8 +43,8 @@ function StepTwo({ form, errors, onSubmit, onChange, onBack }) {
textAlign="center"
>
- Sign Up
- Enter your email address
+ {t("signUp")}
+ {t("enterEmail")}
(e.target.value = e.target.value.toLowerCase())}
onChange={onChange}
error={errors.email ? true : false}
- helperText={errors.email}
+ helperText={errors.email && (
+ errors.email.includes("required") ? t("authRegisterEmailRequired") :
+ errors.email.includes("valid email") ? t("authRegisterEmailInvalid") :
+ t(errors.email)
+ )}
ref={inputRef}
/>
- Back
+ {t("commonBack")}
- Continue
+ {t("continue")}
diff --git a/Client/src/Pages/Auth/SetNewPassword.jsx b/client/src/Pages/Auth/SetNewPassword.jsx
similarity index 82%
rename from Client/src/Pages/Auth/SetNewPassword.jsx
rename to client/src/Pages/Auth/SetNewPassword.jsx
index a4c3b0a5a..4467a4adf 100644
--- a/Client/src/Pages/Auth/SetNewPassword.jsx
+++ b/client/src/Pages/Auth/SetNewPassword.jsx
@@ -3,8 +3,7 @@ import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { useParams } from "react-router-dom";
import { useTheme } from "@emotion/react";
-import { Box, Stack, Typography } from "@mui/material";
-import LoadingButton from "@mui/lab/LoadingButton";
+import { Box, Stack, Typography, Button } from "@mui/material";
import { setNewPassword } from "../../Features/Auth/authSlice";
import { createToast } from "../../Utils/toastUtils";
import { credentials } from "../../Validation/validation";
@@ -17,11 +16,13 @@ import Logo from "../../assets/icons/checkmate-icon.svg?react";
import Background from "../../assets/Images/background-grid.svg?react";
import "./index.css";
import { useValidatePassword } from "./hooks/useValidatePassword";
+import { useTranslation } from "react-i18next";
const SetNewPassword = () => {
const navigate = useNavigate();
const dispatch = useDispatch();
const theme = useTheme();
+ const { t } = useTranslation();
const passwordId = useId();
const confirmPasswordId = useId();
@@ -97,7 +98,7 @@ const SetNewPassword = () => {
gap={theme.spacing(4)}
>
- Checkmate
+ {t("commonAppName")}
{
- Set new password
-
- Your new password must be different to previously used passwords.
-
+ {t("authSetNewPasswordTitle")}
+ {t("authSetNewPasswordDescription")}
{
id={passwordId}
type="password"
name="password"
- label="Password"
+ label={t("commonPassword")}
isRequired={true}
placeholder="••••••••"
value={form.password}
@@ -186,7 +185,7 @@ const SetNewPassword = () => {
id={confirmPasswordId}
type="password"
name="confirm"
- label="Confirm password"
+ label={t("authSetNewPasswordConfirmPassword")}
isRequired={true}
placeholder="••••••••"
value={form.confirm}
@@ -201,38 +200,38 @@ const SetNewPassword = () => {
mb={theme.spacing(12)}
>
- {
}
sx={{ width: "100%", maxWidth: 400 }}
>
- Reset password
-
+ {t("authSetNewPasswordResetPassword")}
+
- Go back to —
+ {t("goBackTo")} —
{
onClick={() => navigate("/login")}
sx={{ userSelect: "none" }}
>
- Log In
+ {t("authLoginTitle")}
diff --git a/Client/src/Pages/Auth/hooks/useValidatePassword.jsx b/client/src/Pages/Auth/hooks/useValidatePassword.jsx
similarity index 100%
rename from Client/src/Pages/Auth/hooks/useValidatePassword.jsx
rename to client/src/Pages/Auth/hooks/useValidatePassword.jsx
diff --git a/Client/src/Pages/Auth/index.css b/client/src/Pages/Auth/index.css
similarity index 91%
rename from Client/src/Pages/Auth/index.css
rename to client/src/Pages/Auth/index.css
index b0a76b748..86ab05c13 100644
--- a/Client/src/Pages/Auth/index.css
+++ b/client/src/Pages/Auth/index.css
@@ -32,10 +32,6 @@
border-radius: var(--env-var-radius-2);
line-height: 1;
}
-.auth button:not(.MuiIconButton-root),
-.auth .field .MuiInputBase-root:has(input) {
- height: 38px;
-}
.auth .field svg {
width: 24px;
height: 24px;
@@ -91,10 +87,6 @@
.auth span {
font-size: var(--env-var-font-size-medium);
}
- .auth button:not(.MuiIconButton-root),
- .auth .field .MuiInputBase-root:has(input) {
- height: 36px;
- }
.auth .check span.MuiTypography-root,
.auth .field .input-error,
.auth .field h3.MuiTypography-root {
diff --git a/client/src/Pages/DistributedUptime/Create/Hooks/useCreateDistributedUptimeMonitor.jsx b/client/src/Pages/DistributedUptime/Create/Hooks/useCreateDistributedUptimeMonitor.jsx
new file mode 100644
index 000000000..b2634e9a7
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Create/Hooks/useCreateDistributedUptimeMonitor.jsx
@@ -0,0 +1,31 @@
+import { useState } from "react";
+import { networkService } from "../../../../main";
+import { useSelector } from "react-redux";
+import { createToast } from "../../../../Utils/toastUtils";
+
+const useCreateDistributedUptimeMonitor = ({ isCreate, monitorId }) => {
+ const [isLoading, setIsLoading] = useState(false);
+ const [networkError, setNetworkError] = useState(false);
+ const createDistributedUptimeMonitor = async ({ form }) => {
+ setIsLoading(true);
+ try {
+ if (isCreate) {
+ await networkService.createMonitor({ monitor: form });
+ } else {
+ await networkService.updateMonitor({ monitor: form, monitorId });
+ }
+
+ return true;
+ } catch (error) {
+ setNetworkError(true);
+ createToast({ body: error?.response?.data?.msg ?? error.message });
+ return false;
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return [createDistributedUptimeMonitor, isLoading, networkError];
+};
+
+export { useCreateDistributedUptimeMonitor };
diff --git a/client/src/Pages/DistributedUptime/Create/Hooks/useMonitorFetch.jsx b/client/src/Pages/DistributedUptime/Create/Hooks/useMonitorFetch.jsx
new file mode 100644
index 000000000..efffbe437
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Create/Hooks/useMonitorFetch.jsx
@@ -0,0 +1,31 @@
+import { useEffect, useState } from "react";
+import { networkService } from "../../../../main";
+import { createToast } from "../../../../Utils/toastUtils";
+
+export const useMonitorFetch = ({ monitorId, isCreate }) => {
+ const [networkError, setNetworkError] = useState(false);
+ const [isLoading, setIsLoading] = useState(true);
+ const [monitor, setMonitor] = useState(undefined);
+
+ useEffect(() => {
+ const fetchMonitors = async () => {
+ try {
+ if (isCreate) return;
+ const res = await networkService.getUptimeDetailsById({
+ monitorId: monitorId,
+ normalize: true,
+ });
+ setMonitor(res?.data?.data ?? {});
+ } catch (error) {
+ setNetworkError(true);
+ createToast({ body: error.message });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+ fetchMonitors();
+ }, [monitorId, isCreate]);
+ return [monitor, isLoading, networkError];
+};
+
+export default useMonitorFetch;
diff --git a/client/src/Pages/DistributedUptime/Create/index.jsx b/client/src/Pages/DistributedUptime/Create/index.jsx
new file mode 100644
index 000000000..458aa011f
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Create/index.jsx
@@ -0,0 +1,347 @@
+// Components
+import { Box, Stack, Typography, Button, ButtonGroup } from "@mui/material";
+
+import Breadcrumbs from "../../../Components/Breadcrumbs";
+import ConfigBox from "../../../Components/ConfigBox";
+import TextInput from "../../../Components/Inputs/TextInput";
+import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments";
+import Radio from "../../../Components/Inputs/Radio";
+import Checkbox from "../../../Components/Inputs/Checkbox";
+import Select from "../../../Components/Inputs/Select";
+import { createToast } from "../../../Utils/toastUtils";
+
+// Utility
+import { useTheme } from "@emotion/react";
+import { useState, useEffect } from "react";
+import { useNavigate } from "react-router-dom";
+import { useSelector } from "react-redux";
+import { monitorValidation } from "../../../Validation/validation";
+import { useParams } from "react-router-dom";
+import { useCreateDistributedUptimeMonitor } from "./Hooks/useCreateDistributedUptimeMonitor";
+import { useMonitorFetch } from "./Hooks/useMonitorFetch";
+import { useTranslation } from "react-i18next";
+
+// Constants
+const MS_PER_MINUTE = 60000;
+const SELECT_VALUES = [
+ { _id: 1, name: "1 minute" },
+ { _id: 2, name: "2 minutes" },
+ { _id: 3, name: "3 minutes" },
+ { _id: 4, name: "4 minutes" },
+ { _id: 5, name: "5 minutes" },
+];
+
+const parseUrl = (url) => {
+ try {
+ return new URL(url);
+ } catch (error) {
+ return null;
+ }
+};
+
+const CreateDistributedUptime = () => {
+ const { monitorId } = useParams();
+ const isCreate = typeof monitorId === "undefined";
+ const { t } = useTranslation();
+
+ let BREADCRUMBS = [
+ { name: `distributed uptime`, path: "/distributed-uptime" },
+ ...(isCreate ? [] : [{ name: "details", path: `/distributed-uptime/${monitorId}` }]),
+ { name: isCreate ? "create" : "configure", path: `` },
+ ];
+
+ // Redux state
+ const { user } = useSelector((state) => state.auth);
+
+ // Local state
+ const [https, setHttps] = useState(true);
+ const [notifications, setNotifications] = useState([]);
+ const [form, setForm] = useState({
+ type: "distributed_http",
+ name: "",
+ url: "",
+ interval: 1,
+ });
+ const [errors, setErrors] = useState({});
+
+ //utils
+ const theme = useTheme();
+ const navigate = useNavigate();
+ const [createDistributedUptimeMonitor, isLoading, networkError] =
+ useCreateDistributedUptimeMonitor({ isCreate, monitorId });
+
+ const [monitor, monitorIsLoading, monitorNetworkError] = useMonitorFetch({
+ monitorId,
+ isCreate,
+ });
+
+ // Effect to set monitor to fetched monitor
+ useEffect(() => {
+ if (typeof monitor !== "undefined") {
+ const parsedUrl = parseUrl(monitor?.url);
+ const protocol = parsedUrl?.protocol?.replace(":", "") || "";
+ setHttps(protocol === "https");
+
+ const newForm = {
+ name: monitor.name,
+ interval: monitor.interval / MS_PER_MINUTE,
+ url: parsedUrl.host,
+ type: monitor.type,
+ };
+
+ setForm(newForm);
+ }
+ }, [monitor]);
+
+ // Handlers
+ const handleCreateMonitor = async () => {
+ const monitorToSubmit = { ...form };
+
+ // Prepend protocol to url
+ monitorToSubmit.url = `http${https ? "s" : ""}://` + monitorToSubmit.url;
+
+ const { error } = monitorValidation.validate(monitorToSubmit, {
+ abortEarly: false,
+ });
+ if (error) {
+ const newErrors = {};
+ error.details.forEach((err) => {
+ newErrors[err.path[0]] = err.message;
+ });
+ setErrors(newErrors);
+ createToast({ body: "Please check the form for errors." });
+ return;
+ }
+
+ // Append needed fields
+ monitorToSubmit.description = form.name;
+ monitorToSubmit.interval = form.interval * MS_PER_MINUTE;
+ monitorToSubmit.teamId = user.teamId;
+ monitorToSubmit.userId = user._id;
+ monitorToSubmit.notifications = notifications;
+
+ const success = await createDistributedUptimeMonitor({ form: monitorToSubmit });
+ if (success) {
+ createToast({ body: "Monitor created successfully!" });
+ navigate("/distributed-uptime");
+ } else {
+ createToast({ body: "Failed to create monitor." });
+ }
+ };
+
+ const handleChange = (event) => {
+ let { name, value } = event.target;
+
+ setForm({
+ ...form,
+ [name]: value,
+ });
+ const { error } = monitorValidation.validate(
+ { [name]: value },
+ { abortEarly: false }
+ );
+ setErrors((prev) => ({
+ ...prev,
+ ...(error ? { [name]: error.details[0].message } : { [name]: undefined }),
+ }));
+ };
+
+ const handleNotifications = (event, type) => {
+ const { value } = event.target;
+ let currentNotifications = [...notifications];
+ const notificationAlreadyExists = notifications.some((notification) => {
+ if (notification.type === type && notification.address === value) {
+ return true;
+ }
+ return false;
+ });
+ if (notificationAlreadyExists) {
+ currentNotifications = currentNotifications.filter((notification) => {
+ if (notification.type === type && notification.address === value) {
+ return false;
+ }
+ return true;
+ });
+ } else {
+ currentNotifications.push({ type, address: value });
+ }
+ setNotifications(currentNotifications);
+ };
+
+ return (
+
+
+ console.log("submit")}
+ >
+
+
+ {isCreate ? "Create your" : "Edit your"}{" "}
+
+
+ {t("monitor")}
+
+
+
+
+ {t("settingsGeneralSettings")}
+
+ {t("distributedUptimeCreateSelectURL")}
+
+
+
+ }
+ label="URL to monitor"
+ https={https}
+ placeholder={"www.google.com"}
+ disabled={!isCreate}
+ value={form.url}
+ name="url"
+ onChange={handleChange}
+ error={errors["url"] ? true : false}
+ helperText={errors["url"]}
+ />
+
+
+
+
+
+ {t("distributedUptimeCreateChecks")}
+
+ {t("distributedUptimeCreateChecksDescription")}
+
+
+
+
+
+ {form.type === "http" || form.type === "distributed_http" ? (
+
+ setHttps(true)}
+ >
+ {t("https")}
+
+ setHttps(false)}
+ >
+ {t("http")}
+
+
+ ) : (
+ ""
+ )}
+
+
+ {errors["type"] ? (
+
+
+ {errors["type"]}
+
+
+ ) : (
+ ""
+ )}
+
+
+
+
+ {t("distributedUptimeCreateIncidentNotification")}
+
+ {t("distributedUptimeCreateIncidentDescription")}
+
+
+
+ notification.type === "email"
+ )}
+ value={user?.email}
+ onChange={(event) => handleNotifications(event, "email")}
+ />
+
+
+
+
+ {t("distributedUptimeCreateAdvancedSettings")}
+
+
+
+
+
+
+ handleCreateMonitor()}
+ disabled={!Object.values(errors).every((value) => value === undefined)}
+ loading={isLoading}
+ >
+ {isCreate ? "Create monitor" : "Configure monitor"}
+
+
+
+
+ );
+};
+
+export default CreateDistributedUptime;
diff --git a/client/src/Pages/DistributedUptime/Details/Components/Chatbot/index.jsx b/client/src/Pages/DistributedUptime/Details/Components/Chatbot/index.jsx
new file mode 100644
index 000000000..899c0fcc3
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/Chatbot/index.jsx
@@ -0,0 +1,50 @@
+// Components
+import { Stack, Typography } from "@mui/material";
+import { ColContainer } from "../../../../../Components/StandardContainer";
+import SmartToyIcon from "@mui/icons-material/SmartToy";
+import Dot from "../../../../../Components/Dot";
+// Utils
+import { useTheme } from "@emotion/react";
+import { useTranslation } from "react-i18next";
+
+const MESSAGES = [
+ "I've checked the network status, and we're seeing excellent performance across all regions.",
+ "The network is stable and functioning optimally. All connections are active and stable.",
+ "I've reviewed the network status, and everything looks great. No issues detected.",
+ "The network is up and running smoothly. All connections are active and stable.",
+ "I've checked the network status, and everything is looking good. No issues detected.",
+];
+
+const ChatBot = ({ sx }) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ return (
+
+
+
+ Status Bot
+
+
+ {t("now")}
+
+
+ {MESSAGES[Math.floor(Math.random() * MESSAGES.length)]}
+
+ );
+};
+
+export default ChatBot;
diff --git a/client/src/Pages/DistributedUptime/Details/Components/ControlsHeader/index.jsx b/client/src/Pages/DistributedUptime/Details/Components/ControlsHeader/index.jsx
new file mode 100644
index 000000000..e9b42c4b9
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/ControlsHeader/index.jsx
@@ -0,0 +1,92 @@
+// Components
+import { Box, Stack, Button } from "@mui/material";
+import Image from "../../../../../Components/Image";
+import SettingsIcon from "../../../../../assets/icons/settings-bold.svg?react";
+
+//Utils
+import { useTheme } from "@mui/material/styles";
+import { useNavigate } from "react-router-dom";
+import PropTypes from "prop-types";
+import { useTranslation } from "react-i18next";
+
+const Controls = ({ isDeleteOpen, setIsDeleteOpen, isDeleting, monitorId }) => {
+ const theme = useTheme();
+ const navigate = useNavigate();
+ const { t } = useTranslation();
+
+ return (
+
+
+ setIsDeleteOpen(!isDeleteOpen)}
+ loading={isDeleting}
+ >
+ {t("delete")}
+
+
+
+ {
+ navigate(`/distributed-uptime/configure/${monitorId}`);
+ }}
+ sx={{
+ px: theme.spacing(5),
+ "& svg": {
+ mr: theme.spacing(3),
+ "& path": {
+ stroke: theme.palette.secondary.contrastText,
+ },
+ },
+ }}
+ >
+ {t("configure")}
+
+
+
+ );
+};
+
+Controls.propTypes = {
+ isDeleting: PropTypes.bool,
+ monitorId: PropTypes.string,
+ isDeleteOpen: PropTypes.bool.isRequired,
+ setIsDeleteOpen: PropTypes.func.isRequired,
+};
+
+const ControlsHeader = ({ isDeleting, isDeleteOpen, setIsDeleteOpen, monitorId }) => {
+ const theme = useTheme();
+
+ return (
+
+
+
+ );
+};
+
+ControlsHeader.propTypes = {
+ monitorId: PropTypes.string,
+ isDeleting: PropTypes.bool,
+ isDeleteOpen: PropTypes.bool.isRequired,
+ setIsDeleteOpen: PropTypes.func.isRequired,
+};
+
+export default ControlsHeader;
diff --git a/client/src/Pages/DistributedUptime/Details/Components/DeviceTicker/index.jsx b/client/src/Pages/DistributedUptime/Details/Components/DeviceTicker/index.jsx
new file mode 100644
index 000000000..4afba9e52
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/DeviceTicker/index.jsx
@@ -0,0 +1,96 @@
+// Components
+import { Stack, Typography } from "@mui/material";
+import PulseDot from "../../../../../Components/Animated/PulseDot";
+import "flag-icons/css/flag-icons.min.css";
+import { ColContainer } from "../../../../../Components/StandardContainer";
+
+// Utils
+import { useTheme } from "@emotion/react";
+import { useTranslation } from "react-i18next";
+
+const DeviceTicker = ({ data, width = "100%", connectionStatus }) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ const statusColor = {
+ up: theme.palette.success.main,
+ down: theme.palette.error.main,
+ undefined: theme.palette.warning.main,
+ };
+
+ return (
+
+
+
+
+
+ {connectionStatus === "up" ? "Connected" : "Connecting..."}
+
+
+
+
+
+
+
+ {t("country")}
+
+
+ {t("city")}
+
+
+ {t("response")}
+
+
+ {"UPT BURNED"}
+
+
+
+
+ {data.map((dataPoint) => {
+ const countryCode = dataPoint?.countryCode?.toLowerCase() ?? null;
+ const flag = countryCode ? `fi fi-${countryCode}` : null;
+ const city = dataPoint?.city !== "" ? dataPoint?.city : "Unknown";
+ return (
+
+
+
+ {flag ? : null}{" "}
+ {countryCode?.toUpperCase() ?? "N/A"}
+
+
+
+ {city}
+
+
+ {Math.floor(dataPoint.responseTime)} {t("ms")}
+
+
+
+ +{dataPoint.uptBurnt}
+
+
+
+ );
+ })}
+
+
+
+
+ );
+};
+
+export default DeviceTicker;
diff --git a/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeMap/DistributedUptimeMapStyle.json b/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeMap/DistributedUptimeMapStyle.json
new file mode 100644
index 000000000..86ca8204d
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeMap/DistributedUptimeMapStyle.json
@@ -0,0 +1,169 @@
+{
+ "id": "43f36e14-e3f5-43c1-84c0-50a9c80dc5c7",
+ "name": "MapLibre",
+ "zoom": 0.861983335785597,
+ "pitch": 0,
+ "center": [17.6543171043124, 32.9541203267468],
+ "glyphs": "https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf",
+ "layers": [
+ {
+ "id": "background",
+ "type": "background",
+ "paint": {
+ "background-color": "#121217"
+ },
+ "filter": ["all"],
+ "layout": {
+ "visibility": "visible"
+ },
+ "maxzoom": 24
+ },
+ {
+ "id": "coastline",
+ "type": "line",
+ "paint": {
+ "line-blur": 0.5,
+ "line-color": "#000000",
+ "line-width": {
+ "stops": [
+ [0, 2],
+ [6, 6],
+ [14, 9],
+ [22, 18]
+ ]
+ }
+ },
+ "filter": ["all"],
+ "layout": {
+ "line-cap": "round",
+ "line-join": "round",
+ "visibility": "visible"
+ },
+ "source": "maplibre",
+ "maxzoom": 24,
+ "minzoom": 0,
+ "source-layer": "countries"
+ },
+ {
+ "id": "countries-fill",
+ "type": "fill",
+ "paint": {
+ "fill-color": "#292929"
+ },
+ "filter": ["all"],
+ "layout": {
+ "visibility": "visible"
+ },
+ "source": "maplibre",
+ "maxzoom": 24,
+ "source-layer": "countries"
+ },
+ {
+ "id": "countries-boundary",
+ "type": "line",
+ "paint": {
+ "line-color": "#484848",
+ "line-width": {
+ "stops": [
+ [1, 1],
+ [6, 2],
+ [14, 6],
+ [22, 12]
+ ]
+ },
+ "line-opacity": {
+ "stops": [
+ [3, 0.5],
+ [6, 1]
+ ]
+ }
+ },
+ "layout": {
+ "line-cap": "round",
+ "line-join": "round",
+ "visibility": "visible"
+ },
+ "source": "maplibre",
+ "maxzoom": 24,
+ "source-layer": "countries"
+ },
+ {
+ "id": "countries-label",
+ "type": "symbol",
+ "paint": {
+ "text-color": "rgba(8, 37, 77, 1)",
+ "text-halo-blur": {
+ "stops": [
+ [2, 0.2],
+ [6, 0]
+ ]
+ },
+ "text-halo-color": "rgba(255, 255, 255, 1)",
+ "text-halo-width": {
+ "stops": [
+ [2, 1],
+ [6, 1.6]
+ ]
+ }
+ },
+ "filter": ["all"],
+ "layout": {
+ "text-font": ["Open Sans Semibold"],
+ "text-size": {
+ "stops": [
+ [2, 10],
+ [4, 12],
+ [6, 16]
+ ]
+ },
+ "text-field": {
+ "stops": [
+ [2, "{ABBREV}"],
+ [4, "{NAME}"]
+ ]
+ },
+ "visibility": "visible",
+ "text-max-width": 10,
+ "text-transform": {
+ "stops": [
+ [0, "uppercase"],
+ [2, "none"]
+ ]
+ }
+ },
+ "source": "maplibre",
+ "maxzoom": 24,
+ "minzoom": 2,
+ "source-layer": "centroids"
+ },
+ {
+ "id": "data-dots",
+ "type": "circle",
+ "source": "data-dots",
+ "paint": {
+ "circle-radius": 3,
+ "circle-color": ["get", "color"],
+ "circle-opacity": 0.5
+ }
+ }
+ ],
+ "bearing": 0,
+ "sources": {
+ "maplibre": {
+ "url": "https://demotiles.maplibre.org/tiles/tiles.json",
+ "type": "vector"
+ },
+ "data-dots": {
+ "type": "geojson",
+ "data": {
+ "type": "FeatureCollection",
+ "features": []
+ }
+ }
+ },
+ "version": 8,
+ "metadata": {
+ "maptiler:copyright": "This style was generated on MapTiler Cloud. Usage is governed by the license terms in https://github.com/maplibre/demotiles/blob/gh-pages/LICENSE",
+ "openmaptiles:version": "3.x"
+ }
+}
diff --git a/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeMap/buildStyle.js b/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeMap/buildStyle.js
new file mode 100644
index 000000000..e4aaa49ce
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeMap/buildStyle.js
@@ -0,0 +1,33 @@
+import baseStyle from "./DistributedUptimeMapStyle.json";
+
+const buildStyle = (theme, mode) => {
+ const style = JSON.parse(JSON.stringify(baseStyle));
+
+ if (mode === "dark") {
+ return baseStyle;
+ }
+
+ if (style.layers) {
+ const newLayers = style.layers.map((layer) => {
+ if (layer.id === "background") {
+ layer.paint["background-color"] = theme.palette.map.main;
+ }
+
+ if (layer.id === "countries-fill") {
+ layer.paint["fill-color"] = theme.palette.map.lowContrast;
+ }
+
+ if (layer.id === "coastline") {
+ layer.paint["line-color"] = theme.palette.map.highContrast;
+ }
+ if (layer.id === "countries-boundary") {
+ layer.paint["line-color"] = theme.palette.map.highContrast;
+ }
+ return layer;
+ });
+ style.layers = newLayers;
+ }
+ return style;
+};
+
+export default buildStyle;
diff --git a/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeMap/index.jsx b/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeMap/index.jsx
new file mode 100644
index 000000000..03993dcc3
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeMap/index.jsx
@@ -0,0 +1,118 @@
+import "maplibre-gl/dist/maplibre-gl.css";
+import PropTypes from "prop-types";
+import { useRef, useState, useEffect } from "react";
+import { useTheme } from "@mui/material/styles";
+import maplibregl from "maplibre-gl";
+import { useSelector } from "react-redux";
+import buildStyle from "./buildStyle";
+
+const DistributedUptimeMap = ({
+ width = "100%",
+ checks,
+ height,
+ minHeight = "350px",
+}) => {
+ const mapContainer = useRef(null);
+ const map = useRef(null);
+ const theme = useTheme();
+ const [mapLoaded, setMapLoaded] = useState(false);
+ const mode = useSelector((state) => state.ui.mode);
+ const initialTheme = useRef(theme);
+ const initialMode = useRef(mode);
+
+ const colorLookup = (avgResponseTime) => {
+ if (avgResponseTime <= 150) {
+ return "#00FF00"; // Green
+ } else if (avgResponseTime <= 250) {
+ return "#FFFF00"; // Yellow
+ } else {
+ return "#FF0000"; // Red
+ }
+ };
+
+ useEffect(() => {
+ if (mapContainer.current && !map.current) {
+ const initialStyle = buildStyle(initialTheme.current, initialMode.current);
+
+ map.current = new maplibregl.Map({
+ container: mapContainer.current,
+ style: initialStyle,
+ center: [0, 20],
+ zoom: 0.8,
+ attributionControl: false,
+ canvasContextAttributes: {
+ antialias: true,
+ preserveDrawingBuffer: true,
+ },
+ });
+ }
+ map.current.on("load", () => {
+ setMapLoaded(true);
+ });
+
+ return () => {
+ if (map.current) {
+ map.current.remove();
+ map.current = null;
+ }
+ };
+ }, []);
+
+ useEffect(() => {
+ const style = buildStyle(theme, mode);
+ if (map.current && mapLoaded) {
+ map.current.setStyle(style);
+ }
+ }, [theme, mode, mapLoaded]);
+
+ useEffect(() => {
+ if (map.current && checks?.length > 0) {
+ // Convert dots to GeoJSON
+ const geojson = {
+ type: "FeatureCollection",
+ features: checks.map((check) => {
+ return {
+ type: "Feature",
+ geometry: {
+ type: "Point",
+ coordinates: [check._id.lng, check._id.lat],
+ },
+ properties: {
+ color: theme.palette.accent.main,
+ // color: colorLookup(check.avgResponseTime) || "blue", // Default to blue if no color specified
+ },
+ };
+ }),
+ };
+
+ // Update the source with new dots
+ const source = map.current.getSource("data-dots");
+ if (source) {
+ source.setData(geojson);
+ }
+ }
+ }, [checks, theme, mapLoaded]);
+ return (
+
+ );
+};
+
+DistributedUptimeMap.propTypes = {
+ checks: PropTypes.array,
+ width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
+ height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
+ minHeight: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
+};
+
+export default DistributedUptimeMap;
diff --git a/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeResponseChart/Area/index.jsx b/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeResponseChart/Area/index.jsx
new file mode 100644
index 000000000..1102f72b8
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeResponseChart/Area/index.jsx
@@ -0,0 +1,95 @@
+import { useState } from "react";
+import { useTheme } from "@emotion/react";
+import {
+ AreaChart,
+ Area,
+ XAxis,
+ Tooltip,
+ CartesianGrid,
+ ResponsiveContainer,
+} from "recharts";
+import CustomTick from "../Helpers/Tick";
+import CustomToolTip from "../Helpers/ToolTip";
+import PropTypes from "prop-types";
+
+const DistributedUptimeResponseAreaChart = ({ checks }) => {
+ const theme = useTheme();
+ const [isHovered, setIsHovered] = useState(false);
+ return (
+
+ setIsHovered(true)}
+ onMouseLeave={() => setIsHovered(false)}
+ >
+
+
+
+
+
+
+
+ }
+ minTickGap={0}
+ axisLine={false}
+ tickLine={false}
+ height={20}
+ />
+ }
+ wrapperStyle={{ pointerEvents: "none" }}
+ />
+
+
+
+ );
+};
+
+DistributedUptimeResponseAreaChart.propTypes = {
+ checks: PropTypes.array,
+};
+
+export default DistributedUptimeResponseAreaChart;
diff --git a/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeResponseChart/Bar/index.jsx b/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeResponseChart/Bar/index.jsx
new file mode 100644
index 000000000..a6d3d455b
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeResponseChart/Bar/index.jsx
@@ -0,0 +1,95 @@
+import {
+ BarChart,
+ Bar,
+ CartesianGrid,
+ ResponsiveContainer,
+ Tooltip,
+ XAxis,
+} from "recharts";
+import { useTheme } from "@emotion/react";
+import PropTypes from "prop-types";
+import CustomToolTip from "../Helpers/ToolTip";
+import CustomTick from "../Helpers/Tick";
+
+const DistributedUptimeResponseBarChart = ({ checks }) => {
+ const theme = useTheme();
+ return (
+
+
+
+
+
+
+
+
+
+ }
+ wrapperStyle={{ pointerEvents: "none" }}
+ />
+ }
+ minTickGap={0}
+ axisLine={false}
+ tickLine={false}
+ height={20}
+ />
+
+
+
+ );
+};
+
+DistributedUptimeResponseBarChart.propTypes = {
+ checks: PropTypes.array,
+};
+
+export default DistributedUptimeResponseBarChart;
diff --git a/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeResponseChart/Helpers/Tick.jsx b/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeResponseChart/Helpers/Tick.jsx
new file mode 100644
index 000000000..15efd5dfa
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeResponseChart/Helpers/Tick.jsx
@@ -0,0 +1,31 @@
+import { useTheme } from "@emotion/react";
+import { useSelector } from "react-redux";
+import { formatDateWithTz } from "../../../../../../Utils/timeUtils";
+import PropTypes from "prop-types";
+import { Text } from "recharts";
+const CustomTick = ({ x, y, payload, index }) => {
+ const theme = useTheme();
+
+ const uiTimezone = useSelector((state) => state.ui.timezone);
+ return (
+
+ {formatDateWithTz(payload?.value, "h:mm a", uiTimezone)}
+
+ );
+};
+
+CustomTick.propTypes = {
+ x: PropTypes.number,
+ y: PropTypes.number,
+ payload: PropTypes.object,
+ index: PropTypes.number,
+};
+
+export default CustomTick;
diff --git a/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeResponseChart/Helpers/ToolTip.jsx b/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeResponseChart/Helpers/ToolTip.jsx
new file mode 100644
index 000000000..737b26106
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeResponseChart/Helpers/ToolTip.jsx
@@ -0,0 +1,89 @@
+import { Box, Stack, Typography } from "@mui/material";
+import { useSelector } from "react-redux";
+import { formatDateWithTz } from "../../../../../../Utils/timeUtils";
+import PropTypes from "prop-types";
+import { useTheme } from "@emotion/react";
+import AccessTimeIcon from "@mui/icons-material/AccessTime";
+import { useTranslation } from "react-i18next";
+
+const CustomToolTip = ({ active, payload, label }) => {
+ const uiTimezone = useSelector((state) => state.ui.timezone);
+ const theme = useTheme();
+ const { t } = useTranslation();
+ if (active && payload && payload.length) {
+ const responseTime = payload[0]?.payload?.originalAvgResponseTime
+ ? payload[0]?.payload?.originalAvgResponseTime
+ : (payload[0]?.payload?.avgResponseTime ?? 0);
+ return (
+
+
+ {formatDateWithTz(label, "ddd, MMMM D, YYYY, h:mm A", uiTimezone)}
+
+
+
+
+
+
+ {t("responseTime")}
+
+
+ {Math.floor(responseTime)}
+
+ {t("ms")}
+
+
+
+
+ );
+ }
+ return null;
+};
+
+CustomToolTip.propTypes = {
+ active: PropTypes.bool,
+ payload: PropTypes.arrayOf(
+ PropTypes.shape({
+ value: PropTypes.number,
+ payload: PropTypes.shape({
+ _id: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
+ avgResponseTime: PropTypes.number,
+ originalAvgResponseTime: PropTypes.number,
+ }),
+ })
+ ),
+ label: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
+};
+export default CustomToolTip;
diff --git a/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeResponseChart/index.jsx b/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeResponseChart/index.jsx
new file mode 100644
index 000000000..90a7671db
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/DistributedUptimeResponseChart/index.jsx
@@ -0,0 +1,53 @@
+//Components
+import { Stack, Switch, Typography } from "@mui/material";
+import { useState } from "react";
+import DistributedUptimeResponseAreaChart from "./Area";
+import DistributedUptimeResponseBarChart from "./Bar";
+import ChartBox from "../../../../../Components/Charts/ChartBox";
+import ResponseTimeIcon from "../../../../../assets/icons/response-time-icon.svg?react";
+
+// Utils
+import PropTypes from "prop-types";
+import { useTranslation } from "react-i18next";
+
+const DistributedUptimeResponseChart = ({ checks }) => {
+ const [chartType, setChartType] = useState("bar");
+ const { t } = useTranslation();
+ let Chart = null;
+ if (chartType === "area") {
+ Chart = DistributedUptimeResponseAreaChart;
+ }
+ if (chartType === "bar") {
+ Chart = DistributedUptimeResponseBarChart;
+ }
+ return (
+
+
+ {t("bar")}
+ setChartType(e.target.checked ? "area" : "bar")}
+ />
+ {t("area")}
+
+ }
+ header="Response Times"
+ sx={{ padding: 0 }}
+ >
+
+
+
+ );
+};
+
+DistributedUptimeResponseChart.propTypes = {
+ checks: PropTypes.array,
+ type: PropTypes.string,
+};
+
+export default DistributedUptimeResponseChart;
diff --git a/client/src/Pages/DistributedUptime/Details/Components/Footer/index.jsx b/client/src/Pages/DistributedUptime/Details/Components/Footer/index.jsx
new file mode 100644
index 000000000..62a1f465a
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/Footer/index.jsx
@@ -0,0 +1,34 @@
+import { Stack, Typography, Box } from "@mui/material";
+import SolanaLogo from "../../../../../assets/icons/solana_logo.svg?react";
+import { useTheme } from "@mui/material/styles";
+import { useTranslation } from "react-i18next";
+
+const Footer = () => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ return (
+
+ {t("distributedUptimeDetailsFooterHeading")}
+
+ {t("distributedUptimeDetailsFooterBuilt")}
+
+ {t("distributedUptimeDetailsFooterSolana")}
+
+
+ );
+};
+
+export default Footer;
diff --git a/client/src/Pages/DistributedUptime/Details/Components/LastUpdate/index.jsx b/client/src/Pages/DistributedUptime/Details/Components/LastUpdate/index.jsx
new file mode 100644
index 000000000..a095b5feb
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/LastUpdate/index.jsx
@@ -0,0 +1,15 @@
+import { useState, useEffect } from "react";
+const LastUpdate = ({ suffix, lastUpdateTime, trigger }) => {
+ const [elapsedMs, setElapsedMs] = useState(lastUpdateTime);
+
+ useEffect(() => {
+ setElapsedMs(lastUpdateTime);
+ const timer = setInterval(() => {
+ setElapsedMs((prev) => prev + 1000);
+ }, 1000);
+ return () => clearInterval(timer);
+ }, [lastUpdateTime, trigger]);
+
+ return `${Math.floor(elapsedMs / 1000)} ${suffix}`;
+};
+export default LastUpdate;
diff --git a/client/src/Pages/DistributedUptime/Details/Components/MonitorHeader/index.jsx b/client/src/Pages/DistributedUptime/Details/Components/MonitorHeader/index.jsx
new file mode 100644
index 000000000..9e2c4e87e
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/MonitorHeader/index.jsx
@@ -0,0 +1,25 @@
+import { Stack, Typography } from "@mui/material";
+import { useTheme } from "@mui/material/styles";
+import PropTypes from "prop-types";
+import { useTranslation } from "react-i18next";
+
+const MonitorHeader = ({ monitor }) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ return (
+
+
+ {monitor.name}
+
+ {t("distributedUptimeDetailsMonitorHeader")}
+
+
+
+ );
+};
+
+MonitorHeader.propTypes = {
+ monitor: PropTypes.object,
+};
+
+export default MonitorHeader;
diff --git a/client/src/Pages/DistributedUptime/Details/Components/NextExpectedCheck/index.jsx b/client/src/Pages/DistributedUptime/Details/Components/NextExpectedCheck/index.jsx
new file mode 100644
index 000000000..03949a9f7
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/NextExpectedCheck/index.jsx
@@ -0,0 +1,30 @@
+import { LinearProgress } from "@mui/material";
+import { useState, useEffect } from "react";
+
+const NextExpectedCheck = ({ lastUpdateTime, interval, trigger }) => {
+ const [elapsedMs, setElapsedMs] = useState(lastUpdateTime);
+
+ useEffect(() => {
+ setElapsedMs(lastUpdateTime);
+ const timer = setInterval(() => {
+ setElapsedMs((prev) => {
+ const newElapsedMs = prev + 100;
+ return newElapsedMs;
+ });
+ }, 100);
+ return () => clearInterval(timer);
+ }, [interval, trigger]);
+
+ return (
+
+ );
+};
+
+export default NextExpectedCheck;
diff --git a/client/src/Pages/DistributedUptime/Details/Components/Skeleton/index.jsx b/client/src/Pages/DistributedUptime/Details/Components/Skeleton/index.jsx
new file mode 100644
index 000000000..233fc3c06
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/Skeleton/index.jsx
@@ -0,0 +1,14 @@
+import { Stack, Skeleton } from "@mui/material";
+
+export const SkeletonLayout = () => {
+ return (
+
+
+
+ );
+};
+
+export default SkeletonLayout;
diff --git a/client/src/Pages/DistributedUptime/Details/Components/StatBoxes/index.jsx b/client/src/Pages/DistributedUptime/Details/Components/StatBoxes/index.jsx
new file mode 100644
index 000000000..97513bb4f
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/StatBoxes/index.jsx
@@ -0,0 +1,60 @@
+// Components
+import { Stack } from "@mui/material";
+import InfoBox from "../../../../../Components/InfoBox";
+import LastUpdate from "../LastUpdate";
+
+// Utils
+import { useTheme } from "@mui/material/styles";
+import PropTypes from "prop-types";
+
+const StatBoxes = ({ monitor, lastUpdateTrigger }) => {
+ const theme = useTheme();
+
+ return (
+
+
+
+
+ }
+ />
+
+ }
+ />
+
+ );
+};
+
+StatBoxes.propTypes = {
+ monitor: PropTypes.object,
+ lastUpdateTrigger: PropTypes.number,
+};
+
+export default StatBoxes;
diff --git a/client/src/Pages/DistributedUptime/Details/Components/StatusHeader/index.jsx b/client/src/Pages/DistributedUptime/Details/Components/StatusHeader/index.jsx
new file mode 100644
index 000000000..22a56bd7e
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Components/StatusHeader/index.jsx
@@ -0,0 +1,94 @@
+// Components
+import { ColContainer } from "../../../../../Components/StandardContainer";
+import { Stack, Typography } from "@mui/material";
+import PulseDot from "../../../../../Components/Animated/PulseDot";
+import LastUpdate from "../LastUpdate";
+import ChatBot from "../Chatbot";
+import ShareComponent from "../../../../../Components/ShareComponent";
+
+// Utils
+import { useTheme } from "@emotion/react";
+import PropTypes from "prop-types";
+import { useTranslation } from "react-i18next";
+
+const StatusHeader = ({ monitor, connectionStatus, elementToCapture }) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ const COLOR_MAP = {
+ up: theme.palette.successSecondary.main,
+ down: theme.palette.error.lowContrast,
+ };
+
+ const MSG_MAP = {
+ up: "All Systems Operational",
+ down: "Last Check Failed",
+ };
+
+ const PULSE_COLOR = {
+ up: theme.palette.success.main,
+ down: theme.palette.error.main,
+ };
+
+ let bgColor = COLOR_MAP[connectionStatus];
+ return (
+
+
+
+
+
+
+
+ {MSG_MAP[connectionStatus]}
+
+
+ {t("distributedUptimeDetailsStatusHeaderUptime")}{" "}
+ {(monitor.uptimePercentage * 100).toFixed(2)}%
+
+
+
+ {t("distributedUptimeDetailsStatusHeaderLastUpdate")}{" "}
+
+
+
+
+
+
+
+
+ );
+};
+
+StatusHeader.propTypes = {
+ monitor: PropTypes.object,
+ connectionStatus: PropTypes.string,
+};
+
+export default StatusHeader;
diff --git a/client/src/Pages/DistributedUptime/Details/Hooks/useDeleteMonitor.jsx b/client/src/Pages/DistributedUptime/Details/Hooks/useDeleteMonitor.jsx
new file mode 100644
index 000000000..a26de2a5e
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/Hooks/useDeleteMonitor.jsx
@@ -0,0 +1,25 @@
+import { useState } from "react";
+import { networkService } from "../../../../main";
+import { createToast } from "../../../../Utils/toastUtils";
+
+const useDeleteMonitor = ({ monitorId }) => {
+ const [isLoading, setIsLoading] = useState(false);
+ const deleteMonitor = async () => {
+ try {
+ setIsLoading(true);
+ await networkService.deleteMonitorById({ monitorId });
+ return true;
+ } catch (error) {
+ createToast({
+ body: error.message,
+ });
+ return false;
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return [deleteMonitor, isLoading];
+};
+
+export { useDeleteMonitor };
diff --git a/client/src/Pages/DistributedUptime/Details/index.jsx b/client/src/Pages/DistributedUptime/Details/index.jsx
new file mode 100644
index 000000000..27b39b600
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Details/index.jsx
@@ -0,0 +1,148 @@
+//Components
+import DistributedUptimeMap from "./Components/DistributedUptimeMap";
+import Breadcrumbs from "../../../Components/Breadcrumbs";
+import { Stack, Typography } from "@mui/material";
+import DeviceTicker from "./Components/DeviceTicker";
+import ResponseTimeChart from "./Components/DistributedUptimeResponseChart";
+import NextExpectedCheck from "./Components/NextExpectedCheck";
+import Footer from "./Components/Footer";
+import StatBoxes from "./Components/StatBoxes";
+import MonitorHeader from "./Components/MonitorHeader";
+import MonitorTimeFrameHeader from "../../../Components/MonitorTimeFrameHeader";
+import GenericFallback from "../../../Components/GenericFallback";
+import MonitorCreateHeader from "../../../Components/MonitorCreateHeader";
+import SkeletonLayout from "./Components/Skeleton";
+import ControlsHeader from "./Components/ControlsHeader";
+import Dialog from "../../../Components/Dialog";
+//Utils
+import { useTheme } from "@mui/material/styles";
+import { useState } from "react";
+import { useParams } from "react-router-dom";
+import { useIsAdmin } from "../../../Hooks/useIsAdmin";
+import { useSubscribeToDepinDetails } from "../../../Hooks/useSubscribeToDepinDetails";
+import { useDeleteMonitor } from "./Hooks/useDeleteMonitor";
+import { useNavigate } from "react-router-dom";
+import { useTranslation } from "react-i18next";
+
+const DistributedUptimeDetails = () => {
+ const { monitorId } = useParams();
+ // Local State
+ const [dateRange, setDateRange] = useState("recent");
+ const [isDeleteOpen, setIsDeleteOpen] = useState(false);
+
+ // Utils
+ const theme = useTheme();
+ const isAdmin = useIsAdmin();
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const [isLoading, networkError, connectionStatus, monitor, lastUpdateTrigger] =
+ useSubscribeToDepinDetails({ monitorId, dateRange });
+
+ const [deleteMonitor, isDeleting] = useDeleteMonitor({ monitorId });
+ // Constants
+ const BREADCRUMBS = [
+ { name: "Distributed Uptime", path: "/distributed-uptime" },
+ { name: "Details", path: `/distributed-uptime/${monitorId}` },
+ ];
+
+ if (isLoading) {
+ return ;
+ }
+
+ if (networkError) {
+ return (
+
+
+ {t("networkError")}
+
+ {t("checkConnection")}
+
+ );
+ }
+ if (
+ typeof monitor === "undefined" ||
+ typeof monitor?.totalChecks === "undefined" ||
+ monitor?.totalChecks === 0
+ ) {
+ return (
+
+
+
+ {t("distributedUptimeDetailsNoMonitorHistory")}
+
+
+ );
+ }
+ return (
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {
+ deleteMonitor();
+ setIsDeleteOpen(false);
+ navigate("/distributed-uptime");
+ }}
+ onCancel={() => {
+ setIsDeleteOpen(false);
+ }}
+ open={isDeleteOpen}
+ confirmationButtonLabel="Yes, delete monitor"
+ description="Once deleted, your monitor cannot be retrieved."
+ isLoading={isDeleting || isLoading}
+ />
+
+ );
+};
+
+export default DistributedUptimeDetails;
diff --git a/client/src/Pages/DistributedUptime/Monitors/Components/MonitorTable/index.jsx b/client/src/Pages/DistributedUptime/Monitors/Components/MonitorTable/index.jsx
new file mode 100644
index 000000000..fa8593cf1
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Monitors/Components/MonitorTable/index.jsx
@@ -0,0 +1,93 @@
+// Components
+import DataTable from "../../../../../Components/Table";
+import BarChart from "../../../../../Components/Charts/BarChart";
+import { Box } from "@mui/material";
+import { StatusLabel } from "../../../../../Components/Label";
+import Host from "../../../../../Components/Host";
+
+// Utils
+import { useTheme } from "@mui/material/styles";
+import { useNavigate } from "react-router-dom";
+import { useMonitorUtils } from "../../../../../Hooks/useMonitorUtils";
+import PropTypes from "prop-types";
+
+// Constants
+const TYPE_MAP = {
+ distributed_http: "Distributed HTTP",
+};
+
+const MonitorTable = ({ isLoading, monitors }) => {
+ const theme = useTheme();
+ const navigate = useNavigate();
+ const { determineState } = useMonitorUtils();
+ const headers = [
+ {
+ id: "name",
+ content: Host ,
+ render: (row) => (
+
+ ),
+ },
+ {
+ id: "status",
+ content: Status ,
+ render: (row) => {
+ const status = determineState(row?.monitor);
+ return (
+
+ );
+ },
+ },
+ {
+ id: "responseTime",
+ content: "Response Time",
+ render: (row) => ,
+ },
+ {
+ id: "type",
+ content: "Type",
+ render: (row) => {TYPE_MAP[row.monitor.type]} ,
+ },
+ {
+ id: "actions",
+ content: "Actions",
+ render: (row) => {"TODO"} ,
+ },
+ ];
+
+ return (
+ {
+ navigate(`/distributed-uptime/${row._id}`);
+ },
+ }}
+ />
+ );
+};
+
+MonitorTable.propTypes = {
+ isLoading: PropTypes.bool,
+ monitors: PropTypes.array,
+};
+
+export default MonitorTable;
diff --git a/client/src/Pages/DistributedUptime/Monitors/Components/Skeleton/index.jsx b/client/src/Pages/DistributedUptime/Monitors/Components/Skeleton/index.jsx
new file mode 100644
index 000000000..233fc3c06
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Monitors/Components/Skeleton/index.jsx
@@ -0,0 +1,14 @@
+import { Stack, Skeleton } from "@mui/material";
+
+export const SkeletonLayout = () => {
+ return (
+
+
+
+ );
+};
+
+export default SkeletonLayout;
diff --git a/client/src/Pages/DistributedUptime/Monitors/index.jsx b/client/src/Pages/DistributedUptime/Monitors/index.jsx
new file mode 100644
index 000000000..d2cea7432
--- /dev/null
+++ b/client/src/Pages/DistributedUptime/Monitors/index.jsx
@@ -0,0 +1,102 @@
+// Components
+import { Stack, Typography } from "@mui/material";
+import Breadcrumbs from "../../../Components/Breadcrumbs";
+import CreateMonitorHeader from "../../../Components/MonitorCreateHeader";
+import MonitorTable from "./Components/MonitorTable";
+import Pagination from "../../../Components/Table/TablePagination";
+import Fallback from "../../../Components/Fallback";
+import GenericFallback from "../../../Components/GenericFallback";
+
+// Utils
+import { useState } from "react";
+import { useTheme } from "@mui/material/styles";
+import { useIsAdmin } from "../../../Hooks/useIsAdmin";
+import { useSubscribeToDepinMonitors } from "../../../Hooks/useSubscribeToDepinMonitors";
+import SkeletonLayout from "./Components/Skeleton";
+import { useTranslation } from "react-i18next";
+// Constants
+const BREADCRUMBS = [{ name: `Distributed Uptime`, path: "/distributed-uptime" }];
+
+const DistributedUptimeMonitors = () => {
+ // Local state
+ const [page, setPage] = useState(0);
+ const [rowsPerPage, setRowsPerPage] = useState(10);
+
+ // Utils
+ const theme = useTheme();
+ const isAdmin = useIsAdmin();
+ const { t } = useTranslation();
+ const [monitors, count, isLoading, networkError] = useSubscribeToDepinMonitors(
+ page,
+ rowsPerPage
+ );
+ // Handlers
+ const handleChangePage = (event, newPage) => {
+ setPage(newPage);
+ };
+
+ const handleChangeRowsPerPage = (event) => {
+ setRowsPerPage(event.target.value);
+ setPage(0);
+ };
+
+ if (isLoading) {
+ return ;
+ }
+
+ if (networkError) {
+ return (
+
+
+ {t("networkError")}
+
+ {t("checkConnection")}
+
+ );
+ }
+
+ if (count === 0) {
+ return (
+
+ );
+ }
+ return (
+
+
+
+
+
+
+ );
+};
+
+export default DistributedUptimeMonitors;
diff --git a/client/src/Pages/DistributedUptimeStatus/Create/Components/VisuallyHiddenInput/index.jsx b/client/src/Pages/DistributedUptimeStatus/Create/Components/VisuallyHiddenInput/index.jsx
new file mode 100644
index 000000000..fd002d2a4
--- /dev/null
+++ b/client/src/Pages/DistributedUptimeStatus/Create/Components/VisuallyHiddenInput/index.jsx
@@ -0,0 +1,22 @@
+const VisuallyHiddenInput = ({ onChange }) => {
+ return (
+
+ );
+};
+
+export default VisuallyHiddenInput;
diff --git a/client/src/Pages/DistributedUptimeStatus/Create/index.jsx b/client/src/Pages/DistributedUptimeStatus/Create/index.jsx
new file mode 100644
index 000000000..308f9489b
--- /dev/null
+++ b/client/src/Pages/DistributedUptimeStatus/Create/index.jsx
@@ -0,0 +1,322 @@
+// Components
+import { Stack, Typography, Button, Box } from "@mui/material";
+import ConfigBox from "../../../Components/ConfigBox";
+import Checkbox from "../../../Components/Inputs/Checkbox";
+import TextInput from "../../../Components/Inputs/TextInput";
+import VisuallyHiddenInput from "./Components/VisuallyHiddenInput";
+import Image from "../../../Components/Image";
+import LogoPlaceholder from "../../../assets/Images/logo_placeholder.svg";
+import Breadcrumbs from "../../../Components/Breadcrumbs";
+import Search from "../../../Components/Inputs/Search";
+import MonitorList from "../../StatusPage/Create/Components/MonitorList";
+// Utils
+import { useTheme } from "@emotion/react";
+import { useState, useEffect } from "react";
+import { useParams } from "react-router-dom";
+import { useCreateStatusPage } from "../../StatusPage/Create/Hooks/useCreateStatusPage";
+import { statusPageValidation } from "../../../Validation/validation";
+import { buildErrors } from "../../../Validation/error";
+import { createToast } from "../../../Utils/toastUtils";
+import { useNavigate } from "react-router-dom";
+import { useMonitorsFetch } from "../../StatusPage/Create/Hooks/useMonitorsFetch";
+import { useTranslation } from "react-i18next";
+import { useFetchDepinStatusPage } from "../../../Hooks/useFetchDepinStatusPage";
+const CreateStatus = () => {
+ const theme = useTheme();
+ const { monitorId, url } = useParams();
+ const navigate = useNavigate();
+ const { t } = useTranslation();
+ const isCreate = typeof url === "undefined";
+
+ const [createStatusPage, isLoading, networkError] = useCreateStatusPage(isCreate);
+
+ const [statusPageIsLoading, statusPageNetworkError, statusPage, _, isPublished] =
+ useFetchDepinStatusPage({
+ url,
+ timeFrame: 30,
+ isCreate,
+ });
+
+ const [monitors, monitorsIsLoading, monitorsNetworkError] = useMonitorsFetch();
+
+ const BREADCRUMBS = [
+ { name: "distributed uptime", path: "/distributed-uptime" },
+ {
+ name: "details",
+ path: `/distributed-uptime/${isCreate ? monitorId : statusPage?.monitors[0]}`,
+ },
+ { name: isCreate ? "create status page" : "edit status page", path: `` },
+ ];
+ // Local state
+ const [form, setForm] = useState({
+ type: "distributed",
+ isPublished: false,
+ url: url ?? Math.floor(Math.random() * 1000000).toFixed(0),
+ logo: undefined,
+ companyName: "",
+ monitors: [monitorId],
+ });
+ const [errors, setErrors] = useState({});
+ const [search, setSearch] = useState("");
+ const [selectedMonitors, setSelectedMonitors] = useState([]);
+
+ const handleFormChange = (e) => {
+ const { name, value, checked, type } = e.target;
+
+ // Check for errors
+ const { error } = statusPageValidation.validate(
+ { [name]: value },
+ { abortEarly: false }
+ );
+
+ setErrors((prev) => buildErrors(prev, name, error));
+
+ if (type === "checkbox") {
+ setForm({ ...form, [name]: checked });
+ return;
+ }
+ setForm({ ...form, [name]: value });
+ };
+
+ const handleMonitorsChange = (selectedMonitors) => {
+ handleFormChange({
+ target: {
+ name: "subMonitors",
+ value: selectedMonitors.map((monitor) => monitor._id),
+ },
+ });
+ setSelectedMonitors(selectedMonitors);
+ };
+
+ const handleImageUpload = (e) => {
+ const img = e.target?.files?.[0];
+ setForm((prev) => ({
+ ...prev,
+ logo: img,
+ }));
+ };
+ const handleSubmit = async () => {
+ let logoToSubmit = undefined;
+
+ // Handle image
+ if (typeof form.logo !== "undefined" && typeof form.logo.src === "undefined") {
+ logoToSubmit = {
+ src: URL.createObjectURL(form.logo),
+ name: form.logo.name,
+ type: form.logo.type,
+ size: form.logo.size,
+ };
+ } else if (typeof form.logo !== "undefined") {
+ logoToSubmit = form.logo;
+ }
+ const formToSubmit = { ...form };
+ if (typeof logoToSubmit !== "undefined") {
+ formToSubmit.logo = logoToSubmit;
+ }
+ // Validate
+ const { error } = statusPageValidation.validate(formToSubmit, { abortEarly: false });
+ if (typeof error === "undefined") {
+ const success = await createStatusPage({ form: formToSubmit });
+ if (success) {
+ const verb = isCreate ? "created" : "updated";
+ createToast({ body: `Status page ${verb} successfully` });
+ navigate(`/status/distributed/${form.url}`);
+ }
+ return;
+ }
+ const newErrors = {};
+ error?.details?.forEach((err) => {
+ newErrors[err.path[0]] = err.message;
+ });
+ setErrors((prev) => ({ ...prev, ...newErrors }));
+ };
+
+ // If we are configuring, populate fields
+ useEffect(() => {
+ if (isCreate) return;
+ if (typeof statusPage === "undefined") {
+ return;
+ }
+
+ let newLogo = undefined;
+ if (statusPage.logo) {
+ newLogo = {
+ src: `data:${statusPage.logo.contentType};base64,${statusPage.logo.data}`,
+ name: "logo",
+ type: statusPage.logo.contentType,
+ size: null,
+ };
+ }
+
+ setForm((prev) => {
+ return {
+ ...prev,
+ companyName: statusPage?.companyName,
+ isPublished: statusPage?.isPublished,
+ timezone: statusPage?.timezone,
+ monitors: statusPage?.monitors,
+ subMonitors: statusPage?.subMonitors.map((monitor) => monitor._id),
+ color: statusPage?.color,
+ logo: newLogo,
+ };
+ });
+ setSelectedMonitors(statusPage?.subMonitors);
+ }, [isCreate, statusPage]);
+
+ const imgSrc = form?.logo?.src
+ ? form.logo.src
+ : form.logo
+ ? URL.createObjectURL(form.logo)
+ : undefined;
+
+ return (
+
+
+
+
+ {isCreate
+ ? t("distributedUptimeStatusCreateYour")
+ : t("distributedUptimeStatusEditYour")}{" "}
+
+
+ {t("distributedUptimeStatusCreateStatusPage")}
+
+
+
+
+
+ {t("distributedUptimeStatusCreateStatusPageAccess")}
+
+
+ {t("distributedUptimeStatusCreateStatusPageReady")}
+
+
+
+
+
+
+
+
+
+ {t("distributedUptimeStatusBasicInfoHeader")}
+
+
+ {t("distributedUptimeStatusBasicInfoDescription")}
+
+
+
+
+
+
+
+
+
+ {t("distributedUptimeStatusLogoHeader")}
+
+ {t("distributedUptimeStatusLogoDescription")}{" "}
+
+
+
+
+
+
+ {t("distributedUptimeStatusLogoUploadButton")}
+
+
+
+
+
+
+
+
+ {t("distributedUptimeStatusStandardMonitorsHeader")}
+
+
+ {t("distributedUptimeStatusStandardMonitorsDescription")}
+
+
+
+
+
+
+
+
+
+ {t("settingsSave")}
+
+
+
+ );
+};
+
+export default CreateStatus;
diff --git a/client/src/Pages/DistributedUptimeStatus/Status/Components/MonitorsList/index.jsx b/client/src/Pages/DistributedUptimeStatus/Status/Components/MonitorsList/index.jsx
new file mode 100644
index 000000000..d9ed16e63
--- /dev/null
+++ b/client/src/Pages/DistributedUptimeStatus/Status/Components/MonitorsList/index.jsx
@@ -0,0 +1,66 @@
+// Components
+import { Stack, Box } from "@mui/material";
+import Host from "../../../../../Components/Host";
+import DePINStatusPageBarChart from "../../../../../Components/Charts/DePINStatusPageBarChart";
+import { StatusLabel } from "../../../../../Components/Label";
+
+//Utils
+import { useTheme } from "@mui/material/styles";
+import useUtils from "../../../../Uptime/Monitors/Hooks/useUtils";
+import PropTypes from "prop-types";
+const MonitorsList = ({
+ isLoading = false,
+ shouldRender = true,
+ monitors = [],
+ timeFrame,
+}) => {
+ const theme = useTheme();
+ const { determineState } = useUtils();
+ return (
+ <>
+ {monitors?.map((monitor) => {
+ const status = determineState(monitor);
+ return (
+
+
+
+
+
+
+
+
+
+
+
+ );
+ })}
+ >
+ );
+};
+
+MonitorsList.propTypes = {
+ monitors: PropTypes.array.isRequired,
+};
+
+export default MonitorsList;
diff --git a/client/src/Pages/DistributedUptimeStatus/Status/Components/Skeleton/index.jsx b/client/src/Pages/DistributedUptimeStatus/Status/Components/Skeleton/index.jsx
new file mode 100644
index 000000000..233fc3c06
--- /dev/null
+++ b/client/src/Pages/DistributedUptimeStatus/Status/Components/Skeleton/index.jsx
@@ -0,0 +1,14 @@
+import { Stack, Skeleton } from "@mui/material";
+
+export const SkeletonLayout = () => {
+ return (
+
+
+
+ );
+};
+
+export default SkeletonLayout;
diff --git a/client/src/Pages/DistributedUptimeStatus/Status/Components/TimeframeHeader/index.jsx b/client/src/Pages/DistributedUptimeStatus/Status/Components/TimeframeHeader/index.jsx
new file mode 100644
index 000000000..7ee4ff292
--- /dev/null
+++ b/client/src/Pages/DistributedUptimeStatus/Status/Components/TimeframeHeader/index.jsx
@@ -0,0 +1,42 @@
+import { Stack, Button, ButtonGroup } from "@mui/material";
+import { useTheme } from "@emotion/react";
+import { useTranslation } from "react-i18next";
+
+const TimeFrameHeader = ({ timeFrame, setTimeFrame, sx, ...props }) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ return (
+
+
+ setTimeFrame(30)}
+ >
+ {t("distributedUptimeStatus30Days")}
+
+ setTimeFrame(60)}
+ >
+ {t("distributedUptimeStatus60Days")}
+
+ setTimeFrame(90)}
+ >
+ {t("distributedUptimeStatus90Days")}
+
+
+
+ );
+};
+
+export default TimeFrameHeader;
diff --git a/client/src/Pages/DistributedUptimeStatus/Status/index.jsx b/client/src/Pages/DistributedUptimeStatus/Status/index.jsx
new file mode 100644
index 000000000..117a297e5
--- /dev/null
+++ b/client/src/Pages/DistributedUptimeStatus/Status/index.jsx
@@ -0,0 +1,319 @@
+//Components
+import DistributedUptimeMap from "../../DistributedUptime/Details/Components/DistributedUptimeMap";
+import Breadcrumbs from "../../../Components/Breadcrumbs";
+import { Stack, Typography } from "@mui/material";
+import DeviceTicker from "../../DistributedUptime/Details/Components/DeviceTicker";
+import DistributedUptimeResponseChart from "../../DistributedUptime/Details/Components/DistributedUptimeResponseChart";
+import NextExpectedCheck from "../../DistributedUptime/Details/Components/NextExpectedCheck";
+import Footer from "../../DistributedUptime/Details/Components/Footer";
+import StatBoxes from "../../DistributedUptime/Details/Components/StatBoxes";
+import ControlsHeader from "../../StatusPage/Status/Components/ControlsHeader";
+import MonitorTimeFrameHeader from "../../../Components/MonitorTimeFrameHeader";
+import GenericFallback from "../../../Components/GenericFallback";
+import Dialog from "../../../Components/Dialog";
+import SkeletonLayout from "./Components/Skeleton";
+import UptLogo from "../../../assets/icons/upt_logo.png";
+import PeopleAltOutlinedIcon from "@mui/icons-material/PeopleAltOutlined";
+import InfoBox from "../../../Components/InfoBox";
+import StatusHeader from "../../DistributedUptime/Details/Components/StatusHeader";
+import MonitorsList from "./Components/MonitorsList";
+import { RowContainer } from "../../../Components/StandardContainer";
+
+//Utils
+import { useTheme } from "@mui/material/styles";
+import { useState, useEffect, useRef } from "react";
+import { useParams } from "react-router-dom";
+import { useFetchDepinStatusPage } from "../../../Hooks/useFetchDepinStatusPage";
+import { useSubscribeToDepinDetails } from "../../../Hooks/useSubscribeToDepinDetails";
+import { useStatusPageDelete } from "../../StatusPage/Status/Hooks/useStatusPageDelete";
+import TimeFrameHeader from "./Components/TimeframeHeader";
+import SubHeader from "../../../Components/Subheader";
+import { safelyParseFloat } from "../../../Utils/utils";
+import { useNavigate, useLocation } from "react-router-dom";
+import { useTranslation } from "react-i18next";
+import { useSelector, useDispatch } from "react-redux";
+import { setMode } from "../../../Features/UI/uiSlice";
+
+// Responsive
+import { useMediaQuery } from "@mui/material";
+
+const DistributedUptimeStatus = () => {
+ const { url } = useParams();
+ const location = useLocation();
+ const { t } = useTranslation();
+ const isPublic = location.pathname.startsWith("/status/distributed/public");
+ const elementToCapture = useRef(null);
+
+ // Redux state
+ const mode = useSelector((state) => state.ui.mode);
+ const originalModeRef = useRef(null);
+
+ // Local State
+ const [dateRange, setDateRange] = useState("recent");
+ const [isDeleteOpen, setIsDeleteOpen] = useState(false);
+ const [timeFrame, setTimeFrame] = useState(30);
+ // Utils
+ const theme = useTheme();
+ const isSmallScreen = useMediaQuery(theme.breakpoints.down("sm"));
+ const navigate = useNavigate();
+ const dispatch = useDispatch();
+
+ const [
+ statusPageIsLoading,
+ statusPageNetworkError,
+ statusPage,
+ monitorId,
+ isPublished,
+ ] = useFetchDepinStatusPage({
+ url,
+ timeFrame,
+ });
+
+ const [isLoading, networkError, connectionStatus, monitor, lastUpdateTrigger] =
+ useSubscribeToDepinDetails({ monitorId, dateRange, isPublic, isPublished });
+
+ const [deleteStatusPage, isDeleting] = useStatusPageDelete(() => {
+ navigate("/distributed-uptime");
+ }, url);
+ // Constants
+ const BREADCRUMBS = [
+ { name: "Distributed Uptime", path: "/distributed-uptime" },
+ { name: "details", path: `/distributed-uptime/${monitorId}` },
+ { name: "status", path: `` },
+ ];
+
+ let sx = {};
+ if (isPublic) {
+ sx = {
+ paddingTop: "10vh",
+ paddingRight: "10vw",
+ paddingBottom: "10vh",
+ paddingLeft: "10vw",
+ };
+ }
+
+ // Default to dark mode
+ useEffect(() => {
+ const cleanup = () => {
+ if (originalModeRef.current === null) {
+ originalModeRef.current = mode;
+ }
+
+ if (isPublic) {
+ dispatch(setMode(originalModeRef.current));
+ }
+ };
+
+ if (isPublic) {
+ dispatch(setMode("dark"));
+ }
+
+ window.addEventListener("beforeunload", cleanup);
+ return () => {
+ window.removeEventListener("beforeunload", cleanup);
+ };
+ }, [dispatch, isPublic]);
+
+ // Done loading, a status page doesn't exist
+ if (!statusPageIsLoading && typeof statusPage === "undefined") {
+ return (
+
+
+
+ {t("distributedUptimeStatusPageNotSetUp")}
+
+ {t("distributedUptimeStatusContactAdmin")}
+
+
+ );
+ }
+
+ // Done loading, a status page exists but is not public
+ if (!statusPageIsLoading && isPublic && statusPage.isPublished === false) {
+ return (
+
+
+ {t("distributedUptimeStatusPageNotPublic")}
+
+
+ );
+ }
+
+ if (isLoading || statusPageIsLoading) {
+ return ;
+ }
+
+ if (networkError || statusPageNetworkError) {
+ return (
+
+
+ {t("networkError")}
+
+ {t("checkConnection")}
+
+ );
+ }
+
+ if (
+ typeof statusPage === "undefined" ||
+ typeof monitor === "undefined" ||
+ monitor.totalChecks === 0
+ ) {
+ return (
+
+
+
+ {t("distributedUptimeDetailsNoMonitorHistory")}
+
+
+ );
+ }
+
+ return (
+
+ {!isPublic && }
+
+
+
+
+
+
+
+
+ {t("distributedRightCategoryTitle")}
+
+ {statusPage.companyName}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 0}
+ direction={{ s: "column", md: "row" }}
+ headerText={t("distributedStatusServerMonitors")}
+ subHeaderText={t("distributedStatusServerMonitorsDescription")}
+ gap={isSmallScreen ? theme.spacing(10) : 0}
+ alignItems={{ s: "flex-start", md: "flex-end" }}
+ >
+
+
+
+
+
+ {
+ deleteStatusPage();
+ setIsDeleteOpen(false);
+ }}
+ onCancel={() => {
+ setIsDeleteOpen(false);
+ }}
+ open={isDeleteOpen}
+ confirmationButtonLabel={t("distributedUptimeStatusPageDeleteConfirm")}
+ description={t("distributedUptimeStatusPageDeleteDescription")}
+ isLoading={isDeleting || isLoading}
+ />
+
+ );
+};
+
+export default DistributedUptimeStatus;
diff --git a/client/src/Pages/Incidents/Components/IncidentTable/index.jsx b/client/src/Pages/Incidents/Components/IncidentTable/index.jsx
new file mode 100644
index 000000000..cc2d212f0
--- /dev/null
+++ b/client/src/Pages/Incidents/Components/IncidentTable/index.jsx
@@ -0,0 +1,132 @@
+//Components
+import Table from "../../../../Components/Table";
+import TableSkeleton from "../../../../Components/Table/skeleton";
+import Pagination from "../../../../Components/Table/TablePagination";
+import { StatusLabel } from "../../../../Components/Label";
+import { HttpStatusLabel } from "../../../../Components/HttpStatusLabel";
+import GenericFallback from "../../../../Components/GenericFallback";
+import NetworkError from "../../../../Components/GenericFallback/NetworkError";
+
+//Utils
+import { formatDateWithTz } from "../../../../Utils/timeUtils";
+import { useSelector } from "react-redux";
+import { useState } from "react";
+import useChecksFetch from "../../Hooks/useChecksFetch";
+import PropTypes from "prop-types";
+import { useTranslation } from "react-i18next";
+
+const IncidentTable = ({
+ shouldRender,
+ monitors,
+ selectedMonitor,
+ filter,
+ dateRange,
+}) => {
+ //Redux state
+ const uiTimezone = useSelector((state) => state.ui.timezone);
+
+ //Local state
+ const [page, setPage] = useState(0);
+ const [rowsPerPage, setRowsPerPage] = useState(10);
+ const selectedMonitorDetails = monitors?.[selectedMonitor];
+ const selectedMonitorType = selectedMonitorDetails?.type;
+ const { isLoading, networkError, checks, checksCount } = useChecksFetch({
+ selectedMonitor,
+ selectedMonitorType,
+ filter,
+ dateRange,
+ page,
+ rowsPerPage,
+ });
+
+ const { t } = useTranslation();
+
+ //Handlers
+ const handleChangePage = (_, newPage) => {
+ setPage(newPage);
+ };
+
+ const handleChangeRowsPerPage = (event) => {
+ setRowsPerPage(event.target.value);
+ };
+
+ const headers = [
+ {
+ id: "monitorName",
+ content: t("incidentsTableMonitorName"),
+ render: (row) => monitors[row.monitorId]?.name ?? "N/A",
+ },
+ {
+ id: "status",
+ content: t("incidentsTableStatus"),
+ render: (row) => {
+ const status = row.status === true ? "up" : "down";
+ return (
+
+ );
+ },
+ },
+ {
+ id: "dateTime",
+ content: t("incidentsTableDateTime"),
+ render: (row) => {
+ const formattedDate = formatDateWithTz(
+ row.createdAt,
+ "YYYY-MM-DD HH:mm:ss A",
+ uiTimezone
+ );
+ return formattedDate;
+ },
+ },
+ {
+ id: "statusCode",
+ content: t("incidentsTableStatusCode"),
+ render: (row) => ,
+ },
+ { id: "message", content: t("incidentsTableMessage"), render: (row) => row.message },
+ ];
+
+ if (!shouldRender || isLoading) return ;
+
+ if (networkError) {
+ return (
+
+
+
+ );
+ }
+
+ if (!isLoading && typeof checksCount === "undefined") {
+ return {t("incidentsTableNoIncidents")} ;
+ }
+
+ return (
+ <>
+
+
+ >
+ );
+};
+
+IncidentTable.propTypes = {
+ shouldRender: PropTypes.bool,
+ monitors: PropTypes.object,
+ selectedMonitor: PropTypes.string,
+ filter: PropTypes.string,
+ dateRange: PropTypes.string,
+};
+export default IncidentTable;
diff --git a/client/src/Pages/Incidents/Components/OptionsHeader/index.jsx b/client/src/Pages/Incidents/Components/OptionsHeader/index.jsx
new file mode 100644
index 000000000..20140e8c4
--- /dev/null
+++ b/client/src/Pages/Incidents/Components/OptionsHeader/index.jsx
@@ -0,0 +1,146 @@
+// Components
+import { Stack, Typography, Button, ButtonGroup } from "@mui/material";
+import Select from "../../../../Components/Inputs/Select";
+import PropTypes from "prop-types";
+
+//Utils
+import { useTheme } from "@emotion/react";
+import SkeletonLayout from "./skeleton";
+import { useTranslation } from "react-i18next";
+
+const OptionsHeader = ({
+ shouldRender,
+ selectedMonitor = 0,
+ setSelectedMonitor,
+ monitors,
+ filter = "all",
+ setFilter,
+ dateRange = "hour",
+ setDateRange,
+}) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ const monitorNames = typeof monitors !== "undefined" ? Object.values(monitors) : [];
+
+ // The stacks below which are three in number have the same style so
+ const stackStyles = {
+ direction: "row",
+ alignItems: "center",
+ gap: theme.spacing(6),
+ };
+
+ if (!shouldRender) return ;
+
+ return (
+
+
+
+ {t("incidentsOptionsHeader")}
+
+ setSelectedMonitor(e.target.value)}
+ items={monitorNames}
+ sx={{
+ backgroundColor: theme.palette.primary.main,
+ color: theme.palette.primary.contrastTextSecondary,
+ }}
+ maxWidth={250}
+ />
+
+
+
+ {t("incidentsOptionsHeaderFilterBy")}
+
+
+ setFilter("all")}
+ >
+ {t("incidentsOptionsHeaderFilterAll")}
+
+ setFilter("down")}
+ >
+ {t("incidentsOptionsHeaderFilterDown")}
+
+ setFilter("resolve")}
+ >
+ {t("incidentsOptionsHeaderFilterCannotResolve")}
+
+
+
+
+
+ {t("incidentsOptionsHeaderShow")}
+
+
+ setDateRange("hour")}
+ >
+ {t("incidentsOptionsHeaderLastHour")}
+
+ setDateRange("day")}
+ >
+ {t("incidentsOptionsHeaderLastDay")}
+
+ setDateRange("week")}
+ >
+ {t("incidentsOptionsHeaderLastWeek")}
+
+ setDateRange("all")}
+ >
+ {t("incidentsOptionsHeaderFilterAll")}
+
+
+
+
+ );
+};
+
+OptionsHeader.propTypes = {
+ shouldRender: PropTypes.bool,
+ selectedMonitor: PropTypes.string,
+ setSelectedMonitor: PropTypes.func,
+ monitors: PropTypes.object,
+ filter: PropTypes.string,
+ setFilter: PropTypes.func,
+ dateRange: PropTypes.string,
+ setDateRange: PropTypes.func,
+};
+
+export default OptionsHeader;
diff --git a/client/src/Pages/Incidents/Components/OptionsHeader/skeleton.jsx b/client/src/Pages/Incidents/Components/OptionsHeader/skeleton.jsx
new file mode 100644
index 000000000..8a8990dc4
--- /dev/null
+++ b/client/src/Pages/Incidents/Components/OptionsHeader/skeleton.jsx
@@ -0,0 +1,11 @@
+import { Stack, Skeleton } from "@mui/material";
+
+const SkeletonLayout = () => {
+ return (
+
+
+
+ );
+};
+
+export default SkeletonLayout;
diff --git a/client/src/Pages/Incidents/Hooks/useChecksFetch.jsx b/client/src/Pages/Incidents/Hooks/useChecksFetch.jsx
new file mode 100644
index 000000000..bb1f201b0
--- /dev/null
+++ b/client/src/Pages/Incidents/Hooks/useChecksFetch.jsx
@@ -0,0 +1,59 @@
+import { useState, useEffect } from "react";
+import { networkService } from "../../../main";
+import { createToast } from "../../../Utils/toastUtils";
+import { useSelector } from "react-redux";
+const useChecksFetch = ({ selectedMonitor, selectedMonitorType, filter, dateRange, page, rowsPerPage }) => {
+ //Redux
+ const { user } = useSelector((state) => state.auth);
+
+ //Local
+ const [isLoading, setIsLoading] = useState(true);
+ const [networkError, setNetworkError] = useState(false);
+ const [checks, setChecks] = useState(undefined);
+ const [checksCount, setChecksCount] = useState(undefined);
+
+ useEffect(() => {
+ const fetchChecks = async () => {
+ try {
+ setIsLoading(true);
+ let res;
+
+ if (selectedMonitor === "0") {
+ res = await networkService.getChecksByTeam({
+ status: false,
+ teamId: user.teamId,
+ sortOrder: "desc",
+ limit: null,
+ dateRange,
+ filter: filter,
+ page: page,
+ rowsPerPage: rowsPerPage,
+ });
+ } else {
+ res = await networkService.getChecksByMonitor({
+ status: false,
+ monitorId: selectedMonitor,
+ type: selectedMonitorType,
+ sortOrder: "desc",
+ limit: null,
+ dateRange,
+ filter: filter,
+ page,
+ rowsPerPage,
+ });
+ }
+ setChecks(res.data.data.checks);
+ setChecksCount(res.data.data.checksCount);
+ } catch (error) {
+ setNetworkError(true);
+ createToast({ body: error.message });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+ fetchChecks();
+ }, [user, dateRange, page, rowsPerPage, filter, selectedMonitor, selectedMonitorType]);
+ return { isLoading, networkError, checks, checksCount };
+};
+
+export default useChecksFetch;
diff --git a/client/src/Pages/Incidents/Hooks/useMonitorsFetch.jsx b/client/src/Pages/Incidents/Hooks/useMonitorsFetch.jsx
new file mode 100644
index 000000000..fcf729cee
--- /dev/null
+++ b/client/src/Pages/Incidents/Hooks/useMonitorsFetch.jsx
@@ -0,0 +1,54 @@
+import { useState, useEffect } from "react";
+import { networkService } from "../../../main";
+import { createToast } from "../../../Utils/toastUtils";
+const useMonitorsFetch = ({ teamId }) => {
+ //Local state
+ const [isLoading, setIsLoading] = useState(true);
+ const [networkError, setNetworkError] = useState(false);
+
+ const [monitors, setMonitors] = useState(undefined);
+
+ useEffect(() => {
+ const fetchMonitors = async () => {
+ try {
+ setIsLoading(true);
+ const res = await networkService.getMonitorsByTeamId({
+ teamId,
+ limit: null,
+ types: null,
+ status: null,
+ checkOrder: null,
+ normalize: null,
+ page: null,
+ rowsPerPage: null,
+ filter: null,
+ field: null,
+ order: null,
+ });
+ if (res?.data?.data?.filteredMonitors?.length > 0) {
+ const monitorLookup = res.data.data.filteredMonitors.reduce((acc, monitor) => {
+ acc[monitor._id] = {
+ _id: monitor._id,
+ name: monitor.name,
+ type: monitor.type
+ };
+ return acc;
+ }, {});
+ setMonitors(monitorLookup);
+ }
+ } catch (error) {
+ setNetworkError(true);
+ createToast({
+ body: error.message,
+ });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ fetchMonitors();
+ }, [teamId]);
+ return { isLoading, monitors, networkError };
+};
+
+export { useMonitorsFetch };
diff --git a/client/src/Pages/Incidents/index.jsx b/client/src/Pages/Incidents/index.jsx
new file mode 100644
index 000000000..36ff66707
--- /dev/null
+++ b/client/src/Pages/Incidents/index.jsx
@@ -0,0 +1,67 @@
+// Components
+import { Stack } from "@mui/material";
+import Breadcrumbs from "../../Components/Breadcrumbs";
+
+//Utils
+import { useTheme } from "@emotion/react";
+import { useMonitorsFetch } from "./Hooks/useMonitorsFetch";
+import { useSelector } from "react-redux";
+import OptionsHeader from "./Components/OptionsHeader";
+import { useState } from "react";
+import IncidentTable from "./Components/IncidentTable";
+import GenericFallback from "../../Components/GenericFallback";
+import NetworkError from "../../Components/GenericFallback/NetworkError";
+import { useTranslation } from "react-i18next";
+//Constants
+
+const Incidents = () => {
+ // Redux state
+ const { user } = useSelector((state) => state.auth);
+ const { t } = useTranslation();
+
+ const BREADCRUMBS = [{ name: t("incidentsPageTitle", "Incidents"), path: "/incidents" }];
+
+ // Local state
+ const [selectedMonitor, setSelectedMonitor] = useState("0");
+ const [filter, setFilter] = useState(undefined);
+ const [dateRange, setDateRange] = useState(undefined);
+ //Utils
+ const theme = useTheme();
+
+ const { monitors, isLoading, networkError } = useMonitorsFetch({
+ teamId: user.teamId,
+ });
+
+ if (networkError) {
+ return (
+
+
+
+ );
+ }
+
+ return (
+
+
+
+
+
+ );
+};
+
+export default Incidents;
diff --git a/Client/src/Pages/Infrastructure/CreateMonitor/CustomThreshold/index.jsx b/client/src/Pages/Infrastructure/Create/Components/CustomThreshold/index.jsx
similarity index 95%
rename from Client/src/Pages/Infrastructure/CreateMonitor/CustomThreshold/index.jsx
rename to client/src/Pages/Infrastructure/Create/Components/CustomThreshold/index.jsx
index 3220582a8..d91e899c5 100644
--- a/Client/src/Pages/Infrastructure/CreateMonitor/CustomThreshold/index.jsx
+++ b/client/src/Pages/Infrastructure/Create/Components/CustomThreshold/index.jsx
@@ -1,6 +1,6 @@
import { Box, Stack, Typography } from "@mui/material";
-import TextInput from "../../../../Components/Inputs/TextInput";
-import Checkbox from "../../../../Components/Inputs/Checkbox";
+import TextInput from "../../../../../Components/Inputs/TextInput";
+import Checkbox from "../../../../../Components/Inputs/Checkbox";
import { useTheme } from "@emotion/react";
import PropTypes from "prop-types";
@@ -117,7 +117,7 @@ CustomThreshold.propTypes = {
fieldName: PropTypes.string,
fieldValue: PropTypes.string.isRequired,
onFieldChange: PropTypes.func.isRequired,
- onFieldBlur: PropTypes.func.isRequired,
+ onFieldBlur: PropTypes.func,
alertUnit: PropTypes.string.isRequired,
infrastructureMonitor: PropTypes.object.isRequired,
errors: PropTypes.object.isRequired,
diff --git a/Client/src/Pages/Infrastructure/CreateMonitor/index.jsx b/client/src/Pages/Infrastructure/Create/index.jsx
similarity index 68%
rename from Client/src/Pages/Infrastructure/CreateMonitor/index.jsx
rename to client/src/Pages/Infrastructure/Create/index.jsx
index c51b56360..144f499fd 100644
--- a/Client/src/Pages/Infrastructure/CreateMonitor/index.jsx
+++ b/client/src/Pages/Infrastructure/Create/index.jsx
@@ -1,17 +1,18 @@
// React, Redux, Router
import { useTheme } from "@emotion/react";
-import { useNavigate } from "react-router-dom";
-import { useState } from "react";
+import { useNavigate, useParams } from "react-router-dom";
+import { useState, useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
// Utility and Network
import { infrastructureMonitorValidation } from "../../../Validation/validation";
-import { createInfrastructureMonitor } from "../../../Features/InfrastructureMonitors/infrastructureMonitorsSlice";
+import { createInfrastructureMonitor, updateInfrastructureMonitor } from "../../../Features/InfrastructureMonitors/infrastructureMonitorsSlice";
+import { useHardwareMonitorsFetch } from "../Details/Hooks/useHardwareMonitorsFetch";
import { capitalizeFirstLetter } from "../../../Utils/stringUtils";
+import { useTranslation } from "react-i18next";
// MUI
import { Box, Stack, Typography, Button, ButtonGroup } from "@mui/material";
-import LoadingButton from "@mui/lab/LoadingButton";
//Components
import Breadcrumbs from "../../../Components/Breadcrumbs";
@@ -22,7 +23,7 @@ import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments";
import { createToast } from "../../../Utils/toastUtils";
import Checkbox from "../../../Components/Inputs/Checkbox";
import Select from "../../../Components/Inputs/Select";
-import { CustomThreshold } from "./CustomThreshold";
+import { CustomThreshold } from "./Components/CustomThreshold";
const SELECT_VALUES = [
{ _id: 0.25, name: "15 seconds" },
@@ -49,10 +50,18 @@ const getAlertError = (errors) => {
const CreateInfrastructureMonitor = () => {
const theme = useTheme();
- const { user, authToken } = useSelector((state) => state.auth);
+ const { user } = useSelector((state) => state.auth);
const monitorState = useSelector((state) => state.infrastructureMonitor);
const dispatch = useDispatch();
const navigate = useNavigate();
+ const { monitorId } = useParams();
+ const { t } = useTranslation();
+
+ // Determine if we are creating or editing
+ const isCreate = typeof monitorId === "undefined";
+
+ // Fetch monitor details if editing
+ const { monitor, isLoading, networkError } = useHardwareMonitorsFetch({ monitorId });
// State
const [errors, setErrors] = useState({});
@@ -61,6 +70,7 @@ const CreateInfrastructureMonitor = () => {
url: "",
name: "",
notifications: [],
+ notify_email: false,
interval: 0.25,
cpu: false,
usage_cpu: "",
@@ -73,10 +83,44 @@ const CreateInfrastructureMonitor = () => {
secret: "",
});
+ // Populate form fields if editing
+ useEffect(() => {
+ if (isCreate || !monitor) return;
+
+ setInfrastructureMonitor({
+ url: monitor.url.replace(/^https?:\/\//, ""),
+ name: monitor.name || "",
+ notifications: monitor.notifications?.filter(n => typeof n === "object") || [],
+ notify_email: (monitor.notifications?.length ?? 0) > 0,
+ interval: monitor.interval / MS_PER_MINUTE,
+ cpu: monitor.thresholds?.usage_cpu !== undefined,
+ usage_cpu: monitor.thresholds?.usage_cpu ? monitor.thresholds.usage_cpu * 100 : "",
+
+ memory: monitor.thresholds?.usage_memory !== undefined,
+ usage_memory: monitor.thresholds?.usage_memory ? monitor.thresholds.usage_memory * 100 : "",
+
+ disk: monitor.thresholds?.usage_disk !== undefined,
+ usage_disk: monitor.thresholds?.usage_disk ? monitor.thresholds.usage_disk * 100 : "",
+
+ temperature: monitor.thresholds?.usage_temperature !== undefined,
+ usage_temperature: monitor.thresholds?.usage_temperature ? monitor.thresholds.usage_temperature * 100 : "",
+ secret: monitor.secret || "",
+ });
+ setHttps(monitor.url.startsWith("https"));
+ }, [isCreate, monitor]);
+
// Handlers
const handleCreateInfrastructureMonitor = async (event) => {
event.preventDefault();
+ const formattedNotifications = infrastructureMonitor.notifications.map((n) =>
+ typeof n === "string" ? { type: "email", address: n } : n
+ );
+
+ if (infrastructureMonitor.notify_email) {
+ formattedNotifications.push({ type: "email", address: user.email });
+ }
+
// Build the form
let form = {
url: `http${https ? "s" : ""}://` + infrastructureMonitor.url,
@@ -102,6 +146,7 @@ const CreateInfrastructureMonitor = () => {
? { usage_temperature: infrastructureMonitor.usage_temperature }
: {}),
secret: infrastructureMonitor.secret,
+ notifications: formattedNotifications,
};
const { error } = infrastructureMonitorValidation.validate(form, {
@@ -148,14 +193,17 @@ const CreateInfrastructureMonitor = () => {
thresholds,
};
- const action = await dispatch(
- createInfrastructureMonitor({ authToken, monitor: form })
- );
+ // Handle create or update
+ const action = isCreate
+ ? await dispatch(createInfrastructureMonitor({ monitor: form }))
+ : await dispatch(updateInfrastructureMonitor({ monitorId, monitor: form }));
if (action.meta.requestStatus === "fulfilled") {
- createToast({ body: "Infrastructure monitor created successfully!" });
+ createToast({
+ body: isCreate ? t("infrastructureMonitorCreated") : t("infrastructureMonitorUpdated"),
+ });
navigate("/infrastructure");
} else {
- createToast({ body: "Failed to create monitor." });
+ createToast({ body: "Failed to save monitor." });
}
};
@@ -186,37 +234,34 @@ const CreateInfrastructureMonitor = () => {
};
const handleNotifications = (event, type) => {
- const { value } = event.target;
+ const { value, checked } = event.target;
let notifications = [...infrastructureMonitor.notifications];
- const notificationExists = notifications.some((notification) => {
- if (notification.type === type && notification.address === value) {
- return true;
+
+ if (checked) {
+ if (!notifications.some((n) => n.type === type && n.address === value)) {
+ notifications.push({ type, address: value });
}
- return false;
- });
- if (notificationExists) {
- notifications = notifications.filter((notification) => {
- if (notification.type === type && notification.address === value) {
- return false;
- }
- return true;
- });
} else {
- notifications.push({ type, address: value });
+ notifications = notifications.filter((n) => !(n.type === type && n.address === value));
}
-
+
setInfrastructureMonitor((prev) => ({
...prev,
notifications,
+ ...(type === "email" ? { notify_email: checked } : {})
}));
};
+
return (
{
component="span"
fontSize="inherit"
>
- Create your{" "}
+ {t(isCreate? "infrastructureCreateYour": "infrastructureEditYour")}{" "}
{
fontSize="inherit"
fontWeight="inherit"
>
- monitor
+ {t("monitor")}
- General settings
+ {t("settingsGeneralSettings")}
- Here you can select the URL of the host, together with the friendly name and
- authorization secret to connect to the server agent.
+ {t("infrastructureCreateGeneralSettingsDescription")}
- The server you are monitoring must be running the{" "}
+ {t("infrastructureServerRequirement")}{" "}
{
name="url"
startAdornment={ }
placeholder={"localhost:59232/api/v1/metrics"}
- label="Server URL"
+ label={t("infrastructureServerUrlLabel")}
https={https}
value={infrastructureMonitor.url}
onChange={handleChange}
error={errors["url"] ? true : false}
helperText={errors["url"]}
+ disabled={!isCreate}
/>
+ {isCreate && (
- Protocol
+ {t("infrastructureProtocol")}
setHttps(true)}
>
- HTTPS
+ {t("https")}
setHttps(false)}
>
- HTTP
+ {t("http")}
+ )}
{
type="text"
id="secret"
name="secret"
- label="Authorization secret"
+ label={t("infrastructureAuthorizationSecretLabel")}
value={infrastructureMonitor.secret}
onChange={handleChange}
error={errors["secret"] ? true : false}
@@ -321,18 +368,16 @@ const CreateInfrastructureMonitor = () => {
- Incident notifications
+ {t("distributedUptimeCreateIncidentNotification")}
- When there is an incident, notify users.
+ {t("distributedUptimeCreateIncidentDescription")}
notification.type === "email"
- )}
+ isChecked={infrastructureMonitor.notify_email}
value={user?.email}
onChange={(event) => handleNotifications(event, "email")}
/>
@@ -340,10 +385,9 @@ const CreateInfrastructureMonitor = () => {
- Customize alerts
+ {t("infrastructureCustomizeAlerts")}
- Send a notification to user(s) when thresholds exceed a specified
- percentage.
+ {t("infrastructureAlertNotificationDescription")}
@@ -364,7 +408,7 @@ const CreateInfrastructureMonitor = () => {
isChecked={infrastructureMonitor[metric]}
fieldId={METRIC_PREFIX + metric}
fieldName={METRIC_PREFIX + metric}
- fieldValue={infrastructureMonitor[METRIC_PREFIX + metric]}
+ fieldValue={String(infrastructureMonitor[METRIC_PREFIX + metric])}
onFieldChange={handleChange}
alertUnit={metric == "temperature" ? "°C" : "%"}
/>
@@ -388,7 +432,7 @@ const CreateInfrastructureMonitor = () => {
- Advanced settings
+ {t("distributedUptimeCreateAdvancedSettings")}
{
direction="row"
justifyContent="flex-end"
>
-
- Create infrastructure monitor
-
+ {t(isCreate? "infrastructureCreateMonitor": "infrastructureEditMonitor")}
+
diff --git a/client/src/Pages/Infrastructure/Details/Components/AreaChartBoxes/InfraAreaChart.jsx b/client/src/Pages/Infrastructure/Details/Components/AreaChartBoxes/InfraAreaChart.jsx
new file mode 100644
index 000000000..9544bcf2a
--- /dev/null
+++ b/client/src/Pages/Infrastructure/Details/Components/AreaChartBoxes/InfraAreaChart.jsx
@@ -0,0 +1,37 @@
+// Components
+import { Typography } from "@mui/material";
+import BaseContainer from "../BaseContainer";
+import AreaChart from "../../../../../Components/Charts/AreaChart";
+// Utils
+import { useTheme } from "@emotion/react";
+import { useHardwareUtils } from "../../Hooks/useHardwareUtils";
+const InfraAreaChart = ({ config }) => {
+ const theme = useTheme();
+ const { getDimensions } = useHardwareUtils();
+ return (
+
+
+ {config.heading}
+
+
+
+ );
+};
+
+export default InfraAreaChart;
diff --git a/client/src/Pages/Infrastructure/Details/Components/AreaChartBoxes/index.jsx b/client/src/Pages/Infrastructure/Details/Components/AreaChartBoxes/index.jsx
new file mode 100644
index 000000000..0eb3aa36d
--- /dev/null
+++ b/client/src/Pages/Infrastructure/Details/Components/AreaChartBoxes/index.jsx
@@ -0,0 +1,140 @@
+// Components
+import { Stack } from "@mui/material";
+import InfraAreaChart from "./InfraAreaChart";
+import SkeletonLayout from "./skeleton";
+
+// Utils
+import {
+ PercentTick,
+ TzTick,
+ InfrastructureTooltip,
+ TemperatureTooltip,
+} from "../../../../../Components/Charts/Utils/chartUtils";
+import { useTheme } from "@emotion/react";
+import { useHardwareUtils } from "../../Hooks/useHardwareUtils";
+import { useTranslation } from "react-i18next";
+const AreaChartBoxes = ({ shouldRender, monitor, dateRange }) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ const { buildTemps } = useHardwareUtils();
+
+ if (!shouldRender) {
+ return ;
+ }
+
+ const { stats } = monitor ?? {};
+ const { checks } = stats;
+
+ let latestCheck = checks[0];
+ const { temps, tempKeys } = buildTemps(checks);
+
+ const configs = [
+ {
+ type: "memory",
+ data: checks,
+ dataKeys: ["avgMemoryUsage"],
+ heading: t("memoryUsage"),
+ strokeColor: theme.palette.accent.main, // CAIO_REVIEW
+ gradientStartColor: theme.palette.accent.main, // CAIO_REVIEW
+ yLabel: t("memoryUsage"),
+ yDomain: [0, 1],
+ yTick: ,
+ xTick: ,
+ toolTip: (
+
+ ),
+ },
+ {
+ type: "cpu",
+ data: checks,
+ dataKeys: ["avgCpuUsage"],
+ heading: t("cpuUsage"),
+ strokeColor: theme.palette.success.main,
+ gradientStartColor: theme.palette.success.main,
+ yLabel: t("cpuUsage"),
+ yDomain: [0, 1],
+ yTick: ,
+ xTick: ,
+ toolTip: (
+
+ ),
+ },
+ {
+ type: "temperature",
+ data: temps,
+ dataKeys: tempKeys,
+ strokeColor: theme.palette.error.main,
+ gradientStartColor: theme.palette.error.main,
+ heading: t("cpuTemperature"),
+ yLabel: "Temperature",
+ xTick: ,
+ yDomain: [
+ 0,
+ Math.max(Math.max(...temps.flatMap((t) => tempKeys.map((k) => t[k]))) * 1.1, 200),
+ ],
+ toolTip: (
+
+ ),
+ },
+ ...(latestCheck?.disks?.map((disk, idx) => ({
+ type: "disk",
+ data: checks,
+ diskIndex: idx,
+ dataKeys: [`disks[${idx}].usagePercent`],
+ heading: `Disk${idx} usage`,
+ strokeColor: theme.palette.warning.main,
+ gradientStartColor: theme.palette.warning.main,
+ yLabel: t("diskUsage"),
+ yDomain: [0, 1],
+ yTick: ,
+ xTick: ,
+ toolTip: (
+
+ ),
+ })) || []),
+ ];
+
+ return (
+ *": {
+ flexBasis: `calc(50% - ${theme.spacing(8)})`,
+ maxWidth: `calc(50% - ${theme.spacing(8)})`,
+ },
+ }}
+ >
+ {configs.map((config) => (
+
+ ))}
+
+ );
+};
+
+export default AreaChartBoxes;
diff --git a/client/src/Pages/Infrastructure/Details/Components/AreaChartBoxes/skeleton.jsx b/client/src/Pages/Infrastructure/Details/Components/AreaChartBoxes/skeleton.jsx
new file mode 100644
index 000000000..f787b88ec
--- /dev/null
+++ b/client/src/Pages/Infrastructure/Details/Components/AreaChartBoxes/skeleton.jsx
@@ -0,0 +1,25 @@
+import { Stack, Skeleton } from "@mui/material";
+import { useTheme } from "@emotion/react";
+const SkeletonLayout = () => {
+ const theme = useTheme();
+ return (
+
+
+
+
+ );
+};
+
+export default SkeletonLayout;
diff --git a/client/src/Pages/Infrastructure/Details/Components/BaseContainer/index.jsx b/client/src/Pages/Infrastructure/Details/Components/BaseContainer/index.jsx
new file mode 100644
index 000000000..246769751
--- /dev/null
+++ b/client/src/Pages/Infrastructure/Details/Components/BaseContainer/index.jsx
@@ -0,0 +1,43 @@
+/**
+ * Renders a base box with consistent styling
+ * @param {Object} props - Component properties
+ * @param {React.ReactNode} props.children - Child components to render inside the box
+ * @param {Object} props.sx - Additional styling for the box
+ * @returns {React.ReactElement} Styled box component
+ */
+
+// Components
+import { Box } from "@mui/material";
+
+// Utils
+import { useTheme } from "@emotion/react";
+import { useHardwareUtils } from "../../Hooks/useHardwareUtils";
+import PropTypes from "prop-types";
+
+const BaseContainer = ({ children, sx = {} }) => {
+ const theme = useTheme();
+ const { getDimensions } = useHardwareUtils();
+ return (
+
+ {children}
+
+ );
+};
+
+BaseContainer.propTypes = {
+ children: PropTypes.node.isRequired,
+ sx: PropTypes.object,
+};
+
+export default BaseContainer;
diff --git a/client/src/Pages/Infrastructure/Details/Components/GaugeBoxes/Gauge.jsx b/client/src/Pages/Infrastructure/Details/Components/GaugeBoxes/Gauge.jsx
new file mode 100644
index 000000000..d374d1960
--- /dev/null
+++ b/client/src/Pages/Infrastructure/Details/Components/GaugeBoxes/Gauge.jsx
@@ -0,0 +1,83 @@
+// Components
+import CustomGauge from "../../../../../Components/Charts/CustomGauge";
+import BaseContainer from "../BaseContainer";
+import { Stack, Typography, Box } from "@mui/material";
+// Utils
+import { useTheme } from "@emotion/react";
+import PropTypes from "prop-types";
+
+const Gauge = ({ value, heading, metricOne, valueOne, metricTwo, valueTwo }) => {
+ const theme = useTheme();
+
+ const valueStyle = {
+ borderRadius: theme.spacing(2),
+ backgroundColor: theme.palette.tertiary.main,
+ width: "40%",
+ mb: theme.spacing(2),
+ mt: theme.spacing(2),
+ pr: theme.spacing(2),
+ textAlign: 'right'
+ }
+
+ return (
+
+
+
+
+ {heading}
+
+
+
+ {metricOne}
+ {valueOne}
+
+
+ {metricTwo}
+ {valueTwo}
+
+
+
+
+ );
+};
+
+Gauge.propTypes = {
+ value: PropTypes.number,
+ heading: PropTypes.string,
+ metricOne: PropTypes.string,
+ valueOne: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
+ metricTwo: PropTypes.string,
+ valueTwo: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
+};
+
+export default Gauge;
diff --git a/client/src/Pages/Infrastructure/Details/Components/GaugeBoxes/index.jsx b/client/src/Pages/Infrastructure/Details/Components/GaugeBoxes/index.jsx
new file mode 100644
index 000000000..4dd978018
--- /dev/null
+++ b/client/src/Pages/Infrastructure/Details/Components/GaugeBoxes/index.jsx
@@ -0,0 +1,82 @@
+// Components
+import { Stack } from "@mui/material";
+import Gauge from "./Gauge";
+import SkeletonLayout from "./skeleton";
+
+// Utils
+import { useHardwareUtils } from "../../Hooks/useHardwareUtils";
+import { useTheme } from "@emotion/react";
+import { useTranslation } from "react-i18next";
+
+const Gauges = ({ shouldRender, monitor }) => {
+ const { decimalToPercentage, formatBytes } = useHardwareUtils();
+ const theme = useTheme();
+ const { t } = useTranslation();
+
+ if (!shouldRender) {
+ return ;
+ }
+
+ const { stats } = monitor ?? {};
+ let latestCheck = stats?.aggregateData?.latestCheck;
+ const memoryUsagePercent = latestCheck?.memory?.usage_percent ?? 0;
+ const memoryUsedBytes = latestCheck?.memory?.used_bytes ?? 0;
+ const memoryTotalBytes = latestCheck?.memory?.total_bytes ?? 0;
+ const cpuUsagePercent = latestCheck?.cpu?.usage_percent ?? 0;
+ const cpuPhysicalCores = latestCheck?.cpu?.physical_core ?? 0;
+ const cpuFrequency = latestCheck?.cpu?.frequency ?? 0;
+
+ const gauges = [
+ {
+ type: "memory",
+ value: decimalToPercentage(memoryUsagePercent),
+ heading: t("memoryUsage"),
+ metricOne: t("used"),
+ valueOne: formatBytes(memoryUsedBytes, true),
+ metricTwo: t("total"),
+ valueTwo: formatBytes(memoryTotalBytes, true),
+ },
+ {
+ type: "cpu",
+ value: decimalToPercentage(cpuUsagePercent),
+ heading: t("cpuUsage"),
+ metricOne: t("cores"),
+ valueOne: cpuPhysicalCores ?? 0,
+ metricTwo: t("frequency"),
+ valueTwo: `${(cpuFrequency / 1000).toFixed(2)} Ghz`,
+ },
+ ...(latestCheck?.disk ?? []).map((disk, idx) => ({
+ type: "disk",
+ diskIndex: idx,
+ value: decimalToPercentage(disk.usage_percent),
+ heading: `Disk${idx} usage`,
+ metricOne: t("used"),
+ valueOne: formatBytes(disk.total_bytes - disk.free_bytes, true),
+ metricTwo: t("total"),
+ valueTwo: formatBytes(disk.total_bytes, true),
+ })),
+ ];
+
+ return (
+
+ {gauges.map((gauge) => {
+ return (
+
+ );
+ })}
+
+ );
+};
+
+export default Gauges;
diff --git a/client/src/Pages/Infrastructure/Details/Components/GaugeBoxes/skeleton.jsx b/client/src/Pages/Infrastructure/Details/Components/GaugeBoxes/skeleton.jsx
new file mode 100644
index 000000000..347a52901
--- /dev/null
+++ b/client/src/Pages/Infrastructure/Details/Components/GaugeBoxes/skeleton.jsx
@@ -0,0 +1,26 @@
+import { Stack, Skeleton } from "@mui/material";
+import { useTheme } from "@emotion/react";
+
+const SkeletonLayout = () => {
+ const theme = useTheme();
+
+ return (
+
+ {Array.from({ length: 3 }).map((_, idx) => {
+ return (
+
+ );
+ })}
+
+ );
+};
+
+export default SkeletonLayout;
diff --git a/client/src/Pages/Infrastructure/Details/Components/StatusBoxes/index.jsx b/client/src/Pages/Infrastructure/Details/Components/StatusBoxes/index.jsx
new file mode 100644
index 000000000..447831acb
--- /dev/null
+++ b/client/src/Pages/Infrastructure/Details/Components/StatusBoxes/index.jsx
@@ -0,0 +1,116 @@
+// Components
+import { Stack, Typography } from "@mui/material";
+import StatusBoxes from "../../../../../Components/StatusBoxes";
+import StatBox from "../../../../../Components/StatBox";
+
+//Utils
+import useUtils from "../../../../../Pages/Uptime/Monitors/Hooks/useUtils";
+import { useHardwareUtils } from "../../Hooks/useHardwareUtils";
+import { useTranslation } from "react-i18next";
+
+const InfraStatBoxes = ({ shouldRender, monitor }) => {
+ // Utils
+ const { formatBytes } = useHardwareUtils();
+ const { determineState } = useUtils();
+ const { t } = useTranslation();
+
+ const { stats, uptimePercentage } = monitor ?? {};
+ const latestCheck = stats?.aggregateData?.latestCheck;
+
+ // Get data from latest check
+ const physicalCores = latestCheck?.cpu?.physical_core ?? 0;
+ const logicalCores = latestCheck?.cpu?.logical_core ?? 0;
+ const cpuFrequency = latestCheck?.cpu?.frequency ?? 0;
+ const cpuTemperature =
+ latestCheck?.cpu?.temperature?.length > 0
+ ? latestCheck.cpu.temperature.reduce((acc, curr) => acc + curr, 0) /
+ latestCheck.cpu.temperature.length
+ : 0;
+ const memoryTotalBytes = latestCheck?.memory?.total_bytes ?? 0;
+ const diskTotalBytes = latestCheck?.disk[0]?.total_bytes ?? 0;
+ const os = latestCheck?.host?.os ?? undefined;
+ const platform = latestCheck?.host?.platform ?? undefined;
+ const osPlatform =
+ typeof os === "undefined" && typeof platform === "undefined"
+ ? undefined
+ : `${os} ${platform}`;
+
+ return (
+
+
+
+ {physicalCores}
+
+ {physicalCores === 1 ? "core" : "cores"}
+
+ >
+ }
+ />
+
+ {logicalCores}
+
+ {logicalCores === 1 ? "core" : "cores"}
+
+ >
+ }
+ />
+
+ {(cpuFrequency / 1000).toFixed(2)}
+ Ghz
+ >
+ }
+ />
+
+ {cpuTemperature.toFixed(2)}
+ °C
+ >
+ }
+ />
+
+
+
+ {(uptimePercentage * 100).toFixed(2)}
+ %
+ >
+ }
+ />
+
+
+ );
+};
+
+export default InfraStatBoxes;
diff --git a/client/src/Pages/Infrastructure/Details/Hooks/useHardwareMonitorsFetch.jsx b/client/src/Pages/Infrastructure/Details/Hooks/useHardwareMonitorsFetch.jsx
new file mode 100644
index 000000000..dfdf92715
--- /dev/null
+++ b/client/src/Pages/Infrastructure/Details/Hooks/useHardwareMonitorsFetch.jsx
@@ -0,0 +1,39 @@
+import { useEffect, useState } from "react";
+import { networkService } from "../../../../main";
+
+const useHardwareMonitorsFetch = ({ monitorId, dateRange }) => {
+
+ // Abort early if creating monitor
+ if (!monitorId) {
+ return { monitor: undefined, isLoading: false, networkError: undefined };
+ }
+ const [isLoading, setIsLoading] = useState(true);
+ const [networkError, setNetworkError] = useState(false);
+ const [monitor, setMonitor] = useState(undefined);
+
+ useEffect(() => {
+ const fetchData = async () => {
+ try {
+ const response = await networkService.getHardwareDetailsByMonitorId({
+ monitorId: monitorId,
+ dateRange: dateRange,
+ });
+ response.data.data;
+ setMonitor(response.data.data);
+ } catch (error) {
+ setNetworkError(true);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+ fetchData();
+ }, [monitorId, dateRange]);
+
+ return {
+ isLoading,
+ networkError,
+ monitor,
+ };
+};
+
+export { useHardwareMonitorsFetch };
diff --git a/client/src/Pages/Infrastructure/Details/Hooks/useHardwareUtils.jsx b/client/src/Pages/Infrastructure/Details/Hooks/useHardwareUtils.jsx
new file mode 100644
index 000000000..a2e4c5153
--- /dev/null
+++ b/client/src/Pages/Infrastructure/Details/Hooks/useHardwareUtils.jsx
@@ -0,0 +1,140 @@
+import { Typography } from "@mui/material";
+import { useTheme } from "@emotion/react";
+import { useTranslation } from "react-i18next";
+
+// Constants
+const BASE_BOX_PADDING_VERTICAL = 4;
+const BASE_BOX_PADDING_HORIZONTAL = 8;
+const TYPOGRAPHY_PADDING = 8;
+const CHART_CONTAINER_HEIGHT = 300;
+
+const useHardwareUtils = () => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+
+ const getDimensions = () => {
+ const totalTypographyPadding = parseInt(theme.spacing(TYPOGRAPHY_PADDING), 10) * 2;
+ const totalChartContainerPadding =
+ parseInt(theme.spacing(BASE_BOX_PADDING_VERTICAL), 10) * 2;
+ return {
+ baseBoxPaddingVertical: BASE_BOX_PADDING_VERTICAL,
+ baseBoxPaddingHorizontal: BASE_BOX_PADDING_HORIZONTAL,
+ totalContainerPadding: parseInt(theme.spacing(BASE_BOX_PADDING_VERTICAL), 10) * 2,
+ areaChartHeight:
+ CHART_CONTAINER_HEIGHT - totalChartContainerPadding - totalTypographyPadding,
+ };
+ };
+
+ const formatBytes = (bytes, space = false) => {
+ if (bytes === undefined || bytes === null)
+ return (
+ <>
+ {0}
+ {space ? " " : ""}
+ {t("gb")}
+ >
+ );
+ if (typeof bytes !== "number")
+ return (
+ <>
+ {0}
+ {space ? " " : ""}
+ {t("gb")}
+ >
+ );
+ if (bytes === 0)
+ return (
+ <>
+ {0}
+ {space ? " " : ""}
+ {t("gb")}
+ >
+ );
+
+ const GB = bytes / (1024 * 1024 * 1024);
+ const MB = bytes / (1024 * 1024);
+
+ if (GB >= 1) {
+ return (
+ <>
+ {Number(GB.toFixed(0))}
+ {space ? " " : ""}
+ {t("gb")}
+ >
+ );
+ } else {
+ return (
+ <>
+ {Number(MB.toFixed(0))}
+ {space ? " " : ""}
+ {t("mb")}
+ >
+ );
+ }
+ };
+
+ /**
+ * Converts a decimal value to a percentage
+ *
+ * @function decimalToPercentage
+ * @param {number} value - Decimal value to convert
+ * @returns {number} Percentage representation
+ *
+ * @example
+ * decimalToPercentage(0.75) // Returns 75
+ * decimalToPercentage(null) // Returns 0
+ */
+ const decimalToPercentage = (value) => {
+ if (value === null || value === undefined) return 0;
+ return value * 100;
+ };
+
+ const buildTemps = (checks) => {
+ let numCores = 1;
+ if (checks === null) return { temps: [], tempKeys: [] };
+
+ for (const check of checks) {
+ if (check?.avgTemperature?.length > numCores) {
+ numCores = check.avgTemperature.length;
+ break;
+ }
+ }
+ const temps = checks.map((check) => {
+ // If there's no data, set the temperature to 0
+ if (
+ check?.avgTemperature?.length === 0 ||
+ check?.avgTemperature === undefined ||
+ check?.avgTemperature === null
+ ) {
+ check.avgTemperature = Array(numCores).fill(0);
+ }
+ const res = check?.avgTemperature?.reduce(
+ (acc, cur, idx) => {
+ acc[`core${idx + 1}`] = cur;
+ return acc;
+ },
+ {
+ _id: check._id,
+ }
+ );
+ return res;
+ });
+ if (temps.length === 0 || !temps[0]) {
+ return { temps: [], tempKeys: [] };
+ }
+
+ return {
+ tempKeys: Object.keys(temps[0] || {}).filter((key) => key !== "_id"),
+ temps,
+ };
+ };
+
+ return {
+ formatBytes,
+ decimalToPercentage,
+ buildTemps,
+ getDimensions,
+ };
+};
+
+export { useHardwareUtils };
diff --git a/client/src/Pages/Infrastructure/Details/index.jsx b/client/src/Pages/Infrastructure/Details/index.jsx
new file mode 100644
index 000000000..f7f96f931
--- /dev/null
+++ b/client/src/Pages/Infrastructure/Details/index.jsx
@@ -0,0 +1,103 @@
+// Components
+import { Stack, Typography } from "@mui/material";
+import Breadcrumbs from "../../../Components/Breadcrumbs";
+import MonitorStatusHeader from "../../../Components/MonitorStatusHeader";
+import MonitorTimeFrameHeader from "../../../Components/MonitorTimeFrameHeader";
+import StatusBoxes from "./Components/StatusBoxes";
+import GaugeBoxes from "./Components/GaugeBoxes";
+import AreaChartBoxes from "./Components/AreaChartBoxes";
+import GenericFallback from "../../../Components/GenericFallback";
+
+// Utils
+import { useTheme } from "@emotion/react";
+import { useIsAdmin } from "../../../Hooks/useIsAdmin";
+import { useHardwareMonitorsFetch } from "./Hooks/useHardwareMonitorsFetch";
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { useParams } from "react-router-dom";
+
+// Constants
+const BREADCRUMBS = [
+ { name: "infrastructure monitors", path: "/infrastructure" },
+ { name: "details", path: "" },
+];
+const InfrastructureDetails = () => {
+ // Redux state
+
+ // Local state
+ const [dateRange, setDateRange] = useState("recent");
+
+ // Utils
+ const theme = useTheme();
+ const { monitorId } = useParams();
+ const { t } = useTranslation();
+ const isAdmin = useIsAdmin();
+
+ const { isLoading, networkError, monitor } = useHardwareMonitorsFetch({
+ monitorId,
+ dateRange,
+ });
+
+ if (networkError === true) {
+ return (
+
+
+ {t("networkError")}
+
+ {t("checkConnection")}
+
+ );
+ }
+
+ if (!isLoading && monitor?.stats?.checks?.length === 0) {
+ return (
+
+
+
+
+ {t("distributedUptimeDetailsNoMonitorHistory")}
+
+
+ );
+ }
+
+ return (
+
+
+
+
+
+
+
+
+ );
+};
+
+export default InfrastructureDetails;
diff --git a/client/src/Pages/Infrastructure/Monitors/Components/Filters/index.jsx b/client/src/Pages/Infrastructure/Monitors/Components/Filters/index.jsx
new file mode 100644
index 000000000..a2d82613c
--- /dev/null
+++ b/client/src/Pages/Infrastructure/Monitors/Components/Filters/index.jsx
@@ -0,0 +1,89 @@
+import { useTheme } from "@emotion/react";
+import PropTypes from "prop-types";
+import FilterHeader from "../../../../../Components/FilterHeader";
+import { useMemo } from "react";
+import { Box, Button } from "@mui/material";
+import ClearIcon from "@mui/icons-material/Clear";
+import { useTranslation } from "react-i18next";
+
+/**
+ * Filter Component
+ *
+ * A high-level component that provides filtering options for status in Infrastructure Page.
+ * It allows users to select multiple options for each filter and reset the filters.
+ *
+ * @component
+ * @param {Object} props - The component props.
+ * @param {string[]} props.selectedStatus - An array of selected status values.
+ * @param {function} props.setSelectedStatus - A function to set the selected status values.
+ * @param {function} props.setToFilterStatus - A function to set the filter status based on selected status values.
+ * @param {function} props.handleReset - A function to reset all filters.
+ *
+ * @returns {JSX.Element} The rendered Filter component.
+ */
+
+const statusOptions = [
+ { value: "Up", label: "Up" },
+ { value: "Down", label: "Down" },
+];
+
+const Filter = ({
+ selectedStatus,
+ setSelectedStatus,
+ setToFilterStatus,
+ handleReset,
+}) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+
+ const handleStatusChange = (event) => {
+ const selectedValues = event.target.value;
+ setSelectedStatus(selectedValues.length > 0 ? selectedValues : undefined);
+
+ if (selectedValues.length === 0 || selectedValues.length === 2) {
+ setToFilterStatus(undefined);
+ } else {
+ setToFilterStatus(selectedValues[0] === "Up" ? "true" : "false");
+ }
+ };
+
+ const isFilterActive = useMemo(() => {
+ return (selectedStatus?.length ?? 0) > 0;
+ }, [selectedStatus]);
+
+ return (
+
+
+ }
+ sx={{
+ visibility: isFilterActive ? "visible" : "hidden",
+ }}
+ >
+ {t("reset")}
+
+
+ );
+};
+
+Filter.propTypes = {
+ selectedStatus: PropTypes.arrayOf(PropTypes.string),
+ setSelectedStatus: PropTypes.func.isRequired,
+ setToFilterStatus: PropTypes.func.isRequired,
+ handleReset: PropTypes.func.isRequired,
+};
+
+export default Filter;
diff --git a/client/src/Pages/Infrastructure/Monitors/Components/MonitorsTable/index.jsx b/client/src/Pages/Infrastructure/Monitors/Components/MonitorsTable/index.jsx
new file mode 100644
index 000000000..25847b1be
--- /dev/null
+++ b/client/src/Pages/Infrastructure/Monitors/Components/MonitorsTable/index.jsx
@@ -0,0 +1,153 @@
+// Components
+import DataTable from "../../../../../Components/Table";
+import Host from "../../../../../Components/Host";
+import { StatusLabel } from "../../../../../Components/Label";
+import { Stack } from "@mui/material";
+import { InfrastructureMenu } from "../MonitorsTableMenu";
+// Assets
+import CPUChipIcon from "../../../../../assets/icons/cpu-chip.svg?react";
+import CustomGauge from "../../../../../Components/Charts/CustomGauge";
+
+// Utils
+import { useTheme } from "@emotion/react";
+import useUtils from "../../../../Uptime/Monitors/Hooks/useUtils";
+import { useNavigate } from "react-router-dom";
+import PropTypes from "prop-types";
+import { useTranslation } from "react-i18next";
+
+const MonitorsTable = ({ shouldRender, monitors, isAdmin, handleActionMenuDelete }) => {
+ // Utils
+ const theme = useTheme();
+ const { t } = useTranslation();
+ const { determineState } = useUtils();
+ const navigate = useNavigate();
+
+ // Handlers
+ const openDetails = (id) => {
+ navigate(`/infrastructure/${id}`);
+ };
+ const headers = [
+ {
+ id: "host",
+ content: t("host"),
+ render: (row) => (
+
+ ),
+ },
+ {
+ id: "status",
+ content: t("incidentsTableStatus"),
+ render: (row) => (
+
+ ),
+ },
+ {
+ id: "frequency",
+ content: t("frequency"),
+ render: (row) => (
+
+
+ {row.processor}
+
+ ),
+ },
+ { id: "cpu", content: t("cpu"), render: (row) => },
+ {
+ id: "memory",
+ content: t("memory"),
+ render: (row) => ,
+ },
+ {
+ id: "disk",
+ content: t("disk"),
+ render: (row) => ,
+ },
+ {
+ id: "actions",
+ content: t("actions"),
+ render: (row) => (
+
+ ),
+ },
+ ];
+
+ const data = monitors?.map((monitor) => {
+ const processor =
+ ((monitor.checks[0]?.cpu?.frequency ?? 0) / 1000).toFixed(2) + " GHz";
+ const cpu = (monitor?.checks[0]?.cpu.usage_percent ?? 0) * 100;
+ const mem = (monitor?.checks[0]?.memory.usage_percent ?? 0) * 100;
+ const disk = (monitor?.checks[0]?.disk[0]?.usage_percent ?? 0) * 100;
+ const status = determineState(monitor);
+ const uptimePercentage = ((monitor?.uptimePercentage ?? 0) * 100)
+ .toFixed(2)
+ .toString();
+ const percentageColor =
+ monitor.uptimePercentage < 0.25
+ ? theme.palette.error.main
+ : monitor.uptimePercentage < 0.5
+ ? theme.palette.warning.main
+ : theme.palette.success.main;
+
+ return {
+ id: monitor._id,
+ name: monitor.name,
+ url: monitor.url,
+ processor,
+ cpu,
+ mem,
+ disk,
+ status,
+ uptimePercentage,
+ percentageColor,
+ };
+ });
+
+ return (
+ openDetails(row.id),
+ emptyView: "No monitors found",
+ }}
+ />
+ );
+};
+
+MonitorsTable.propTypes = {
+ shouldRender: PropTypes.bool,
+ monitors: PropTypes.array,
+ isAdmin: PropTypes.bool,
+ handleActionMenuDelete: PropTypes.func,
+};
+
+export default MonitorsTable;
diff --git a/Client/src/Pages/Infrastructure/components/Menu/index.jsx b/client/src/Pages/Infrastructure/Monitors/Components/MonitorsTableMenu/index.jsx
similarity index 90%
rename from Client/src/Pages/Infrastructure/components/Menu/index.jsx
rename to client/src/Pages/Infrastructure/Monitors/Components/MonitorsTableMenu/index.jsx
index f036b9d86..bce3020a6 100644
--- a/Client/src/Pages/Infrastructure/components/Menu/index.jsx
+++ b/client/src/Pages/Infrastructure/Monitors/Components/MonitorsTableMenu/index.jsx
@@ -4,12 +4,12 @@ import { useRef, useState } from "react";
import { useSelector } from "react-redux";
import { useTheme } from "@emotion/react";
import { useNavigate } from "react-router-dom";
-import { createToast } from "../../../../Utils/toastUtils";
+import { createToast } from "../../../../../Utils/toastUtils";
import { IconButton, Menu, MenuItem } from "@mui/material";
-import Settings from "../../../../assets/icons/settings-bold.svg?react";
+import Settings from "../../../../../assets/icons/settings-bold.svg?react";
import PropTypes from "prop-types";
-import Dialog from "../../../../Components/Dialog";
-import { networkService } from "../../../../Utils/NetworkService.js";
+import Dialog from "../../../../../Components/Dialog";
+import { networkService } from "../../../../../Utils/NetworkService.js";
/**
* InfrastructureMenu Component
@@ -30,8 +30,6 @@ const InfrastructureMenu = ({ monitor, isAdmin, updateCallback }) => {
const [isOpen, setIsOpen] = useState(false);
const [isDialogOpen, setIsDialogOpen] = useState(false);
const theme = useTheme();
- const authState = useSelector((state) => state.auth);
- const authToken = authState.authToken;
const { isLoading } = useSelector((state) => state.uptimeMonitors);
const openMenu = (e) => {
@@ -61,7 +59,6 @@ const InfrastructureMenu = ({ monitor, isAdmin, updateCallback }) => {
const handleRemove = async () => {
try {
await networkService.deleteMonitorById({
- authToken,
monitorId: monitor.id,
});
createToast({ body: "Monitor deleted successfully." });
@@ -78,6 +75,7 @@ const InfrastructureMenu = ({ monitor, isAdmin, updateCallback }) => {
{
+ // Redux state
+ const { user } = useSelector((state) => state.auth);
+
+ // Local state
+ const [isLoading, setIsLoading] = useState(true);
+ const [networkError, setNetworkError] = useState(false);
+ const [monitors, setMonitors] = useState(undefined);
+ const [summary, setSummary] = useState(undefined);
+
+ useEffect(() => {
+ const fetchMonitors = async () => {
+ try {
+ const response = await networkService.getMonitorsByTeamId({
+ teamId: user.teamId,
+ limit: 1,
+ field: field,
+ filter: filter,
+ types: ["hardware"],
+ page: page,
+ rowsPerPage: rowsPerPage,
+ });
+ setMonitors(response?.data?.data?.filteredMonitors ?? []);
+ setSummary(response?.data?.data?.summary ?? {});
+ } catch (error) {
+ setNetworkError(true);
+ createToast({
+ body: error.message,
+ });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ fetchMonitors();
+ }, [page, field, filter, rowsPerPage, user.teamId, updateTrigger]);
+
+ return { monitors, summary, isLoading, networkError };
+};
+
+export { useMonitorFetch };
diff --git a/client/src/Pages/Infrastructure/Monitors/index.jsx b/client/src/Pages/Infrastructure/Monitors/index.jsx
new file mode 100644
index 000000000..0d22e98b5
--- /dev/null
+++ b/client/src/Pages/Infrastructure/Monitors/index.jsx
@@ -0,0 +1,130 @@
+// Components
+import { Stack, Typography } from "@mui/material";
+import Breadcrumbs from "../../../Components/Breadcrumbs";
+import MonitorCountHeader from "../../../Components/MonitorCountHeader";
+import MonitorCreateHeader from "../../../Components/MonitorCreateHeader";
+import MonitorsTable from "./Components/MonitorsTable";
+import Pagination from "../../..//Components/Table/TablePagination";
+import GenericFallback from "../../../Components/GenericFallback";
+import Fallback from "../../../Components/Fallback";
+import Filter from "./Components/Filters";
+// Utils
+import { useTheme } from "@emotion/react";
+import { useMonitorFetch } from "./Hooks/useMonitorFetch";
+import { useState } from "react";
+import { useIsAdmin } from "../../../Hooks/useIsAdmin";
+import { useTranslation } from "react-i18next";
+// Constants
+const BREADCRUMBS = [{ name: `infrastructure`, path: "/infrastructure" }];
+
+const InfrastructureMonitors = () => {
+ // Redux state
+ const [page, setPage] = useState(0);
+ const [rowsPerPage, setRowsPerPage] = useState(5);
+ const [updateTrigger, setUpdateTrigger] = useState(false);
+ const [selectedStatus, setSelectedStatus] = useState(undefined);
+ const [toFilterStatus, setToFilterStatus] = useState(undefined);
+
+ // Utils
+ const theme = useTheme();
+ const isAdmin = useIsAdmin();
+ const { t } = useTranslation();
+
+ // Handlers
+ const handleActionMenuDelete = () => {
+ setUpdateTrigger(!updateTrigger);
+ };
+
+ const handleChangePage = (event, newPage) => {
+ setPage(newPage);
+ };
+
+ const handleChangeRowsPerPage = (event) => {
+ setRowsPerPage(event.target.value);
+ };
+
+ const handleReset = () => {
+ setSelectedStatus(undefined);
+ setToFilterStatus(undefined);
+ };
+
+ const field = toFilterStatus !== undefined ? "status" : undefined;
+
+ const { monitors, summary, isLoading, networkError } = useMonitorFetch({
+ page,
+ field: field,
+ filter: toFilterStatus,
+ rowsPerPage,
+ updateTrigger,
+ });
+
+ if (networkError === true) {
+ return (
+
+
+ {t("networkError")}
+
+ {t("checkConnection")}
+
+ );
+ }
+
+ if (!isLoading && typeof summary?.totalMonitors === "undefined" ) {
+ return (
+
+ );
+ }
+
+ return (
+
+
+
+
+
+
+
+
+
+
+ );
+};
+
+export default InfrastructureMonitors;
diff --git a/Client/src/Pages/Integrations/index.css b/client/src/Pages/Integrations/index.css
similarity index 100%
rename from Client/src/Pages/Integrations/index.css
rename to client/src/Pages/Integrations/index.css
diff --git a/Client/src/Pages/Integrations/index.jsx b/client/src/Pages/Integrations/index.jsx
similarity index 88%
rename from Client/src/Pages/Integrations/index.jsx
rename to client/src/Pages/Integrations/index.jsx
index e74a1a450..4a91a26bc 100644
--- a/Client/src/Pages/Integrations/index.jsx
+++ b/client/src/Pages/Integrations/index.jsx
@@ -4,6 +4,7 @@ import { useTheme } from "@emotion/react";
import Discord from "../../assets/icons/discord-icon.svg?react";
import Slack from "../../assets/icons/slack-icon.svg?react";
import Zapier from "../../assets/icons/zapier-icon.svg?react";
+import { useTranslation } from "react-i18next";
import "./index.css";
@@ -18,6 +19,7 @@ import "./index.css";
*/
const IntegrationsComponent = ({ icon, header, info, onClick }) => {
const theme = useTheme();
+ const { t } = useTranslation();
return (
{
sx={{ alignSelf: "center" }}
disabled={true}
>
- Add
+ {t("add")}
@@ -81,6 +83,7 @@ IntegrationsComponent.propTypes = {
const Integrations = () => {
const theme = useTheme();
+ const { t } = useTranslation();
const integrations = [
{
@@ -90,8 +93,8 @@ const Integrations = () => {
style={{ width: "45px", height: "45px", alignSelf: "center" }}
/>
),
- header: "Slack",
- info: "Connect with Slack and see incidents in a channel",
+ header: t("integrationsSlack"),
+ info: t("integrationsSlackInfo"),
onClick: () => {},
},
{
@@ -101,8 +104,8 @@ const Integrations = () => {
style={{ width: "42px", height: "42px", alignSelf: "center" }}
/>
),
- header: "Discord",
- info: "Connect with Discord and view incidents directly in a channel",
+ header: t("integrationsDiscord"),
+ info: t("integrationsDiscordInfo"),
onClick: () => {},
},
{
@@ -112,8 +115,8 @@ const Integrations = () => {
style={{ width: "42px", height: "42px", alignSelf: "center" }}
/>
),
- header: "Zapier",
- info: "Send all incidents to Zapier, and then see them everywhere",
+ header: t("integrationsZapier"),
+ info: t("integrationsZapierInfo"),
onClick: () => {},
},
// Add more integrations as needed
@@ -130,9 +133,9 @@ const Integrations = () => {
},
}}
>
- Integrations
+ {t("integrations")}
- Connect Checkmate to your favorite service.
+ {t("integrationsPrism")}
{
+ const [search, setSearch] = useState("");
+ const handleSearch = (value) => {
+ setSearch(value);
+ };
+
+ return (
+
+
+
+ );
+};
+
+MonitorsConfig.propTypes = {
+ monitors: PropTypes.array.isRequired,
+ selectedMonitors: PropTypes.array.isRequired,
+ error: PropTypes.string,
+ isEditMode: PropTypes.bool.isRequired,
+ onSelectMonitors: PropTypes.func.isRequired,
+ secondaryLabel: PropTypes.string,
+};
+
+export default MonitorsConfig;
diff --git a/Client/src/Pages/Maintenance/CreateMaintenance/index.css b/client/src/Pages/Maintenance/CreateMaintenance/index.css
similarity index 100%
rename from Client/src/Pages/Maintenance/CreateMaintenance/index.css
rename to client/src/Pages/Maintenance/CreateMaintenance/index.css
diff --git a/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx b/client/src/Pages/Maintenance/CreateMaintenance/index.jsx
similarity index 93%
rename from Client/src/Pages/Maintenance/CreateMaintenance/index.jsx
rename to client/src/Pages/Maintenance/CreateMaintenance/index.jsx
index cacc0e8d5..714d57f13 100644
--- a/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx
+++ b/client/src/Pages/Maintenance/CreateMaintenance/index.jsx
@@ -9,7 +9,6 @@ import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { MobileTimePicker } from "@mui/x-date-pickers/MobileTimePicker";
import { maintenanceWindowValidation } from "../../../Validation/validation";
import { createToast } from "../../../Utils/toastUtils";
-import LoadingButton from "@mui/lab/LoadingButton";
import dayjs from "dayjs";
import Select from "../../../Components/Inputs/Select";
@@ -29,6 +28,7 @@ import {
} from "../../../Utils/timeUtils";
import { useNavigate, useParams } from "react-router-dom";
import { buildErrors, hasValidationErrors } from "../../../Validation/error";
+import { useTranslation } from "react-i18next";
const getDurationAndUnit = (durationInMs) => {
if (durationInMs % MS_PER_DAY === 0) {
@@ -114,7 +114,8 @@ const CreateMaintenance = () => {
const { maintenanceWindowId } = useParams();
const navigate = useNavigate();
const theme = useTheme();
- const { user, authToken } = useSelector((state) => state.auth);
+ const { t } = useTranslation();
+ const { user } = useSelector((state) => state.auth);
const [monitors, setMonitors] = useState([]);
const [search, setSearch] = useState("");
const [isLoading, setIsLoading] = useState(false);
@@ -134,7 +135,6 @@ const CreateMaintenance = () => {
setIsLoading(true);
try {
const response = await networkService.getMonitorsByTeamId({
- authToken: authToken,
teamId: user.teamId,
limit: null,
types: ["http", "ping", "pagespeed"],
@@ -147,7 +147,6 @@ const CreateMaintenance = () => {
}
const res = await networkService.getMaintenanceWindowById({
- authToken: authToken,
maintenanceWindowId: maintenanceWindowId,
});
const maintenanceWindow = res.data.data;
@@ -175,7 +174,7 @@ const CreateMaintenance = () => {
}
};
fetchMonitors();
- }, [authToken, user]);
+ }, [user]);
const handleSearch = (value) => {
setSearch(value);
@@ -240,7 +239,7 @@ const CreateMaintenance = () => {
submit.expiry = end;
}
- const requestConfig = { authToken: authToken, maintenanceWindow: submit };
+ const requestConfig = { maintenanceWindow: submit };
if (maintenanceWindowId !== undefined) {
requestConfig.maintenanceWindowId = maintenanceWindowId;
@@ -296,7 +295,7 @@ const CreateMaintenance = () => {
component="span"
fontSize="inherit"
>
- {`${maintenanceWindowId === undefined ? "Create a" : "Edit"}`}{" "}
+ {`${maintenanceWindowId === undefined ? t("createA") : t("edit")}`}{" "}
{
fontSize="inherit"
fontWeight="inherit"
>
- maintenance{" "}
+ {t("maintenance")}{" "}
- window
+ {t("window")}
{
variant="body2"
fontSize={14}
>
- Your pings won't be sent during this time frame
+ {t("maintenanceWindowDescription")}
@@ -327,14 +326,14 @@ const CreateMaintenance = () => {
component="h2"
variant="h2"
>
- General Settings
+ {t("settingsGeneralSettings")}
{
handleFormChange("name", event.target.value);
@@ -345,7 +344,7 @@ const CreateMaintenance = () => {
{
handleFormChange(
@@ -362,7 +361,7 @@ const CreateMaintenance = () => {
disablePast
disableHighlightToday
value={form.startDate}
- slots={{ openPickerIcon: CalendarIcon }}
+ slots={{ openPickerIcon: () => }}
slotProps={{
switchViewButton: { sx: { display: "none" } },
nextIconButton: { sx: { ml: theme.spacing(2) } },
@@ -412,7 +411,7 @@ const CreateMaintenance = () => {
backgroundColor: theme.palette.accent.light, // Hover background
},
"&.Mui-disabled": {
- color: theme.palette.primary.ContrastTextTertiary, // Disabled day color
+ color: theme.palette.secondary.main, // Disabled day color
},
},
"& .MuiDayCalendar-weekDayLabel": {
@@ -440,15 +439,15 @@ const CreateMaintenance = () => {
component="h2"
variant="h2"
>
- Start time
+ {t("startTime")}
- All dates and times are in GMT+0 time zone.
+ {t("timeZoneInfo")}
{
handleTimeChange("startTime", newTime);
@@ -489,7 +488,7 @@ const CreateMaintenance = () => {
{
handleFormChange("duration", event.target.value);
@@ -519,13 +518,13 @@ const CreateMaintenance = () => {
component="h2"
variant="h2"
>
- Monitors to apply maintenance window to
+ {t("monitorsToApply")}
{
onClick={() => navigate("/maintenance")}
sx={{ mr: theme.spacing(6) }}
>
- Cancel
+ {t("cancel")}
- {
>
{`${
maintenanceWindowId === undefined
- ? "Create maintenance"
- : "Edit maintenance"
+ ? t("createMaintenance")
+ : t("editMaintenance")
}`}
-
+
diff --git a/Client/src/Pages/Maintenance/MaintenanceTable/ActionsMenu/index.jsx b/client/src/Pages/Maintenance/MaintenanceTable/ActionsMenu/index.jsx
similarity index 92%
rename from Client/src/Pages/Maintenance/MaintenanceTable/ActionsMenu/index.jsx
rename to client/src/Pages/Maintenance/MaintenanceTable/ActionsMenu/index.jsx
index 704e8c230..aa1c48433 100644
--- a/Client/src/Pages/Maintenance/MaintenanceTable/ActionsMenu/index.jsx
+++ b/client/src/Pages/Maintenance/MaintenanceTable/ActionsMenu/index.jsx
@@ -8,17 +8,18 @@ import Settings from "../../../../assets/icons/settings-bold.svg?react";
import PropTypes from "prop-types";
import { networkService } from "../../../../main";
import { createToast } from "../../../../Utils/toastUtils";
+import { useTranslation } from "react-i18next";
import Dialog from "../../../../Components/Dialog";
const ActionsMenu = ({ /* isAdmin, */ maintenanceWindow, updateCallback }) => {
maintenanceWindow;
- const { authToken } = useSelector((state) => state.auth);
const [anchorEl, setAnchorEl] = useState(null);
const [isOpen, setIsOpen] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const theme = useTheme();
+ const { t } = useTranslation();
const handleRemove = async (event) => {
event.preventDefault();
@@ -26,7 +27,6 @@ const ActionsMenu = ({ /* isAdmin, */ maintenanceWindow, updateCallback }) => {
try {
setIsLoading(true);
await networkService.deleteMaintenanceWindow({
- authToken,
maintenanceWindowId: maintenanceWindow._id,
});
updateCallback();
@@ -47,7 +47,6 @@ const ActionsMenu = ({ /* isAdmin, */ maintenanceWindow, updateCallback }) => {
active: !maintenanceWindow.active,
};
await networkService.editMaintenanceWindow({
- authToken,
maintenanceWindowId: maintenanceWindow._id,
maintenanceWindow: data,
});
@@ -127,7 +126,7 @@ const ActionsMenu = ({ /* isAdmin, */ maintenanceWindow, updateCallback }) => {
handleEdit();
}}
>
- Edit
+ {t("edit")}
{
@@ -136,7 +135,7 @@ const ActionsMenu = ({ /* isAdmin, */ maintenanceWindow, updateCallback }) => {
e.stopPropagation();
}}
>
- {`${maintenanceWindow.active === true ? "Pause" : "Resume"}`}
+ {`${maintenanceWindow.active === true ? t("pause") : t("resume")}`}
{
openRemove(e);
}}
>
- Remove
+ {t("remove")}
{
e.stopPropagation();
setIsOpen(false);
}}
- confirmationButtonLabel={"Delete"}
+ confirmationButtonLabel={t("delete")}
onConfirm={(e) => {
e.stopPropagation(e);
handleRemove(e);
diff --git a/Client/src/Pages/Maintenance/MaintenanceTable/index.jsx b/client/src/Pages/Maintenance/MaintenanceTable/index.jsx
similarity index 95%
rename from Client/src/Pages/Maintenance/MaintenanceTable/index.jsx
rename to client/src/Pages/Maintenance/MaintenanceTable/index.jsx
index 9bdce5887..aa5c4be2e 100644
--- a/Client/src/Pages/Maintenance/MaintenanceTable/index.jsx
+++ b/client/src/Pages/Maintenance/MaintenanceTable/index.jsx
@@ -10,6 +10,7 @@ import { useDispatch, useSelector } from "react-redux";
import { formatDurationRounded } from "../../../Utils/timeUtils";
import { StatusLabel } from "../../../Components/Label";
import { setRowsPerPage } from "../../../Features/UI/uiSlice";
+import { useTranslation } from "react-i18next";
import dayjs from "dayjs";
/**
* Component for pagination actions (first, previous, next, last).
@@ -34,7 +35,6 @@ const MaintenanceTable = ({
updateCallback,
}) => {
const { rowsPerPage } = useSelector((state) => state.ui.maintenance);
- console.log(rowsPerPage);
const dispatch = useDispatch();
const handleChangePage = (event, newPage) => {
@@ -50,13 +50,15 @@ const MaintenanceTable = ({
);
setPage(0);
};
+
+ const { t } = useTranslation();
const headers = [
{
id: "name",
content: (
handleSort("name")}>
- Maintenance Window Name
+ {t("maintenanceWindowName")}
handleSort("status")}>
{" "}
- Status
+ {t("status")}
{
return getTimeToNextWindow(row.start, row.end, row.repeat);
},
},
{
id: "repeat",
- content: "Repeat",
+ content: t("repeat"),
render: (row) => {
return row.repeat === 0 ? "N/A" : formatDurationRounded(row.repeat);
},
},
{
id: "actions",
- content: "Actions",
+ content: t("actions"),
render: (row) => (
{
+ const theme = useTheme();
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const { rowsPerPage } = useSelector((state) => state.ui.maintenance);
+ const isAdmin = useIsAdmin();
+ const [maintenanceWindows, setMaintenanceWindows] = useState([]);
+ const [maintenanceWindowCount, setMaintenanceWindowCount] = useState(0);
+ const [page, setPage] = useState(0);
+ const [sort, setSort] = useState({});
+ const [updateTrigger, setUpdateTrigger] = useState(false);
+ const [networkError, setNetworkError] = useState(false);
+
+ const handleActionMenuDelete = () => {
+ setUpdateTrigger((prev) => !prev);
+ };
+
+ useEffect(() => {
+ const fetchMaintenanceWindows = async () => {
+ try {
+ const response = await networkService.getMaintenanceWindowsByTeamId({
+ page: page,
+ rowsPerPage: rowsPerPage,
+ });
+ const { maintenanceWindows, maintenanceWindowCount } = response.data.data;
+ setMaintenanceWindows(maintenanceWindows);
+ setMaintenanceWindowCount(maintenanceWindowCount);
+ } catch (error) {
+ setNetworkError(true);
+ }
+ };
+ fetchMaintenanceWindows();
+ }, [page, rowsPerPage, updateTrigger]);
+
+ if (networkError) {
+ return (
+
+
+ {t("networkError")}
+
+ {t("checkConnection")}
+
+ );
+ }
+ if (maintenanceWindows.length === 0) {
+ return (
+
+ );
+ }
+
+ return (
+
+
+
+ {
+ navigate("/maintenance/create");
+ }}
+ sx={{ fontWeight: 500 }}
+ >
+ {t("createMaintenanceWindow")}
+
+
+
+
+ );
+};
+
+export default Maintenance;
diff --git a/Client/src/Pages/NotFound/index.jsx b/client/src/Pages/NotFound/index.jsx
similarity index 94%
rename from Client/src/Pages/NotFound/index.jsx
rename to client/src/Pages/NotFound/index.jsx
index 63b3104ae..f9dfe8ec1 100644
--- a/Client/src/Pages/NotFound/index.jsx
+++ b/client/src/Pages/NotFound/index.jsx
@@ -4,6 +4,7 @@ import NotFoundSvg from "../../../src/assets/Images/sushi_404.svg";
import { Button, Stack, Typography } from "@mui/material";
import { useNavigate } from "react-router";
import { useTheme } from "@emotion/react";
+import { useTranslation } from "react-i18next";
/**
* Support for defaultProps will be removed from function components in a future major release
@@ -33,6 +34,7 @@ const DefaultValue = {
const NotFound = ({ title = DefaultValue.title, desc = DefaultValue.desc }) => {
const navigate = useNavigate();
const theme = useTheme();
+ const { t } = useTranslation();
return (
{
sx={{ mt: theme.spacing(10) }}
onClick={() => navigate("/")}
>
- Go to the main dashboard
+ {t("notFoundButton")}
diff --git a/Client/src/Pages/PageSpeed/Configure/index.css b/client/src/Pages/PageSpeed/Configure/index.css
similarity index 100%
rename from Client/src/Pages/PageSpeed/Configure/index.css
rename to client/src/Pages/PageSpeed/Configure/index.css
diff --git a/Client/src/Pages/PageSpeed/Configure/index.jsx b/client/src/Pages/PageSpeed/Configure/index.jsx
similarity index 86%
rename from Client/src/Pages/PageSpeed/Configure/index.jsx
rename to client/src/Pages/PageSpeed/Configure/index.jsx
index f7829ef35..d9753ef2c 100644
--- a/Client/src/Pages/PageSpeed/Configure/index.jsx
+++ b/client/src/Pages/PageSpeed/Configure/index.jsx
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react";
import { useTheme } from "@emotion/react";
-import { Box, Stack, Tooltip, Typography } from "@mui/material";
+import { Box, Stack, Tooltip, Typography, Button } from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate, useParams } from "react-router";
import {
@@ -13,6 +13,7 @@ import {
import { monitorValidation } from "../../../Validation/validation";
import { createToast } from "../../../Utils/toastUtils";
import { logger } from "../../../Utils/Logger";
+import { useTranslation } from "react-i18next";
import ConfigBox from "../../../Components/ConfigBox";
import TextInput from "../../../Components/Inputs/TextInput";
import Select from "../../../Components/Inputs/Select";
@@ -20,19 +21,19 @@ import Checkbox from "../../../Components/Inputs/Checkbox";
import PauseCircleOutlineIcon from "@mui/icons-material/PauseCircleOutline";
import Breadcrumbs from "../../../Components/Breadcrumbs";
import PulseDot from "../../../Components/Animated/PulseDot";
-import LoadingButton from "@mui/lab/LoadingButton";
import PlayCircleOutlineRoundedIcon from "@mui/icons-material/PlayCircleOutlineRounded";
import SkeletonLayout from "./skeleton";
-import useUtils from "../../Uptime/utils";
+import useUtils from "../../Uptime/Monitors/Hooks/useUtils";
import "./index.css";
import Dialog from "../../../Components/Dialog";
const PageSpeedConfigure = () => {
const theme = useTheme();
+ const { t } = useTranslation();
const navigate = useNavigate();
const dispatch = useDispatch();
const MS_PER_MINUTE = 60000;
- const { user, authToken } = useSelector((state) => state.auth);
+ const { user } = useSelector((state) => state.auth);
const { isLoading } = useSelector((state) => state.pageSpeedMonitors);
const { monitorId } = useParams();
const [monitor, setMonitor] = useState({});
@@ -60,7 +61,7 @@ const PageSpeedConfigure = () => {
useEffect(() => {
const fetchMonitor = async () => {
try {
- const action = await dispatch(getPagespeedMonitorById({ authToken, monitorId }));
+ const action = await dispatch(getPagespeedMonitorById({ monitorId }));
if (getPagespeedMonitorById.fulfilled.match(action)) {
const monitor = action.payload.data;
@@ -74,7 +75,7 @@ const PageSpeedConfigure = () => {
}
};
fetchMonitor();
- }, [dispatch, authToken, monitorId, navigate]);
+ }, [dispatch, monitorId, navigate]);
const handleChange = (event, name) => {
let { value, id } = event.target;
@@ -131,7 +132,7 @@ const PageSpeedConfigure = () => {
const handlePause = async () => {
try {
- const action = await dispatch(pausePageSpeed({ authToken, monitorId }));
+ const action = await dispatch(pausePageSpeed({ monitorId }));
if (pausePageSpeed.fulfilled.match(action)) {
const monitor = action.payload.data;
setMonitor(monitor);
@@ -148,10 +149,10 @@ const PageSpeedConfigure = () => {
const handleSave = async (event) => {
event.preventDefault();
- const action = await dispatch(updatePageSpeed({ authToken, monitor: monitor }));
+ const action = await dispatch(updatePageSpeed({ monitor: monitor }));
if (action.meta.requestStatus === "fulfilled") {
createToast({ body: "Monitor updated successfully!" });
- dispatch(getPageSpeedByTeamId(authToken));
+ dispatch(getPageSpeedByTeamId());
} else {
createToast({ body: "Failed to update monitor." });
}
@@ -161,7 +162,7 @@ const PageSpeedConfigure = () => {
const handleRemove = async (event) => {
event.preventDefault();
setButtonLoading(true);
- const action = await dispatch(deletePageSpeed({ authToken, monitor }));
+ const action = await dispatch(deletePageSpeed({ monitor }));
if (action.meta.requestStatus === "fulfilled") {
navigate("/pagespeed");
} else {
@@ -257,7 +258,7 @@ const PageSpeedConfigure = () => {
},
}}
>
- Editing...
+ {t("editing")}
@@ -265,7 +266,7 @@ const PageSpeedConfigure = () => {
alignSelf="flex-end"
ml="auto"
>
- {
{monitor?.isActive ? (
<>
- Pause
+ {t("pause")}
>
) : (
<>
- Resume
+ {t("resume")}
>
)}
-
-
+ {
ml: theme.spacing(6),
}}
>
- Remove
-
+ {t("remove")}
+
- General settings
+ {t("settingsGeneralSettings")}
- Here you can select the URL of the host, together with the type of
- monitor.
+ {t("pageSpeedConfigureSettingsDescription")}
{
{
{
- Incident notifications
+ {t("distributedUptimeCreateIncidentNotification")}
- When there is an incident, notify users.
+ {t("distributedUptimeCreateIncidentDescription")}
- When there is a new incident,
+ {t("whenNewIncident")}
logger.warn("disabled")}
@@ -377,7 +377,7 @@ const PageSpeedConfigure = () => {
/>
logger.warn("disabled")}
@@ -395,7 +395,7 @@ const PageSpeedConfigure = () => {
onChange={() => logger.warn("disabled")}
/>
- You can separate multiple emails with a comma
+ {t("seperateEmails")}
) : (
@@ -405,12 +405,12 @@ const PageSpeedConfigure = () => {
- Advanced settings
+ {t("distributedUptimeCreateAdvancedSettings")}
handleChange(event, "interval")}
@@ -422,7 +422,7 @@ const PageSpeedConfigure = () => {
justifyContent="flex-end"
mt="auto"
>
- {
onClick={handleSave}
sx={{ px: theme.spacing(12) }}
>
- Save
-
+ {t("settingsSave")}
+
>
@@ -439,10 +439,10 @@ const PageSpeedConfigure = () => {
setIsOpen(false)}
- confirmationButtonLabel={"Delete"}
+ confirmationButtonLabel={t("delete")}
onConfirm={handleRemove}
isLoading={buttonLoading}
/>
diff --git a/Client/src/Pages/PageSpeed/Configure/skeleton.jsx b/client/src/Pages/PageSpeed/Configure/skeleton.jsx
similarity index 100%
rename from Client/src/Pages/PageSpeed/Configure/skeleton.jsx
rename to client/src/Pages/PageSpeed/Configure/skeleton.jsx
diff --git a/Client/src/Pages/PageSpeed/CreatePageSpeed/index.css b/client/src/Pages/PageSpeed/Create/index.css
similarity index 100%
rename from Client/src/Pages/PageSpeed/CreatePageSpeed/index.css
rename to client/src/Pages/PageSpeed/Create/index.css
diff --git a/Client/src/Pages/PageSpeed/CreatePageSpeed/index.jsx b/client/src/Pages/PageSpeed/Create/index.jsx
similarity index 89%
rename from Client/src/Pages/PageSpeed/CreatePageSpeed/index.jsx
rename to client/src/Pages/PageSpeed/Create/index.jsx
index 925d077df..75e60eb79 100644
--- a/Client/src/Pages/PageSpeed/CreatePageSpeed/index.jsx
+++ b/client/src/Pages/PageSpeed/Create/index.jsx
@@ -10,11 +10,11 @@ import {
checkEndpointResolution,
} from "../../../Features/PageSpeedMonitor/pageSpeedMonitorSlice";
import { parseDomainName } from "../../../Utils/monitorUtils";
+import { useTranslation } from "react-i18next";
// MUI
import { useTheme } from "@emotion/react";
import { Box, Stack, Typography, Button, ButtonGroup } from "@mui/material";
-import LoadingButton from "@mui/lab/LoadingButton";
//Components
import Breadcrumbs from "../../../Components/Breadcrumbs";
@@ -55,7 +55,7 @@ const CreatePageSpeed = () => {
const [https, setHttps] = useState(true);
const [errors, setErrors] = useState({});
- const { user, authToken } = useSelector((state) => state.auth);
+ const { user } = useSelector((state) => state.auth);
const { isLoading } = useSelector((state) => state.pageSpeedMonitors);
// Setup
@@ -88,7 +88,7 @@ const CreatePageSpeed = () => {
}
const checkEndpointAction = await dispatch(
- checkEndpointResolution({ authToken, monitorURL: form.url })
+ checkEndpointResolution({ monitorURL: form.url })
);
if (checkEndpointAction.meta.requestStatus === "rejected") {
@@ -107,7 +107,7 @@ const CreatePageSpeed = () => {
notifications: monitor.notifications,
};
- const action = await dispatch(createPageSpeed({ authToken, monitor: form }));
+ const action = await dispatch(createPageSpeed({ monitor: form }));
if (action.meta.requestStatus === "fulfilled") {
createToast({ body: "Monitor created successfully!" });
navigate("/pagespeed");
@@ -174,6 +174,8 @@ const CreatePageSpeed = () => {
}
};
+ const { t } = useTranslation();
+
return (
{
component="span"
fontSize="inherit"
>
- Create your{" "}
+ {t("createYour")}{" "}
{
fontWeight="inherit"
color={theme.palette.primary.contrastTextSecondary}
>
- PageSpeed monitor
+ {t("pageSpeedMonitor")}
- General settings
+ {t("settingsGeneralSettings")}
- Here you can select the URL of the host, together with the type of monitor.
+ {t("distributedUptimeCreateSelectURL")}
@@ -249,9 +251,9 @@ const CreatePageSpeed = () => {
- Checks to perform
+ {t("distributedUptimeCreateChecks")}
- You can always add or remove checks after adding your site.
+ {t("distributedUptimeCreateChecksDescription")}
@@ -270,14 +272,14 @@ const CreatePageSpeed = () => {
filled={https.toString()}
onClick={() => setHttps(true)}
>
- HTTPS
+ {t("https")}
setHttps(false)}
>
- HTTP
+ {t("http")}
@@ -298,13 +300,13 @@ const CreatePageSpeed = () => {
- Incident notifications
+ {t("distributedUptimeCreateIncidentNotification")}
- When there is an incident, notify users.
+ {t("distributedUptimeCreateIncidentDescription")}
- When there is a new incident,
+ {t("whenNewIncident")}
{
- Advanced settings
+ {t("distributedUptimeCreateAdvancedSettings")}
{
direction="row"
justifyContent="flex-end"
>
- value === undefined)}
loading={isLoading}
>
- Create monitor
-
+ {t("createMonitor")}
+
diff --git a/Client/src/Pages/PageSpeed/Details/Charts/AreaChart.jsx b/client/src/Pages/PageSpeed/Details/Components/Charts/AreaChart.jsx
similarity index 95%
rename from Client/src/Pages/PageSpeed/Details/Charts/AreaChart.jsx
rename to client/src/Pages/PageSpeed/Details/Components/Charts/AreaChart.jsx
index a854eb094..40fec0ab6 100644
--- a/Client/src/Pages/PageSpeed/Details/Charts/AreaChart.jsx
+++ b/client/src/Pages/PageSpeed/Details/Components/Charts/AreaChart.jsx
@@ -11,7 +11,7 @@ import {
import { useTheme } from "@emotion/react";
import { useMemo, useState } from "react";
import { Box, Stack, Typography } from "@mui/material";
-import { formatDateWithTz } from "../../../../Utils/timeUtils";
+import { formatDateWithTz } from "../../../../../Utils/timeUtils";
import { useSelector } from "react-redux";
const config = {
@@ -211,10 +211,13 @@ CustomTick.propTypes = {
* @returns {JSX.Element} The area chart component.
*/
-const PagespeedDetailsAreaChart = ({ data, interval, metrics }) => {
+const PageSpeedAreaChart = ({ data, monitor, metrics }) => {
const theme = useTheme();
const [isHovered, setIsHovered] = useState(false);
- const memoizedData = useMemo(() => processDataWithGaps(data, interval), [data[0]]);
+ const memoizedData = useMemo(
+ () => processDataWithGaps(data, monitor.interval),
+ [data[0]]
+ );
const filteredConfig = Object.keys(config).reduce((result, key) => {
if (metrics[key]) {
@@ -310,7 +313,7 @@ const PagespeedDetailsAreaChart = ({ data, interval, metrics }) => {
);
};
-PagespeedDetailsAreaChart.propTypes = {
+PageSpeedAreaChart.propTypes = {
data: PropTypes.arrayOf(
PropTypes.shape({
createdAt: PropTypes.string.isRequired,
@@ -320,8 +323,8 @@ PagespeedDetailsAreaChart.propTypes = {
seo: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
})
).isRequired,
- interval: PropTypes.number.isRequired,
+ monitor: PropTypes.object.isRequired,
metrics: PropTypes.object,
};
-export default PagespeedDetailsAreaChart;
+export default PageSpeedAreaChart;
diff --git a/client/src/Pages/PageSpeed/Details/Components/Charts/AreaChartLegend.jsx b/client/src/Pages/PageSpeed/Details/Components/Charts/AreaChartLegend.jsx
new file mode 100644
index 000000000..72811fa2a
--- /dev/null
+++ b/client/src/Pages/PageSpeed/Details/Components/Charts/AreaChartLegend.jsx
@@ -0,0 +1,57 @@
+import { Box, Typography, Divider } from "@mui/material";
+import Checkbox from "../../../../../Components/Inputs/Checkbox";
+import MetricsIcon from "../../../../../assets/icons/ruler-icon.svg?react";
+import LegendBox from "../../../../../Components/Charts/LegendBox";
+import { useTranslation } from "react-i18next";
+import { useTheme } from "@emotion/react";
+
+const AreaChartLegend = ({ metrics, handleMetrics }) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ return (
+ }
+ header="Metrics"
+ >
+
+
+ {t("shown")}
+
+
+
+ handleMetrics("accessibility")}
+ />
+
+ handleMetrics("bestPractices")}
+ />
+
+ handleMetrics("performance")}
+ />
+
+ handleMetrics("seo")}
+ />
+
+
+ );
+};
+
+export default AreaChartLegend;
diff --git a/Client/src/Pages/PageSpeed/Details/Charts/PieChart.jsx b/client/src/Pages/PageSpeed/Details/Components/Charts/PieChart.jsx
similarity index 99%
rename from Client/src/Pages/PageSpeed/Details/Charts/PieChart.jsx
rename to client/src/Pages/PageSpeed/Details/Components/Charts/PieChart.jsx
index 193841e7e..c9204c38a 100644
--- a/Client/src/Pages/PageSpeed/Details/Charts/PieChart.jsx
+++ b/client/src/Pages/PageSpeed/Details/Components/Charts/PieChart.jsx
@@ -115,6 +115,8 @@ const weights = {
const PieChart = ({ audits }) => {
const theme = useTheme();
+ const [highlightedItem, setHighLightedItem] = useState(null);
+ const [expand, setExpand] = useState(false);
/**
* Retrieves color properties based on the performance value.
@@ -162,6 +164,8 @@ const PieChart = ({ audits }) => {
*/
let performance = 0;
const getPieData = (audits) => {
+ if (typeof audits === "undefined") return undefined;
+
let data = [];
let startAngle = 0;
const padding = 3; // padding between arcs
@@ -216,8 +220,6 @@ const PieChart = ({ audits }) => {
const pieData = getPieData(audits);
const colorMap = getColors(performance);
- const [highlightedItem, setHighLightedItem] = useState(null);
- const [expand, setExpand] = useState(false);
return (
setExpand(false)}>
{expand ? (
diff --git a/client/src/Pages/PageSpeed/Details/Components/Charts/PieChartLegend.jsx b/client/src/Pages/PageSpeed/Details/Components/Charts/PieChartLegend.jsx
new file mode 100644
index 000000000..010716b88
--- /dev/null
+++ b/client/src/Pages/PageSpeed/Details/Components/Charts/PieChartLegend.jsx
@@ -0,0 +1,96 @@
+import { Stack, Box, Typography } from "@mui/material";
+import { useTheme } from "@emotion/react";
+import LegendBox from "../../../../../Components/Charts/LegendBox";
+import SpeedometerIcon from "../../../../../assets/icons/speedometer-icon.svg?react";
+import PropTypes from "prop-types";
+
+const PieChartLegend = ({ audits }) => {
+ const theme = useTheme();
+
+ return (
+ }
+ header="Performance metrics"
+ sx={{ flex: 1 }}
+ >
+ {typeof audits !== "undefined" &&
+ Object.keys(audits).map((key) => {
+ if (key === "_id") return;
+
+ let audit = audits[key];
+ let score = audit.score * 100;
+ let bg =
+ score >= 90
+ ? theme.palette.success.main
+ : score >= 50
+ ? theme.palette.warning.main
+ : score >= 0
+ ? theme.palette.error.main
+ : theme.palette.tertiary.main;
+
+ // Find the position where the number ends and the unit begins
+ const match = audit.displayValue.match(/(\d+\.?\d*)\s*([a-zA-Z]+)/);
+ let value;
+ let unit;
+ if (match) {
+ value = match[1];
+ match[2] === "s" ? (unit = "seconds") : (unit = match[2]);
+ } else {
+ value = audit.displayValue;
+ }
+
+ return (
+
+
+
+ {audit.title}
+
+
+ {value}
+
+ {unit}
+
+
+
+
+
+ );
+ })}
+
+ );
+};
+
+PieChartLegend.propTypes = {
+ audits: PropTypes.object,
+};
+
+export default PieChartLegend;
diff --git a/client/src/Pages/PageSpeed/Details/Components/PageSpeedAreaChart/index.jsx b/client/src/Pages/PageSpeed/Details/Components/PageSpeedAreaChart/index.jsx
new file mode 100644
index 000000000..582648e23
--- /dev/null
+++ b/client/src/Pages/PageSpeed/Details/Components/PageSpeedAreaChart/index.jsx
@@ -0,0 +1,55 @@
+import ChartBox from "../../../../../Components/Charts/ChartBox";
+import AreaChart from "../Charts/AreaChart";
+import AreaChartLegend from "../Charts/AreaChartLegend";
+import SkeletonLayout from "./skeleton";
+import ScoreIcon from "../../../../../assets/icons/monitor-graph-line.svg?react";
+import { Stack } from "@mui/material";
+import PropTypes from "prop-types";
+
+import { useTheme } from "@emotion/react";
+
+const PageSpeedAreaChart = ({ shouldRender, monitor, metrics, handleMetrics }) => {
+ const theme = useTheme();
+
+ if (!shouldRender) {
+ return ;
+ }
+
+ const data = monitor?.checks ? [...monitor.checks].reverse() : [];
+
+ return (
+
+ }
+ header="Score history"
+ height="100%"
+ borderRadiusRight={16}
+ Legend={
+
+ }
+ >
+
+
+
+ );
+};
+
+PageSpeedAreaChart.propTypes = {
+ shouldRender: PropTypes.bool,
+ monitor: PropTypes.object,
+ metrics: PropTypes.object,
+ handleMetrics: PropTypes.func,
+};
+
+export default PageSpeedAreaChart;
diff --git a/client/src/Pages/PageSpeed/Details/Components/PageSpeedAreaChart/skeleton.jsx b/client/src/Pages/PageSpeed/Details/Components/PageSpeedAreaChart/skeleton.jsx
new file mode 100644
index 000000000..b793908d4
--- /dev/null
+++ b/client/src/Pages/PageSpeed/Details/Components/PageSpeedAreaChart/skeleton.jsx
@@ -0,0 +1,17 @@
+import { Box, Skeleton } from "@mui/material";
+
+const SkeletonLayout = () => {
+ return (
+
+
+
+ );
+};
+
+export default SkeletonLayout;
diff --git a/client/src/Pages/PageSpeed/Details/Components/PageSpeedStatusBoxes/index.jsx b/client/src/Pages/PageSpeed/Details/Components/PageSpeedStatusBoxes/index.jsx
new file mode 100644
index 000000000..d3c597c3d
--- /dev/null
+++ b/client/src/Pages/PageSpeed/Details/Components/PageSpeedStatusBoxes/index.jsx
@@ -0,0 +1,44 @@
+import StatusBoxes from "../../../../../Components/StatusBoxes";
+import StatBox from "../../../../../Components/StatBox";
+import { Typography } from "@mui/material";
+import { getHumanReadableDuration } from "../../../../../Utils/timeUtils";
+import { useTranslation } from "react-i18next";
+
+const PageSpeedStatusBoxes = ({ shouldRender, monitor }) => {
+ const { time: uptimeDuration, units: uptimeUnits } = getHumanReadableDuration(
+ monitor?.uptimeDuration
+ );
+
+ const { time: lastCheckTime, units: lastCheckUnits } = getHumanReadableDuration(
+ monitor?.lastChecked
+ );
+
+ const { t } = useTranslation();
+
+ return (
+
+
+ {uptimeDuration}
+ {uptimeUnits}
+ {t("ago")}
+ >
+ }
+ />
+
+ {lastCheckTime}
+ {lastCheckUnits}
+ {t("ago")}
+ >
+ }
+ />
+
+ );
+};
+
+export default PageSpeedStatusBoxes;
diff --git a/client/src/Pages/PageSpeed/Details/Components/PerformanceReport/index.jsx b/client/src/Pages/PageSpeed/Details/Components/PerformanceReport/index.jsx
new file mode 100644
index 000000000..c83f77294
--- /dev/null
+++ b/client/src/Pages/PageSpeed/Details/Components/PerformanceReport/index.jsx
@@ -0,0 +1,53 @@
+import ChartBox from "../../../../../Components/Charts/ChartBox";
+import PerformanceIcon from "../../../../../assets/icons/performance-report.svg?react";
+import PieChart from "../Charts/PieChart";
+import { Typography } from "@mui/material";
+import { useTheme } from "@emotion/react";
+import PieChartLegend from "../Charts/PieChartLegend";
+import SkeletonLayout from "./skeleton";
+import { useTranslation } from "react-i18next";
+
+const PerformanceReport = ({ shouldRender, audits }) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+
+ if (!shouldRender) {
+ return ;
+ }
+
+ return (
+ }
+ header="Performance report"
+ Legend={ }
+ borderRadiusRight={16}
+ >
+
+
+ {t("pageSpeedDetailsPerformanceReport")}{" "}
+
+ {t("pageSpeedDetailsPerformanceReportCalculator")}
+
+
+
+ );
+};
+
+export default PerformanceReport;
diff --git a/client/src/Pages/PageSpeed/Details/Components/PerformanceReport/skeleton.jsx b/client/src/Pages/PageSpeed/Details/Components/PerformanceReport/skeleton.jsx
new file mode 100644
index 000000000..b793908d4
--- /dev/null
+++ b/client/src/Pages/PageSpeed/Details/Components/PerformanceReport/skeleton.jsx
@@ -0,0 +1,17 @@
+import { Box, Skeleton } from "@mui/material";
+
+const SkeletonLayout = () => {
+ return (
+
+
+
+ );
+};
+
+export default SkeletonLayout;
diff --git a/client/src/Pages/PageSpeed/Details/Hooks/useMonitorFetch.jsx b/client/src/Pages/PageSpeed/Details/Hooks/useMonitorFetch.jsx
new file mode 100644
index 000000000..18ffd8782
--- /dev/null
+++ b/client/src/Pages/PageSpeed/Details/Hooks/useMonitorFetch.jsx
@@ -0,0 +1,39 @@
+import { useEffect, useState } from "react";
+import { networkService } from "../../../../main";
+import { createToast } from "../../../../Utils/toastUtils";
+import { useNavigate } from "react-router-dom";
+const useMonitorFetch = ({ monitorId }) => {
+ const navigate = useNavigate();
+
+ const [monitor, setMonitor] = useState(undefined);
+ const [audits, setAudits] = useState(undefined);
+ const [isLoading, setIsLoading] = useState(true);
+ const [networkError, setNetworkError] = useState(false);
+ useEffect(() => {
+ const fetchMonitor = async () => {
+ try {
+ const res = await networkService.getStatsByMonitorId({
+ monitorId: monitorId,
+ sortOrder: "desc",
+ limit: 50,
+ dateRange: "day",
+ numToDisplay: null,
+ normalize: null,
+ });
+ setMonitor(res?.data?.data ?? undefined);
+ setAudits(res?.data?.data?.checks?.[0]?.audits ?? undefined);
+ } catch (error) {
+ setNetworkError(true);
+ createToast({ body: error.message });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ fetchMonitor();
+ }, [monitorId, navigate]);
+
+ return { monitor, audits, isLoading };
+};
+
+export { useMonitorFetch };
diff --git a/client/src/Pages/PageSpeed/Details/index.jsx b/client/src/Pages/PageSpeed/Details/index.jsx
new file mode 100644
index 000000000..d429858d2
--- /dev/null
+++ b/client/src/Pages/PageSpeed/Details/index.jsx
@@ -0,0 +1,112 @@
+// Components
+import { Stack, Typography } from "@mui/material";
+import Breadcrumbs from "../../../Components/Breadcrumbs";
+import MonitorTimeFrameHeader from "../../../Components/MonitorTimeFrameHeader";
+import MonitorStatusHeader from "../../../Components/MonitorStatusHeader";
+import PageSpeedStatusBoxes from "./Components/PageSpeedStatusBoxes";
+import PageSpeedAreaChart from "./Components/PageSpeedAreaChart";
+import PerformanceReport from "./Components/PerformanceReport";
+import GenericFallback from "../../../Components/GenericFallback";
+// Utils
+import { useTheme } from "@emotion/react";
+import { useIsAdmin } from "../../../Hooks/useIsAdmin";
+import { useParams } from "react-router-dom";
+import { useSelector } from "react-redux";
+import { useMonitorFetch } from "./Hooks/useMonitorFetch";
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+// Constants
+const BREADCRUMBS = [
+ { name: "pagespeed", path: "/pagespeed" },
+ { name: "details", path: `` },
+ // { name: "details", path: `/pagespeed/${monitorId}` }, // Not needed?
+];
+
+const PageSpeedDetails = () => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ const isAdmin = useIsAdmin();
+ const { monitorId } = useParams();
+
+ const { monitor, audits, isLoading, networkError } = useMonitorFetch({
+ monitorId,
+ });
+
+ const [metrics, setMetrics] = useState({
+ accessibility: true,
+ bestPractices: true,
+ performance: true,
+ seo: true,
+ });
+
+ // Handlers
+ const handleMetrics = (id) => {
+ setMetrics((prev) => ({ ...prev, [id]: !prev[id] }));
+ };
+
+ if (networkError === true) {
+ return (
+
+
+ {t("networkError")}
+
+ {t("checkConnection")}
+
+ );
+ }
+
+ // Empty view, displayed when loading is complete and there are no checks
+ if (!isLoading && monitor?.checks?.length === 0) {
+ return (
+
+
+
+
+ {t("distributedUptimeDetailsNoMonitorHistory")}
+
+
+ );
+ }
+
+ return (
+
+
+
+
+
+
+
+
+
+ );
+};
+
+export default PageSpeedDetails;
diff --git a/Client/src/Pages/PageSpeed/card.jsx b/client/src/Pages/PageSpeed/Monitors/Components/Card/index.jsx
similarity index 93%
rename from Client/src/Pages/PageSpeed/card.jsx
rename to client/src/Pages/PageSpeed/Monitors/Components/Card/index.jsx
index f5b0d7110..36bf91eee 100644
--- a/Client/src/Pages/PageSpeed/card.jsx
+++ b/client/src/Pages/PageSpeed/Monitors/Components/Card/index.jsx
@@ -1,15 +1,17 @@
import PropTypes from "prop-types";
-import PageSpeedIcon from "../../assets/icons/page-speed.svg?react";
-import { StatusLabel } from "../../Components/Label";
+// import PageSpeedIcon from "../../../../assets/icons/page-speed.svg?react";
+import PageSpeedIcon from "../../../../../assets/icons/page-speed.svg?react";
+import { StatusLabel } from "../../../../../Components/Label";
import { Box, Grid, Stack, Typography } from "@mui/material";
import { useNavigate } from "react-router";
import { useTheme } from "@emotion/react";
import { Area, AreaChart, CartesianGrid, ResponsiveContainer, Tooltip } from "recharts";
import { useSelector } from "react-redux";
-import { formatDateWithTz, formatDurationSplit } from "../../Utils/timeUtils";
-import useUtils from "../Uptime/utils";
+import { formatDateWithTz, formatDurationSplit } from "../../../../../Utils/timeUtils";
+import useUtils from "../../../../Uptime/Monitors/Hooks/useUtils";
import { useState } from "react";
-import IconBox from "../../Components/IconBox";
+import { useTranslation } from "react-i18next";
+import IconBox from "../../../../../Components/IconBox";
/**
* CustomToolTip displays a tooltip with formatted date and score information.
* @param {Object} props
@@ -206,6 +208,7 @@ PagespeedAreaChart.propTypes = {
const Card = ({ monitor }) => {
const { determineState, pagespeedStatusMsg } = useUtils();
const theme = useTheme();
+ const { t } = useTranslation();
const navigate = useNavigate();
const monitorState = determineState(monitor);
@@ -296,7 +299,7 @@ const Card = ({ monitor }) => {
fontSize={11}
color={theme.palette.primary.contrastTextSecondary}
>
- Checking every{" "}
+ {t("checkingEvery")}{" "}
{(() => {
const { time, format } = formatDurationSplit(monitor?.interval);
return (
diff --git a/client/src/Pages/PageSpeed/Monitors/Components/MonitorGrid/index.jsx b/client/src/Pages/PageSpeed/Monitors/Components/MonitorGrid/index.jsx
new file mode 100644
index 000000000..6266ebdc9
--- /dev/null
+++ b/client/src/Pages/PageSpeed/Monitors/Components/MonitorGrid/index.jsx
@@ -0,0 +1,20 @@
+import { Grid, Grid2 } from "@mui/material";
+import Card from "../Card";
+
+const MonitorGrid = ({ shouldRender, monitors }) => {
+ return (
+
+ {monitors?.map((monitor) => (
+
+ ))}
+
+ );
+};
+
+export default MonitorGrid;
diff --git a/client/src/Pages/PageSpeed/Monitors/Hooks/useMonitorsFetch.jsx b/client/src/Pages/PageSpeed/Monitors/Hooks/useMonitorsFetch.jsx
new file mode 100644
index 000000000..d2f0f4842
--- /dev/null
+++ b/client/src/Pages/PageSpeed/Monitors/Hooks/useMonitorsFetch.jsx
@@ -0,0 +1,44 @@
+import { useEffect, useState } from "react";
+import { networkService } from "../../../../main";
+import { createToast } from "../../../../Utils/toastUtils";
+
+const useMonitorsFetch = ({ teamId }) => {
+ const [isLoading, setIsLoading] = useState(true);
+ const [monitors, setMonitors] = useState([]);
+ const [summary, setSummary] = useState({});
+ const [networkError, setNetworkError] = useState(false);
+
+ useEffect(() => {
+ const fetchMonitors = async () => {
+ try {
+ setIsLoading(true);
+ const res = await networkService.getMonitorsByTeamId({
+ teamId: teamId,
+ limit: 10,
+ types: ["pagespeed"],
+ page: null,
+ rowsPerPage: null,
+ filter: null,
+ field: null,
+ order: null,
+ });
+ if (res?.data?.data?.filteredMonitors) {
+ setMonitors(res.data.data.filteredMonitors);
+ setSummary(res.data.data.summary);
+ }
+ } catch (error) {
+ setNetworkError(true);
+ createToast({
+ body: error.message,
+ });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ fetchMonitors();
+ }, [teamId]);
+ return { isLoading, monitors, summary, networkError };
+};
+
+export default useMonitorsFetch;
diff --git a/client/src/Pages/PageSpeed/Monitors/index.jsx b/client/src/Pages/PageSpeed/Monitors/index.jsx
new file mode 100644
index 000000000..bd40aedff
--- /dev/null
+++ b/client/src/Pages/PageSpeed/Monitors/index.jsx
@@ -0,0 +1,83 @@
+// Components
+import Breadcrumbs from "../../../Components/Breadcrumbs";
+import { Stack, Typography } from "@mui/material";
+import CreateMonitorHeader from "../../../Components/MonitorCreateHeader";
+import MonitorCountHeader from "../../../Components/MonitorCountHeader";
+import MonitorGrid from "./Components/MonitorGrid";
+import Fallback from "../../../Components/Fallback";
+
+// Utils
+import { useTheme } from "@emotion/react";
+import { useSelector } from "react-redux";
+import { useIsAdmin } from "../../../Hooks/useIsAdmin";
+import useMonitorsFetch from "./Hooks/useMonitorsFetch";
+import GenericFallback from "../../../Components/GenericFallback";
+import { useTranslation } from "react-i18next";
+// Constants
+const BREADCRUMBS = [{ name: `pagespeed`, path: "/pagespeed" }];
+
+const PageSpeed = () => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ const isAdmin = useIsAdmin();
+ const { user } = useSelector((state) => state.auth);
+ const { pagespeedApiKey } = useSelector((state) => state.settings);
+
+ const { isLoading, monitors, summary, networkError } = useMonitorsFetch({
+ teamId: user.teamId,
+ });
+
+ if (networkError === true) {
+ return (
+
+
+ {t("networkError")}
+
+ {t("checkConnection")}
+
+ );
+ }
+
+ if (!isLoading && monitors?.length === 0) {
+ return (
+
+ );
+ }
+
+ return (
+
+
+
+
+
+
+ );
+};
+
+export default PageSpeed;
diff --git a/client/src/Pages/ServerUnreachable.jsx b/client/src/Pages/ServerUnreachable.jsx
new file mode 100644
index 000000000..aaa61cbc4
--- /dev/null
+++ b/client/src/Pages/ServerUnreachable.jsx
@@ -0,0 +1,161 @@
+import React, { useState } from "react";
+import { Box, Typography, Button, Stack } from "@mui/material";
+import { useTheme } from "@emotion/react";
+import { useNavigate } from "react-router";
+import { networkService } from "../Utils/NetworkService";
+import Alert from "../Components/Alert";
+import { createToast } from "../Utils/toastUtils";
+import { useTranslation } from "react-i18next";
+import Background from "../assets/Images/background-grid.svg?react";
+import Logo from "../assets/icons/checkmate-icon.svg?react";
+import ThemeSwitch from "../Components/ThemeSwitch";
+import LanguageSelector from "../Components/LanguageSelector";
+
+const ServerUnreachable = () => {
+ const theme = useTheme();
+ const navigate = useNavigate();
+ const { t } = useTranslation();
+
+ // State for tracking connection check status
+ const [isCheckingConnection, setIsCheckingConnection] = useState(false);
+
+ const handleRetry = React.useCallback(async () => {
+ setIsCheckingConnection(true);
+ try {
+ // Try to connect to the backend with a simple API call
+ // We'll use any lightweight endpoint that doesn't require authentication
+ await networkService.axiosInstance.get('/health', { timeout: 5000 });
+
+ // If successful, show toast and navigate to login page
+ createToast({
+ body: t("backendReconnected", "Connection to server restored"),
+ });
+ navigate("/login");
+ } catch (error) {
+ // If still unreachable, stay on this page and show toast
+ createToast({
+ body: t("backendStillUnreachable", "Server is still unreachable"),
+ });
+ } finally {
+ setIsCheckingConnection(false);
+ }
+ }, [navigate, t]);
+
+ return (
+
+
+
+
+
+ {/* Header with logo */}
+
+
+
+ Checkmate
+
+
+
+
+
+
+ .MuiStack-root": {
+ border: 1,
+ borderRadius: theme.spacing(5),
+ borderColor: theme.palette.primary.lowContrast,
+ backgroundColor: theme.palette.primary.main,
+ padding: {
+ xs: theme.spacing(12),
+ sm: theme.spacing(20),
+ },
+ },
+ }}
+ >
+
+
+
+
+
+
+ {t("backendUnreachableMessage", "The Checkmate server is not responding. Please check your deployment configuration or try again later.")}
+
+
+
+
+ {isCheckingConnection ?
+ t("retryingConnection", "Retrying Connection...") :
+ t("retryConnection", "Retry Connection")}
+
+
+
+
+
+ );
+};
+
+export default ServerUnreachable;
diff --git a/client/src/Pages/Settings/SettingsAbout.jsx b/client/src/Pages/Settings/SettingsAbout.jsx
new file mode 100644
index 000000000..5551d8e7c
--- /dev/null
+++ b/client/src/Pages/Settings/SettingsAbout.jsx
@@ -0,0 +1,32 @@
+import Box from "@mui/material/Box";
+import Typography from "@mui/material/Typography";
+import ConfigBox from "../../Components/ConfigBox";
+// Utils
+import { useTheme } from "@emotion/react";
+import { useTranslation } from "react-i18next";
+import Link from "../../Components/Link";
+
+const SettingsAbout = () => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ return (
+
+
+ {t("settingsAbout")}
+
+
+ Checkmate {2.1}
+
+ {t("settingsDevelopedBy")}
+
+
+
+
+ );
+};
+
+export default SettingsAbout;
diff --git a/client/src/Pages/Settings/SettingsDemoMonitors.jsx b/client/src/Pages/Settings/SettingsDemoMonitors.jsx
new file mode 100644
index 000000000..3a288f558
--- /dev/null
+++ b/client/src/Pages/Settings/SettingsDemoMonitors.jsx
@@ -0,0 +1,96 @@
+import Box from "@mui/material/Box";
+import Typography from "@mui/material/Typography";
+import Button from "@mui/material/Button";
+import ConfigBox from "../../Components/ConfigBox";
+// Utils
+import { useTheme } from "@emotion/react";
+import { PropTypes } from "prop-types";
+import { useTranslation } from "react-i18next";
+import Dialog from "../../Components/Dialog";
+import { useState } from "react";
+
+const SettingsDemoMonitors = ({ isAdmin, HEADER_SX, handleChange, isLoading }) => {
+ const { t } = useTranslation();
+ const theme = useTheme();
+ // Local state
+ const [isOpen, setIsOpen] = useState(false);
+
+ if (!isAdmin) {
+ return null;
+ }
+
+ return (
+ <>
+
+
+ {t("settingsDemoMonitors")}
+ {t("settingsDemoMonitorsDescription")}
+
+
+ {t("settingsAddDemoMonitors")}
+ {
+ const syntheticEvent = {
+ target: {
+ name: "demo",
+ },
+ };
+ handleChange(syntheticEvent);
+ }}
+ sx={{ mt: theme.spacing(4) }}
+ >
+ {t("settingsAddDemoMonitorsButton")}
+
+
+
+
+
+ {t("settingsSystemReset")}
+
+ {t("settingsSystemResetDescription")}
+
+
+
+ {t("settingsRemoveAllMonitors")}
+ setIsOpen(true)}
+ sx={{ mt: theme.spacing(4) }}
+ >
+ {t("settingsRemoveAllMonitorsButton")}
+
+
+ setIsOpen(false)}
+ confirmationButtonLabel={t("settingsRemoveAllMonitorsDialogConfirm")}
+ onConfirm={() => {
+ const syntheticEvent = {
+ target: {
+ name: "deleteMonitors",
+ },
+ };
+ handleChange(syntheticEvent);
+ setIsOpen(false);
+ }}
+ isLoading={isLoading}
+ />
+
+ >
+ );
+};
+
+SettingsDemoMonitors.propTypes = {
+ isAdmin: PropTypes.bool,
+ handleChange: PropTypes.func,
+ HEADER_SX: PropTypes.object,
+};
+
+export default SettingsDemoMonitors;
diff --git a/client/src/Pages/Settings/SettingsEmail.jsx b/client/src/Pages/Settings/SettingsEmail.jsx
new file mode 100644
index 000000000..694219614
--- /dev/null
+++ b/client/src/Pages/Settings/SettingsEmail.jsx
@@ -0,0 +1,150 @@
+import Box from "@mui/material/Box";
+import Typography from "@mui/material/Typography";
+import ConfigBox from "../../Components/ConfigBox";
+import TextInput from "../../Components/Inputs/TextInput";
+import Button from "@mui/material/Button";
+import Stack from "@mui/material/Stack";
+// Utils
+import { useTheme } from "@emotion/react";
+import { PropTypes } from "prop-types";
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { PasswordEndAdornment } from "../../Components/Inputs/TextInput/Adornments";
+import { useSendTestEmail } from "../../Hooks/useSendTestEmail";
+
+const SettingsEmail = ({
+ isAdmin,
+ HEADER_SX,
+ handleChange,
+ settingsData,
+ setSettingsData,
+ isPasswordSet,
+}) => {
+ // Setup
+ const { t } = useTranslation();
+ const theme = useTheme();
+
+ // Local state
+ const [password, setPassword] = useState("");
+ const [hasBeenReset, setHasBeenReset] = useState(false);
+
+ // Network
+ const [isSending, error, sendTestEmail] = useSendTestEmail();
+
+ // Handlers
+ const handlePasswordChange = (e) => {
+ setPassword(e.target.value);
+ setSettingsData({
+ ...settingsData,
+ settings: { ...settingsData.settings, systemEmailPassword: e.target.value },
+ });
+ };
+
+ if (!isAdmin) {
+ return null;
+ }
+
+ return (
+
+
+ {t("settingsEmail")}
+ {t("settingsEmailDescription")}
+
+
+
+
+ {t("settingsEmailHost")}
+
+
+
+ {t("settingsEmailPort")}
+
+
+
+ {t("settingsEmailUser")}
+
+
+
+ {t("settingsEmailAddress")}
+
+
+ {(isPasswordSet === false || hasBeenReset === true) && (
+
+ {t("settingsEmailPassword")}
+ }
+ />
+
+ )}
+ {isPasswordSet === true && hasBeenReset === false && (
+
+ {t("settingsEmailFieldResetLabel")}
+ {
+ setPassword("");
+ setSettingsData({
+ ...settingsData,
+ settings: { ...settingsData.settings, systemEmailPassword: "" },
+ });
+ setHasBeenReset(true);
+ }}
+ variant="contained"
+ color="error"
+ sx={{ mt: theme.spacing(4) }}
+ >
+ {t("reset")}
+
+
+ )}
+
+
+ Send test e-mail
+
+
+
+
+
+ );
+};
+
+SettingsEmail.propTypes = {
+ isAdmin: PropTypes.bool,
+ settingsData: PropTypes.object,
+ setSettingsData: PropTypes.func,
+ handleChange: PropTypes.func,
+ HEADER_SX: PropTypes.object,
+ isPasswordSet: PropTypes.bool,
+};
+
+export default SettingsEmail;
diff --git a/client/src/Pages/Settings/SettingsPagespeed.jsx b/client/src/Pages/Settings/SettingsPagespeed.jsx
new file mode 100644
index 000000000..c3636d0a1
--- /dev/null
+++ b/client/src/Pages/Settings/SettingsPagespeed.jsx
@@ -0,0 +1,93 @@
+import Box from "@mui/material/Box";
+import Stack from "@mui/material/Stack";
+import Typography from "@mui/material/Typography";
+import Button from "@mui/material/Button";
+import ConfigBox from "../../Components/ConfigBox";
+import TextInput from "../../Components/Inputs/TextInput";
+import { PasswordEndAdornment } from "../../Components/Inputs/TextInput/Adornments";
+// Utils
+import { useTheme } from "@emotion/react";
+import { PropTypes } from "prop-types";
+import { useState, useEffect } from "react";
+import { useTranslation } from "react-i18next";
+
+const SettingsPagespeed = ({
+ isAdmin,
+ HEADING_SX,
+ settingsData,
+ setSettingsData,
+ isApiKeySet,
+}) => {
+ const { t } = useTranslation();
+ const theme = useTheme();
+
+ // Local state
+ const [apiKey, setApiKey] = useState("");
+ const [hasBeenReset, setHasBeenReset] = useState(false);
+
+ // Handler
+ const handleChange = (e) => {
+ setApiKey(e.target.value);
+ setSettingsData({
+ ...settingsData,
+ settings: { ...settingsData.settings, pagespeedApiKey: e.target.value },
+ });
+ };
+
+ if (!isAdmin) {
+ return null;
+ }
+
+ return (
+
+
+ {t("pageSpeedApiKeyFieldTitle")}
+ {t("pageSpeedApiKeyFieldDescription")}
+
+
+ {(isApiKeySet === false || hasBeenReset === true) && (
+ }
+ />
+ )}
+
+ {isApiKeySet === true && hasBeenReset === false && (
+
+ {t("pageSpeedApiKeyFieldResetLabel")}
+ {
+ setApiKey("");
+ setSettingsData({
+ ...settingsData,
+ settings: { ...settingsData.settings, pagespeedApiKey: "" },
+ });
+ setHasBeenReset(true);
+ }}
+ variant="contained"
+ color="error"
+ sx={{ mt: theme.spacing(4) }}
+ >
+ {t("reset")}
+
+
+ )}
+
+
+ );
+};
+
+SettingsPagespeed.propTypes = {
+ isAdmin: PropTypes.bool,
+ HEADING_SX: PropTypes.object,
+ settingsData: PropTypes.object,
+ setSettingsData: PropTypes.func,
+ isApiKeySet: PropTypes.bool,
+};
+
+export default SettingsPagespeed;
diff --git a/client/src/Pages/Settings/SettingsStats.jsx b/client/src/Pages/Settings/SettingsStats.jsx
new file mode 100644
index 000000000..dd4fa11c0
--- /dev/null
+++ b/client/src/Pages/Settings/SettingsStats.jsx
@@ -0,0 +1,90 @@
+import Box from "@mui/material/Box";
+import Typography from "@mui/material/Typography";
+import Button from "@mui/material/Button";
+import Stack from "@mui/material/Stack";
+import ConfigBox from "../../Components/ConfigBox";
+import TextInput from "../../Components/Inputs/TextInput";
+import Dialog from "../../Components/Dialog";
+
+// Utils
+import { useTheme } from "@emotion/react";
+import { PropTypes } from "prop-types";
+import { useTranslation } from "react-i18next";
+import { useState } from "react";
+
+const SettingsStats = ({ isAdmin, HEADING_SX, handleChange, settingsData, errors }) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ const [isOpen, setIsOpen] = useState(false);
+
+ if (!isAdmin) {
+ return null;
+ }
+
+ return (
+
+
+
+ {t("settingsHistoryAndMonitoring")}
+
+
+ {t("settingsHistoryAndMonitoringDescription")}
+
+
+
+
+
+ {t("settingsClearAllStats")}
+ setIsOpen(true)}
+ sx={{ mt: theme.spacing(4) }}
+ >
+ {t("settingsClearAllStatsButton")}
+
+
+
+ setIsOpen(false)}
+ confirmationButtonLabel={t("settingsClearAllStatsDialogConfirm")}
+ onConfirm={() => {
+ const syntheticEvent = {
+ target: {
+ name: "deleteStats",
+ },
+ };
+ handleChange(syntheticEvent);
+ setIsOpen(false);
+ }}
+ isLoading={false}
+ />
+
+ );
+};
+
+SettingsStats.propTypes = {
+ isAdmin: PropTypes.bool,
+ HEADING_SX: PropTypes.object,
+ handleChange: PropTypes.func,
+ settingsData: PropTypes.object,
+ errors: PropTypes.object,
+};
+
+export default SettingsStats;
diff --git a/client/src/Pages/Settings/SettingsTimeZone.jsx b/client/src/Pages/Settings/SettingsTimeZone.jsx
new file mode 100644
index 000000000..e6ba1a77b
--- /dev/null
+++ b/client/src/Pages/Settings/SettingsTimeZone.jsx
@@ -0,0 +1,43 @@
+import Box from "@mui/material/Box";
+import Stack from "@mui/material/Stack";
+import Typography from "@mui/material/Typography";
+import ConfigBox from "../../Components/ConfigBox";
+import Select from "../../Components/Inputs/Select";
+import timezones from "../../Utils/timezones.json";
+
+// Utils
+import { useTheme } from "@emotion/react";
+import { PropTypes } from "prop-types";
+import { useTranslation } from "react-i18next";
+const SettingsTimeZone = ({ HEADING_SX, handleChange, timezone }) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ return (
+
+
+ {t("settingsGeneralSettings")}
+
+ {t("settingsDisplayTimezone")} -{" "}
+ {t("settingsDisplayTimezoneDescription")}
+
+
+
+
+
+
+ );
+};
+
+SettingsTimeZone.propTypes = {
+ HEADING_SX: PropTypes.object,
+ handleChange: PropTypes.func,
+ timezone: PropTypes.string,
+};
+
+export default SettingsTimeZone;
diff --git a/client/src/Pages/Settings/SettingsUI.jsx b/client/src/Pages/Settings/SettingsUI.jsx
new file mode 100644
index 000000000..24588d79e
--- /dev/null
+++ b/client/src/Pages/Settings/SettingsUI.jsx
@@ -0,0 +1,52 @@
+import Box from "@mui/material/Box";
+import Stack from "@mui/material/Stack";
+import Typography from "@mui/material/Typography";
+import ConfigBox from "../../Components/ConfigBox";
+import Select from "../../Components/Inputs/Select";
+
+// Utils
+import { useTheme } from "@emotion/react";
+import { PropTypes } from "prop-types";
+import { useTranslation } from "react-i18next";
+
+const SettingsUI = ({ HEADING_SX, handleChange, mode, language }) => {
+ const { t, i18n } = useTranslation();
+ const theme = useTheme();
+ const languages = Object.keys(i18n.options.resources || {});
+ return (
+
+
+ {t("settingsAppearance")}
+ {t("settingsAppearanceDescription")}
+
+
+
+ ({ _id: lang, name: lang.toUpperCase() }))}
+ >
+
+
+ );
+};
+
+SettingsUI.propTypes = {
+ HEADING_SX: PropTypes.object,
+ handleChange: PropTypes.func,
+ mode: PropTypes.string,
+ language: PropTypes.string,
+};
+
+export default SettingsUI;
diff --git a/client/src/Pages/Settings/index.jsx b/client/src/Pages/Settings/index.jsx
new file mode 100644
index 000000000..66662dc58
--- /dev/null
+++ b/client/src/Pages/Settings/index.jsx
@@ -0,0 +1,208 @@
+import Stack from "@mui/material/Stack";
+import Typography from "@mui/material/Typography";
+import Breadcrumbs from "../../Components/Breadcrumbs";
+import SettingsTimeZone from "./SettingsTimeZone";
+import SettingsUI from "./SettingsUI";
+import SettingsPagespeed from "./SettingsPagespeed";
+import SettingsDemoMonitors from "./SettingsDemoMonitors";
+import SettingsAbout from "./SettingsAbout";
+import SettingsEmail from "./SettingsEmail";
+import Button from "@mui/material/Button";
+// Utils
+import { settingsValidation } from "../../Validation/validation";
+import { createToast } from "../../Utils/toastUtils";
+import { useState } from "react";
+import { useTheme } from "@emotion/react";
+import { useTranslation } from "react-i18next";
+import { useSelector, useDispatch } from "react-redux";
+import { setTimezone, setMode, setLanguage } from "../../Features/UI/uiSlice";
+import SettingsStats from "./SettingsStats";
+import {
+ deleteMonitorChecksByTeamId,
+ addDemoMonitors,
+ deleteAllMonitors,
+} from "../../Features/UptimeMonitors/uptimeMonitorsSlice";
+import { useFetchSettings, useSaveSettings } from "../../Hooks/useFetchSettings";
+import { UseDeleteMonitorStats } from "../../Hooks/useDeleteMonitorStats";
+import { useIsAdmin } from "../../Hooks/useIsAdmin";
+
+// Constants
+const BREADCRUMBS = [{ name: `Settings`, path: "/settings" }];
+
+const Settings = () => {
+ // Redux state
+ const { mode, language, timezone } = useSelector((state) => state.ui);
+ const { user } = useSelector((state) => state.auth);
+
+ // Local state
+ const [settingsData, setSettingsData] = useState({});
+ const [errors, setErrors] = useState({});
+
+ // Network
+ const [isSettingsLoading, settingsError] = useFetchSettings({
+ setSettingsData,
+ });
+
+ const [isSaving, saveError, saveSettings] = useSaveSettings();
+ const [deleteMonitorStats, isDeletingMonitorStats] = UseDeleteMonitorStats();
+
+ // Setup
+ const isAdmin = useIsAdmin();
+ const theme = useTheme();
+ const HEADING_SX = { mt: theme.spacing(2), mb: theme.spacing(2) };
+ const { t, i18n } = useTranslation();
+ const dispatch = useDispatch();
+
+ // Handlers
+ const handleChange = async (e) => {
+ const { name, value } = e.target;
+
+ // Build next state early
+ const newSettingsData = {
+ ...settingsData,
+ settings: { ...settingsData.settings, [name]: value },
+ };
+
+ // Validate
+ const { error } = settingsValidation.validate(newSettingsData.settings, {
+ abortEarly: false,
+ });
+ if (!error || error.details.length === 0) {
+ setErrors({});
+ } else {
+ const newErrors = {};
+ error.details.forEach((err) => {
+ newErrors[err.path[0]] = err.message;
+ });
+ setErrors(newErrors);
+ }
+
+ if (name === "timezone") {
+ dispatch(setTimezone({ timezone: value }));
+ }
+
+ if (name === "mode") {
+ dispatch(setMode(value));
+ }
+
+ if (name === "language") {
+ dispatch(setLanguage(value));
+ i18n.changeLanguage(value);
+ }
+
+ if (name === "deleteStats") {
+ await deleteMonitorStats({ teamId: user.teamId });
+ return;
+ }
+
+ if (name === "demo") {
+ try {
+ const action = await dispatch(addDemoMonitors());
+ if (addDemoMonitors.fulfilled.match(action)) {
+ createToast({ body: t("settingsDemoMonitorsAdded") });
+ } else {
+ createToast({ body: t("settingsFailedToAddDemoMonitors") });
+ }
+ } catch (error) {
+ createToast({ body: t("settingsFailedToAddDemoMonitors") });
+ }
+ return;
+ }
+
+ if (name === "deleteMonitors") {
+ try {
+ const action = await dispatch(deleteAllMonitors());
+ if (deleteAllMonitors.fulfilled.match(action)) {
+ createToast({ body: t("settingsMonitorsDeleted") });
+ } else {
+ createToast({ body: t("settingsFailedToDeleteMonitors") });
+ }
+ } catch (error) {
+ createToast({ body: t("settingsFailedToDeleteMonitors") });
+ }
+ return;
+ }
+
+ setSettingsData(newSettingsData);
+ };
+
+ const handleSave = () => {
+ const { error } = settingsValidation.validate(settingsData.settings, {
+ abortEarly: false,
+ });
+ if (!error || error.details.length === 0) {
+ setErrors({});
+ } else {
+ const newErrors = {};
+ error.details.forEach((err) => {
+ newErrors[err.path[0]] = err.message;
+ });
+ setErrors(newErrors);
+ }
+ saveSettings(settingsData?.settings);
+ };
+
+ return (
+
+
+ Settings
+
+
+
+
+
+
+
+
+ 0}
+ variant="contained"
+ color="accent"
+ sx={{ px: theme.spacing(12), mt: theme.spacing(20) }}
+ onClick={handleSave}
+ >
+ {t("settingsSave")}
+
+
+
+ );
+};
+
+export default Settings;
diff --git a/client/src/Pages/StatusPage/Create/Components/MonitorList/index.jsx b/client/src/Pages/StatusPage/Create/Components/MonitorList/index.jsx
new file mode 100644
index 000000000..5484202d5
--- /dev/null
+++ b/client/src/Pages/StatusPage/Create/Components/MonitorList/index.jsx
@@ -0,0 +1,106 @@
+// Components
+import { Stack, Typography } from "@mui/material";
+import ReorderRoundedIcon from "@mui/icons-material/ReorderRounded";
+import DeleteIcon from "@mui/icons-material/Delete";
+
+// Utils
+import { DragDropContext, Droppable, Draggable } from "@hello-pangea/dnd";
+import { useTheme } from "@emotion/react";
+const MonitorListItem = ({
+ monitor,
+ innerRef,
+ draggableProps,
+ dragHandleProps,
+ onDelete,
+}) => {
+ const theme = useTheme();
+ return (
+
+
+ {monitor.name}
+ {
+ onDelete(monitor);
+ }}
+ />
+
+ );
+};
+
+const MonitorList = ({ selectedMonitors, setSelectedMonitors }) => {
+ const onDelete = (monitorToDelete) => {
+ const newMonitors = selectedMonitors.filter(
+ (monitor) => monitor._id !== monitorToDelete._id
+ );
+ setSelectedMonitors(newMonitors);
+ };
+ const reorder = (list, startIndex, endIndex) => {
+ const result = Array.from(list);
+ const [removed] = result.splice(startIndex, 1);
+ result.splice(endIndex, 0, removed);
+
+ return result;
+ };
+
+ const onDragEnd = (result) => {
+ // dropped outside the list
+ if (!result.destination) {
+ return;
+ }
+
+ const reorderedMonitors = reorder(
+ selectedMonitors,
+ result.source.index,
+ result.destination.index
+ );
+
+ setSelectedMonitors(reorderedMonitors);
+ };
+
+ return (
+
+
+ {(provided, snapshot) => (
+
+ {selectedMonitors?.map((monitor, index) => (
+
+ {(provided, snapshot) => (
+
+ )}
+
+ ))}
+ {provided.placeholder}
+
+ )}
+
+
+ );
+};
+
+export default MonitorList;
diff --git a/client/src/Pages/StatusPage/Create/Components/Progress/index.jsx b/client/src/Pages/StatusPage/Create/Components/Progress/index.jsx
new file mode 100644
index 000000000..14c4ce0f5
--- /dev/null
+++ b/client/src/Pages/StatusPage/Create/Components/Progress/index.jsx
@@ -0,0 +1,38 @@
+import { Button, Box } from "@mui/material";
+import ProgressUpload from "../../../../../Components/ProgressBars";
+import ImageIcon from "@mui/icons-material/Image";
+import { useTranslation } from "react-i18next";
+import { formatBytes } from "../../../../../Utils/fileUtils";
+const Progress = ({ isLoading, progressValue, logo, logoType, removeLogo, errors }) => {
+ const { t } = useTranslation();
+ if (isLoading) {
+ return (
+ }
+ label={logo?.name}
+ size={formatBytes(logo?.size)}
+ progress={progressValue}
+ onClick={removeLogo}
+ />
+ );
+ }
+
+ if (logo && logoType) {
+ return (
+
+
+ {t("removeLogo")}
+
+
+ );
+ }
+};
+
+export default Progress;
diff --git a/client/src/Pages/StatusPage/Create/Components/Skeleton/index.jsx b/client/src/Pages/StatusPage/Create/Components/Skeleton/index.jsx
new file mode 100644
index 000000000..482c490fb
--- /dev/null
+++ b/client/src/Pages/StatusPage/Create/Components/Skeleton/index.jsx
@@ -0,0 +1,14 @@
+import { Stack, Skeleton } from "@mui/material";
+
+const SkeletonLayout = () => {
+ return (
+
+
+
+ );
+};
+
+export default SkeletonLayout;
diff --git a/client/src/Pages/StatusPage/Create/Components/Tabs/ConfigStack.jsx b/client/src/Pages/StatusPage/Create/Components/Tabs/ConfigStack.jsx
new file mode 100644
index 000000000..6eb64a519
--- /dev/null
+++ b/client/src/Pages/StatusPage/Create/Components/Tabs/ConfigStack.jsx
@@ -0,0 +1,26 @@
+import { Stack, Typography } from "@mui/material";
+import ConfigBox from "../../../../../Components/ConfigBox";
+import PropTypes from "prop-types";
+import { useTheme } from "@emotion/react";
+
+// This can be used to add any extra/additional section/stacks on top of existing sections on the tab
+const ConfigStack = ({ title, description, children }) => {
+ const theme = useTheme();
+ return (
+
+
+ {title}
+ {description}
+
+ {children}
+
+ );
+};
+
+ConfigStack.propTypes = {
+ title: PropTypes.string.isRequired, // Title must be a string and is required
+ description: PropTypes.string.isRequired, // Description must be a string and is required
+ children: PropTypes.node.isRequired,
+};
+
+export default ConfigStack;
diff --git a/client/src/Pages/StatusPage/Create/Components/Tabs/Content.jsx b/client/src/Pages/StatusPage/Create/Components/Tabs/Content.jsx
new file mode 100644
index 000000000..7423b05bd
--- /dev/null
+++ b/client/src/Pages/StatusPage/Create/Components/Tabs/Content.jsx
@@ -0,0 +1,100 @@
+// Components
+import { Stack, Typography } from "@mui/material";
+import { TabPanel } from "@mui/lab";
+import MonitorList from "../MonitorList";
+import Search from "../../../../../Components/Inputs/Search";
+import Checkbox from "../../../../../Components/Inputs/Checkbox";
+// Utils
+import { useState } from "react";
+import { useTheme } from "@emotion/react";
+import { useTranslation } from "react-i18next";
+import ConfigStack from "./ConfigStack";
+const Content = ({
+ tabValue,
+ form,
+ monitors,
+ handleFormChange,
+ errors,
+ selectedMonitors,
+ setSelectedMonitors,
+}) => {
+ // Local state
+ const [search, setSearch] = useState("");
+
+ // Handlers
+ const handleMonitorsChange = (selectedMonitors) => {
+ handleFormChange({
+ target: { name: "monitors", value: selectedMonitors.map((monitor) => monitor._id) },
+ });
+ setSelectedMonitors(selectedMonitors);
+ };
+
+ // Utils
+ const theme = useTheme();
+ const { t } = useTranslation();
+
+ return (
+
+
+
+
+
+
+
+
+ {errors["monitors"]}
+
+
+
+
+
+
+
+
+
+
+
+
+ );
+};
+
+export default Content;
diff --git a/client/src/Pages/StatusPage/Create/Components/Tabs/Settings.jsx b/client/src/Pages/StatusPage/Create/Components/Tabs/Settings.jsx
new file mode 100644
index 000000000..e3d0a0bc6
--- /dev/null
+++ b/client/src/Pages/StatusPage/Create/Components/Tabs/Settings.jsx
@@ -0,0 +1,145 @@
+// Components
+import { Stack, Typography } from "@mui/material";
+import { TabPanel } from "@mui/lab";
+import ConfigBox from "../../../../../Components/ConfigBox";
+import Checkbox from "../../../../../Components/Inputs/Checkbox";
+import TextInput from "../../../../../Components/Inputs/TextInput";
+import Select from "../../../../../Components/Inputs/Select";
+import ImageUpload from "../../../../../Components/Inputs/ImageUpload";
+import ColorPicker from "../../../../../Components/Inputs/ColorPicker";
+import Progress from "../Progress";
+
+// Utils
+import { useTheme } from "@emotion/react";
+import timezones from "../../../../../Utils/timezones.json";
+import PropTypes from "prop-types";
+import { useTranslation } from "react-i18next";
+
+const TabSettings = ({
+ isCreate,
+ tabValue,
+ form,
+ handleFormChange,
+ handleImageChange,
+ progress,
+ removeLogo,
+ errors,
+}) => {
+ // Utils
+ const theme = useTheme();
+ const { t } = useTranslation();
+
+ return (
+
+
+
+
+ {t("access")}
+
+ {t("statusPageCreateSettings")}
+
+
+
+
+
+
+
+
+ {t("basicInformation")}
+
+ {t("statusPageCreateBasicInfoDescription")}
+
+
+
+
+
+
+
+
+
+ {t("timezone")}
+
+ {t("statusPageCreateSelectTimeZoneDescription")}
+
+
+
+
+
+
+
+
+ {t("settingsAppearance")}
+
+ {t("statusPageCreateAppearanceDescription")}
+
+
+
+
+
+
+
+
+
+
+ );
+};
+
+TabSettings.propTypes = {
+ isCreate: PropTypes.bool,
+ tabValue: PropTypes.string,
+ form: PropTypes.object,
+ handleFormChange: PropTypes.func,
+ handleImageChange: PropTypes.func,
+ progress: PropTypes.object,
+ removeLogo: PropTypes.func,
+ errors: PropTypes.object,
+};
+
+export default TabSettings;
diff --git a/client/src/Pages/StatusPage/Create/Components/Tabs/index.jsx b/client/src/Pages/StatusPage/Create/Components/Tabs/index.jsx
new file mode 100644
index 000000000..5f5433bb6
--- /dev/null
+++ b/client/src/Pages/StatusPage/Create/Components/Tabs/index.jsx
@@ -0,0 +1,86 @@
+// Components
+import { TabContext } from "@mui/lab";
+import { Tab, useTheme } from "@mui/material";
+import Settings from "./Settings";
+import Content from "./Content";
+
+// Utils
+import PropTypes from "prop-types";
+import CustomTabList from "../../../../../Components/Tab";
+
+const Tabs = ({
+ isCreate,
+ form,
+ errors,
+ monitors,
+ selectedMonitors,
+ setSelectedMonitors,
+ handleFormChange,
+ handleImageChange,
+ progress,
+ removeLogo,
+ tab,
+ setTab,
+ TAB_LIST,
+}) => {
+
+ const theme = useTheme();
+ return (
+
+ {
+ setTab(TAB_LIST.indexOf(selected));
+ }}
+ aria-label="status page tabs"
+ >
+ {TAB_LIST.map((tabLabel, idx) => (
+
+ ))}
+
+ {tab === 0 ? (
+
+ ) : (
+
+ )}
+
+
+ );
+};
+
+Tabs.propTypes = {
+ form: PropTypes.object,
+ errors: PropTypes.object,
+ monitors: PropTypes.array,
+ selectedMonitors: PropTypes.array,
+ setSelectedMonitors: PropTypes.func,
+ handleFormChange: PropTypes.func,
+ handleImageChange: PropTypes.func,
+ progress: PropTypes.object,
+ removeLogo: PropTypes.func,
+ tab: PropTypes.number,
+ setTab: PropTypes.func,
+ TAB_LIST: PropTypes.array,
+};
+
+export default Tabs;
diff --git a/client/src/Pages/StatusPage/Create/Hooks/useCreateStatusPage.jsx b/client/src/Pages/StatusPage/Create/Hooks/useCreateStatusPage.jsx
new file mode 100644
index 000000000..8407955a6
--- /dev/null
+++ b/client/src/Pages/StatusPage/Create/Hooks/useCreateStatusPage.jsx
@@ -0,0 +1,28 @@
+import { useState } from "react";
+import { networkService } from "../../../../main";
+import { useSelector } from "react-redux";
+import { createToast } from "../../../../Utils/toastUtils";
+
+const useCreateStatusPage = (isCreate, url) => {
+ const { user } = useSelector((state) => state.auth);
+
+ const [isLoading, setIsLoading] = useState(false);
+ const [networkError, setNetworkError] = useState(false);
+ const createStatusPage = async ({ form }) => {
+ setIsLoading(true);
+ try {
+ await networkService.createStatusPage({ user, form, isCreate, url });
+ return true;
+ } catch (error) {
+ setNetworkError(true);
+ createToast({ body: error?.response?.data?.msg ?? error.message });
+ return false;
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return [createStatusPage, isLoading, networkError];
+};
+
+export { useCreateStatusPage };
diff --git a/client/src/Pages/StatusPage/Create/Hooks/useMonitorsFetch.jsx b/client/src/Pages/StatusPage/Create/Hooks/useMonitorsFetch.jsx
new file mode 100644
index 000000000..a665aa9eb
--- /dev/null
+++ b/client/src/Pages/StatusPage/Create/Hooks/useMonitorsFetch.jsx
@@ -0,0 +1,34 @@
+import { useEffect, useState } from "react";
+import { networkService } from "../../../../main";
+import { useSelector } from "react-redux";
+import { createToast } from "../../../../Utils/toastUtils";
+
+const useMonitorsFetch = () => {
+ const { user } = useSelector((state) => state.auth);
+
+ const [monitors, setMonitors] = useState(undefined);
+ const [isLoading, setIsLoading] = useState(true);
+ const [networkError, setNetworkError] = useState(false);
+ useEffect(() => {
+ const fetchMonitors = async () => {
+ try {
+ const response = await networkService.getMonitorsByTeamId({
+ teamId: user.teamId,
+ limit: null, // donot return any checks for the monitors
+ types: ["http"], // status page is available only for the uptime type
+ });
+ setMonitors(response.data.data.monitors);
+ } catch (error) {
+ setNetworkError(true);
+ createToast({ body: error.message });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+ fetchMonitors();
+ }, [user]);
+
+ return [monitors, isLoading, networkError];
+};
+
+export { useMonitorsFetch };
diff --git a/client/src/Pages/StatusPage/Create/index.jsx b/client/src/Pages/StatusPage/Create/index.jsx
new file mode 100644
index 000000000..5534ef68d
--- /dev/null
+++ b/client/src/Pages/StatusPage/Create/index.jsx
@@ -0,0 +1,253 @@
+// Components
+import { Stack, Button, Typography } from "@mui/material";
+import Tabs from "./Components/Tabs";
+import GenericFallback from "../../../Components/GenericFallback";
+import SkeletonLayout from "./Components/Skeleton";
+//Utils
+import { useTheme } from "@emotion/react";
+import { useState, useEffect, useRef, useCallback } from "react";
+import { statusPageValidation } from "../../../Validation/validation";
+import { buildErrors } from "../../../Validation/error";
+import { useMonitorsFetch } from "./Hooks/useMonitorsFetch";
+import { useCreateStatusPage } from "./Hooks/useCreateStatusPage";
+import { createToast } from "../../../Utils/toastUtils";
+import { useNavigate } from "react-router-dom";
+import { useStatusPageFetch } from "../Status/Hooks/useStatusPageFetch";
+import { useParams } from "react-router-dom";
+import { useTranslation } from "react-i18next";
+//Constants
+const TAB_LIST = ["General settings", "Contents"];
+
+const ERROR_TAB_MAPPING = [
+ ["companyName", "url", "timezone", "color", "isPublished", "logo"],
+ ["monitors", "showUptimePercentage", "showCharts"],
+];
+
+const CreateStatusPage = () => {
+ const { url } = useParams();
+ //Local state
+ const [tab, setTab] = useState(0);
+ const [progress, setProgress] = useState({ value: 0, isLoading: false });
+ const [form, setForm] = useState({
+ isPublished: false,
+ companyName: "",
+ url: url ?? Math.floor(Math.random() * 1000000).toFixed(0),
+ logo: undefined,
+ timezone: "America/Toronto",
+ color: "#4169E1",
+ type: "uptime",
+ monitors: [],
+ showCharts: true,
+ showUptimePercentage: true,
+ });
+ const [errors, setErrors] = useState({});
+ const [selectedMonitors, setSelectedMonitors] = useState([]);
+ // Refs
+ const intervalRef = useRef(null);
+
+ // Setup
+ const isCreate = typeof url === "undefined";
+
+ //Utils
+ const theme = useTheme();
+ const [monitors, isLoading, networkError] = useMonitorsFetch();
+ const [createStatusPage, createStatusIsLoading, createStatusPageNetworkError] =
+ useCreateStatusPage(isCreate);
+ const navigate = useNavigate();
+ const { t } = useTranslation();
+
+ const [statusPage, statusPageMonitors, statusPageIsLoading, statusPageNetworkError] =
+ useStatusPageFetch(isCreate, url);
+
+ // Handlers
+ const handleFormChange = (e) => {
+ let { type, name, value, checked } = e.target;
+ // Handle errors
+ const { error } = statusPageValidation.validate(
+ { [name]: value },
+ { abortEarly: false }
+ );
+ setErrors((prev) => {
+ return buildErrors(prev, name, error);
+ });
+
+ //Handle checkbox
+ if (type === "checkbox") {
+ setForm((prev) => ({
+ ...prev,
+ [name]: checked,
+ }));
+ return;
+ }
+
+ // Handle other inputs
+ setForm((prev) => ({
+ ...prev,
+ [name]: value,
+ }));
+ };
+
+ const handleImageChange = useCallback((fileObj) => {
+ if (!fileObj || !fileObj.file) return;
+
+ setForm((prev) => ({
+ ...prev,
+ logo: {
+ src: fileObj.src,
+ name: fileObj.name,
+ type: fileObj.file.type,
+ size: fileObj.file.size,
+ },
+ }));
+
+ intervalRef.current = setInterval(() => {
+ const buffer = 12;
+ setProgress((prev) => {
+ if (prev.value + buffer >= 100) {
+ clearInterval(intervalRef.current);
+ return { value: 100, isLoading: false };
+ }
+ return { ...prev, value: prev.value + buffer };
+ });
+ }, 120);
+ }, []);
+
+ const removeLogo = () => {
+ setForm((prev) => ({
+ ...prev,
+ logo: undefined,
+ }));
+ // interrupt interval if image upload is canceled prior to completing the process
+ clearInterval(intervalRef.current);
+ setProgress({ value: 0, isLoading: false });
+ };
+
+ const handleSubmit = async () => {
+ let toSubmit = {
+ ...form,
+ logo: { type: form.logo?.type ?? null, size: form.logo?.size ?? null },
+ };
+ const { error } = statusPageValidation.validate(toSubmit, {
+ abortEarly: false,
+ });
+
+ if (typeof error === "undefined") {
+ const success = await createStatusPage({ form });
+ if (success) {
+ createToast({
+ body: isCreate
+ ? "Status page created successfully"
+ : "Status page updated successfully",
+ });
+ navigate(`/status/uptime/${form.url}`);
+ }
+ return;
+ }
+
+ const newErrors = {};
+ error?.details?.forEach((err) => {
+ newErrors[err.path[0]] = err.message;
+ });
+ setErrors((prev) => ({ ...prev, ...newErrors }));
+ const errorTabs = Object.keys(newErrors).map((err) => {
+ return ERROR_TAB_MAPPING.findIndex((tab) => tab.includes(err));
+ });
+
+ // If there's an error in the current tab, don't change the tab
+ if (errorTabs.some((errorTab) => errorTab === tab)) {
+ return;
+ }
+
+ // If we get -1, there's an unknown error
+ if (errorTabs[0] === -1) {
+ createToast({ body: "Unknown error" });
+ return;
+ }
+
+ // Otherwise go to tab with error
+ setTab(errorTabs[0]);
+ };
+
+ // If we are configuring, populate fields
+ useEffect(() => {
+ if (isCreate) return;
+ if (typeof statusPage === "undefined") {
+ return;
+ }
+
+ let newLogo = undefined;
+ if (statusPage.logo) {
+ newLogo = {
+ src: `data:${statusPage.logo.contentType};base64,${statusPage.logo.data}`,
+ name: "logo",
+ type: statusPage.logo.contentType,
+ size: null,
+ };
+ }
+
+ setForm((prev) => {
+ return {
+ ...prev,
+ companyName: statusPage?.companyName,
+ isPublished: statusPage?.isPublished,
+ timezone: statusPage?.timezone,
+ monitors: statusPageMonitors.map((monitor) => monitor._id),
+ color: statusPage?.color,
+ logo: newLogo,
+ };
+ });
+ setSelectedMonitors(statusPageMonitors);
+ }, [isCreate, statusPage, statusPageMonitors]);
+
+ if (networkError === true) {
+ return (
+
+
+ {t("networkError")}
+
+ {t("checkConnection")}
+
+ );
+ }
+
+ if (isLoading) return ;
+
+ // Load fields
+ return (
+
+
+
+
+ {t("settingsSave")}
+
+
+
+ );
+};
+
+export default CreateStatusPage;
diff --git a/client/src/Pages/StatusPage/Status/Components/AdminLink/index.jsx b/client/src/Pages/StatusPage/Status/Components/AdminLink/index.jsx
new file mode 100644
index 000000000..816fbd375
--- /dev/null
+++ b/client/src/Pages/StatusPage/Status/Components/AdminLink/index.jsx
@@ -0,0 +1,36 @@
+// Components
+import { Box, Typography } from "@mui/material";
+
+// Utils
+import { useTheme } from "@mui/material/styles";
+import { useNavigate } from "react-router-dom";
+import { useTranslation } from "react-i18next";
+
+const AdminLink = () => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+
+ return (
+
+
+ {t("administrator")}
+
+ navigate("/login")}
+ >
+ {t("loginHere")}
+
+
+ );
+};
+
+export default AdminLink;
diff --git a/client/src/Pages/StatusPage/Status/Components/ControlsHeader/index.jsx b/client/src/Pages/StatusPage/Status/Components/ControlsHeader/index.jsx
new file mode 100644
index 000000000..7546e8725
--- /dev/null
+++ b/client/src/Pages/StatusPage/Status/Components/ControlsHeader/index.jsx
@@ -0,0 +1,167 @@
+// Components
+import { Box, Stack, Typography, Button } from "@mui/material";
+import Image from "../../../../../Components/Image";
+import SettingsIcon from "../../../../../assets/icons/settings-bold.svg?react";
+import ThemeSwitch from "../../../../../Components/ThemeSwitch";
+import ArrowOutwardIcon from "@mui/icons-material/ArrowOutward";
+//Utils
+import { useTheme } from "@mui/material/styles";
+import { useNavigate } from "react-router-dom";
+import { useLocation } from "react-router-dom";
+import PropTypes from "prop-types";
+import { useTranslation } from "react-i18next";
+
+const Controls = ({ isDeleteOpen, setIsDeleteOpen, isDeleting, url, type }) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ const location = useLocation();
+ const currentPath = location.pathname;
+ const navigate = useNavigate();
+
+ if (currentPath.startsWith("/status/uptime/public")) {
+ return null;
+ }
+
+ if (currentPath.startsWith("/status/distributed/public")) {
+ return null;
+ }
+
+ return (
+
+
+ setIsDeleteOpen(!isDeleteOpen)}
+ loading={isDeleting}
+ >
+ {t("delete")}
+
+
+
+ {
+ if (type === "uptime") {
+ navigate(`/status/uptime/configure/${url}`);
+ } else {
+ navigate(`/status/distributed/configure/${url}`);
+ }
+ }}
+ sx={{
+ px: theme.spacing(5),
+ "& svg": {
+ mr: theme.spacing(3),
+ "& path": {
+ stroke: theme.palette.secondary.contrastText,
+ },
+ },
+ }}
+ >
+ {t("configure")}
+
+
+
+ );
+};
+
+Controls.propTypes = {
+ type: PropTypes.string,
+ isDeleting: PropTypes.bool,
+ url: PropTypes.string,
+ isDeleteOpen: PropTypes.bool.isRequired,
+ setIsDeleteOpen: PropTypes.func.isRequired,
+};
+
+const ControlsHeader = ({
+ statusPage,
+ isPublic,
+ isDeleting,
+ isDeleteOpen,
+ setIsDeleteOpen,
+ url,
+ type = "uptime",
+}) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ const publicUrl = `/status/uptime/public/${url}`;
+
+ return (
+
+
+
+
+ {statusPage?.companyName}
+
+ {statusPage?.isPublished && !isPublic && (
+ {
+ window.open(publicUrl, "_blank", "noopener,noreferrer");
+ }}
+ sx={{
+ display: "inline-flex",
+ ":hover": {
+ cursor: "pointer",
+ borderBottom: 1,
+ },
+ }}
+ >
+ {t("publicLink")}
+
+
+ )}
+
+
+ {isPublic && }
+
+ );
+};
+
+ControlsHeader.propTypes = {
+ url: PropTypes.string,
+ statusPage: PropTypes.object,
+ isPublic: PropTypes.bool,
+ isDeleting: PropTypes.bool,
+ isDeleteOpen: PropTypes.bool.isRequired,
+ setIsDeleteOpen: PropTypes.func.isRequired,
+ type: PropTypes.string,
+};
+
+export default ControlsHeader;
diff --git a/client/src/Pages/StatusPage/Status/Components/MonitorsList/index.jsx b/client/src/Pages/StatusPage/Status/Components/MonitorsList/index.jsx
new file mode 100644
index 000000000..10cfec129
--- /dev/null
+++ b/client/src/Pages/StatusPage/Status/Components/MonitorsList/index.jsx
@@ -0,0 +1,58 @@
+// Components
+import { Stack, Box } from "@mui/material";
+import Host from "../../../../../Components/Host";
+import StatusPageBarChart from "../../../../../Components/Charts/StatusPageBarChart";
+import { StatusLabel } from "../../../../../Components/Label";
+
+//Utils
+import { useTheme } from "@mui/material/styles";
+import useUtils from "../../../../Uptime/Monitors/Hooks/useUtils";
+import PropTypes from "prop-types";
+const MonitorsList = ({ isLoading = false, shouldRender = true, monitors = [] }) => {
+ const theme = useTheme();
+ const { determineState } = useUtils();
+ return (
+ <>
+ {monitors?.map((monitor) => {
+ const status = determineState(monitor);
+ return (
+
+
+
+
+
+
+
+
+
+
+
+ );
+ })}
+ >
+ );
+};
+
+MonitorsList.propTypes = {
+ monitors: PropTypes.array.isRequired,
+};
+
+export default MonitorsList;
diff --git a/client/src/Pages/StatusPage/Status/Components/Skeleton/index.jsx b/client/src/Pages/StatusPage/Status/Components/Skeleton/index.jsx
new file mode 100644
index 000000000..482c490fb
--- /dev/null
+++ b/client/src/Pages/StatusPage/Status/Components/Skeleton/index.jsx
@@ -0,0 +1,14 @@
+import { Stack, Skeleton } from "@mui/material";
+
+const SkeletonLayout = () => {
+ return (
+
+
+
+ );
+};
+
+export default SkeletonLayout;
diff --git a/client/src/Pages/StatusPage/Status/Components/StatusBar/index.jsx b/client/src/Pages/StatusPage/Status/Components/StatusBar/index.jsx
new file mode 100644
index 000000000..1898ff3d7
--- /dev/null
+++ b/client/src/Pages/StatusPage/Status/Components/StatusBar/index.jsx
@@ -0,0 +1,74 @@
+// Components
+import { Stack, Typography } from "@mui/material";
+import CheckCircleIcon from "@mui/icons-material/CheckCircle";
+import ErrorOutlineIcon from "@mui/icons-material/ErrorOutline";
+
+// Utils
+import { useTheme } from "@mui/material/styles";
+import PropTypes from "prop-types";
+
+const getMonitorStatus = (monitors, theme) => {
+ const monitorsStatus = {
+ icon: (
+
+ ),
+ };
+ if (monitors.every((monitor) => monitor.status === true)) {
+ monitorsStatus.msg = "All systems operational";
+ monitorsStatus.color = theme.palette.success.lowContrast;
+ monitorsStatus.icon = (
+
+ );
+ }
+
+ if (monitors.every((monitor) => monitor.status === false)) {
+ monitorsStatus.msg = "All systems down";
+ monitorsStatus.color = theme.palette.error.lowContrast;
+ }
+
+ if (monitors.some((monitor) => monitor.status === false)) {
+ monitorsStatus.msg = "Degraded performance";
+ monitorsStatus.color = theme.palette.warning.lowContrast;
+ }
+
+ // Paused or unknown
+ if (monitors.some((monitor) => typeof monitor.status === "undefined")) {
+ monitorsStatus.msg = "Unknown status";
+ monitorsStatus.color = theme.palette.warning.lowContrast;
+ }
+ return monitorsStatus;
+};
+
+const StatusBar = ({ monitors }) => {
+ const theme = useTheme();
+
+ if (typeof monitors === "undefined") return;
+
+ const monitorsStatus = getMonitorStatus(monitors, theme);
+ return (
+
+ {monitorsStatus.icon}
+ {/* CAIO_REVIEW */}
+ {monitorsStatus.msg}
+
+ );
+};
+
+export default StatusBar;
+
+StatusBar.propTypes = {
+ status: PropTypes.object,
+};
diff --git a/client/src/Pages/StatusPage/Status/Hooks/useStatusPageDelete.jsx b/client/src/Pages/StatusPage/Status/Hooks/useStatusPageDelete.jsx
new file mode 100644
index 000000000..d5c87c530
--- /dev/null
+++ b/client/src/Pages/StatusPage/Status/Hooks/useStatusPageDelete.jsx
@@ -0,0 +1,27 @@
+import { useSelector } from "react-redux";
+import { useState } from "react";
+import { networkService } from "../../../../main";
+import { createToast } from "../../../../Utils/toastUtils";
+
+const useStatusPageDelete = (fetchStatusPage, url) => {
+ const [isLoading, setIsLoading] = useState(false);
+ const deleteStatusPage = async () => {
+ try {
+ setIsLoading(true);
+ await networkService.deleteStatusPage({ url });
+ fetchStatusPage?.();
+ return true;
+ } catch (error) {
+ createToast({
+ body: error.message,
+ });
+ return false;
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return [deleteStatusPage, isLoading];
+};
+
+export { useStatusPageDelete };
diff --git a/client/src/Pages/StatusPage/Status/Hooks/useStatusPageFetch.jsx b/client/src/Pages/StatusPage/Status/Hooks/useStatusPageFetch.jsx
new file mode 100644
index 000000000..ae9c7b579
--- /dev/null
+++ b/client/src/Pages/StatusPage/Status/Hooks/useStatusPageFetch.jsx
@@ -0,0 +1,53 @@
+import { useEffect, useState, useCallback } from "react";
+import { networkService } from "../../../../main";
+import { useSelector } from "react-redux";
+import { createToast } from "../../../../Utils/toastUtils";
+import { useTheme } from "@emotion/react";
+import { useMonitorUtils } from "../../../../Hooks/useMonitorUtils";
+
+const useStatusPageFetch = (isCreate = false, url) => {
+ const [isLoading, setIsLoading] = useState(true);
+ const [networkError, setNetworkError] = useState(false);
+ const [statusPage, setStatusPage] = useState(undefined);
+ const [monitors, setMonitors] = useState(undefined);
+ const theme = useTheme();
+ const { getMonitorWithPercentage } = useMonitorUtils();
+ const fetchStatusPage = useCallback(async () => {
+ try {
+ const response = await networkService.getStatusPageByUrl({
+ url,
+ type: "uptime",
+ });
+ if (!response?.data?.data) return;
+ const { statusPage, monitors } = response.data.data;
+ setStatusPage(statusPage);
+
+ const monitorsWithPercentage = monitors.map((monitor) =>
+ getMonitorWithPercentage(monitor, theme)
+ );
+
+ setMonitors(monitorsWithPercentage);
+ } catch (error) {
+ // If there is a 404, status page is not found
+ if (error?.response?.status === 404) {
+ setStatusPage(undefined);
+ return;
+ }
+ createToast({ body: error.message });
+ setNetworkError(true);
+ } finally {
+ setIsLoading(false);
+ }
+ }, [theme, getMonitorWithPercentage, url]);
+
+ useEffect(() => {
+ if (isCreate === true) {
+ return;
+ }
+ fetchStatusPage();
+ }, [isCreate, fetchStatusPage]);
+
+ return [statusPage, monitors, isLoading, networkError, fetchStatusPage];
+};
+
+export { useStatusPageFetch };
diff --git a/client/src/Pages/StatusPage/Status/index.jsx b/client/src/Pages/StatusPage/Status/index.jsx
new file mode 100644
index 000000000..3997a8429
--- /dev/null
+++ b/client/src/Pages/StatusPage/Status/index.jsx
@@ -0,0 +1,167 @@
+// Components
+import { Typography, Stack } from "@mui/material";
+import GenericFallback from "../../../Components/GenericFallback";
+import AdminLink from "./Components/AdminLink";
+import ControlsHeader from "./Components/ControlsHeader";
+import SkeletonLayout from "./Components/Skeleton";
+import StatusBar from "./Components/StatusBar";
+import MonitorsList from "./Components/MonitorsList";
+import Dialog from "../../../Components/Dialog";
+import Breadcrumbs from "../../../Components/Breadcrumbs/index.jsx";
+
+// Utils
+import { useStatusPageFetch } from "./Hooks/useStatusPageFetch";
+import { useTheme } from "@emotion/react";
+import { useIsAdmin } from "../../../Hooks/useIsAdmin";
+import { useLocation } from "react-router-dom";
+import { useStatusPageDelete } from "./Hooks/useStatusPageDelete";
+import { useState } from "react";
+import { useParams } from "react-router-dom";
+import { useNavigate } from "react-router-dom";
+import { useTranslation } from "react-i18next";
+const PublicStatus = () => {
+ const { url } = useParams();
+
+ // Local state
+ const [isDeleteOpen, setIsDeleteOpen] = useState(false);
+ // Utils
+ const theme = useTheme();
+ const { t } = useTranslation();
+ const location = useLocation();
+ const navigate = useNavigate();
+
+ const [statusPage, monitors, isLoading, networkError, fetchStatusPage] =
+ useStatusPageFetch(false, url);
+ const [deleteStatusPage, isDeleting] = useStatusPageDelete(fetchStatusPage, url);
+
+ // Breadcrumbs
+ const crumbs = [
+ { name: t("statusBreadCrumbsStatusPages"), path: "/status" },
+ { name: t("statusBreadCrumbsDetails"), path: `/status/uptime/${statusPage?.url}` },
+ ];
+
+ // Setup
+ let sx = { paddingLeft: theme.spacing(20), paddingRight: theme.spacing(20) };
+ let link = undefined;
+ const isPublic = location.pathname.startsWith("/status/uptime/public");
+ // Public status page
+ if (isPublic) {
+ sx = {
+ paddingTop: theme.spacing(20),
+ paddingLeft: "20vw",
+ paddingRight: "20vw",
+ };
+ link = ;
+ }
+
+ // Loading
+ if (isLoading) {
+ return ;
+ }
+
+ // Error fetching data
+ if (networkError === true) {
+ return (
+
+
+ {t("networkError")}
+
+ {t("checkConnection")}
+
+ );
+ }
+
+ // Public status page fallback
+ if (!isLoading && typeof statusPage === "undefined" && isPublic) {
+ return (
+
+
+
+ {t("statusPageStatus")}
+
+ {t("statusPageStatusContactAdmin")}
+
+
+ );
+ }
+
+ // Finished loading, but status page is not public
+ if (!isLoading && isPublic && statusPage.isPublished === false) {
+ return (
+
+
+
+ {t("statusPageStatusNotPublic")}
+
+ {t("statusPageStatusContactAdmin")}
+
+
+ );
+ }
+
+ // Status page doesn't exist
+ if (!isLoading && typeof statusPage === "undefined") {
+ return (
+
+
+ {t("statusPageStatusNoPage")}
+
+ {t("statusPageStatusContactAdmin")}
+
+ );
+ }
+
+ return (
+
+ {!isPublic && }
+
+ {t("statusPageStatusServiceStatus")}
+
+
+ {link}
+ {
+ deleteStatusPage();
+ setIsDeleteOpen(false);
+ navigate("/status");
+ }}
+ onCancel={() => {
+ setIsDeleteOpen(false);
+ }}
+ open={isDeleteOpen}
+ confirmationButtonLabel={t("deleteStatusPageConfirm")}
+ description={t("deleteStatusPageDescription")}
+ isLoading={isDeleting || isLoading}
+ />
+
+ );
+};
+
+export default PublicStatus;
diff --git a/client/src/Pages/StatusPage/StatusPages/Components/StatusPagesTable/index.jsx b/client/src/Pages/StatusPage/StatusPages/Components/StatusPagesTable/index.jsx
new file mode 100644
index 000000000..a7b69ded0
--- /dev/null
+++ b/client/src/Pages/StatusPage/StatusPages/Components/StatusPagesTable/index.jsx
@@ -0,0 +1,109 @@
+import DataTable from "../../../../../Components/Table";
+import { useTheme } from "@emotion/react";
+import { useNavigate } from "react-router-dom";
+import { StatusLabel } from "../../../../../Components/Label";
+import ArrowOutwardIcon from "@mui/icons-material/ArrowOutward";
+import { Stack, Typography } from "@mui/material";
+import { useTranslation } from "react-i18next";
+const StatusPagesTable = ({ data }) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const headers = [
+ {
+ id: "name",
+ content: t("statusPageName"),
+ render: (row) => {
+ return row.companyName;
+ },
+ },
+ {
+ id: "url",
+ content: t("publicURL"),
+ onClick: (e, row) => {
+ if (row.isPublished) {
+ e.stopPropagation();
+ const url =
+ row.type === "distributed"
+ ? `/status/distributed/public/${row.url}`
+ : `/status/uptime/public/${row.url}`;
+ window.open(url, "_blank", "noopener,noreferrer");
+ }
+ },
+ render: (row) => {
+ const content = row.isPublished ? `/${row.url}` : "Unpublished";
+ return (
+
+ {content}
+ {row.isPublished && }
+
+ );
+ },
+ },
+ {
+ id: "type",
+ content: t("type"),
+ render: (row) => {
+ return row.type;
+ },
+ },
+ {
+ id: "status",
+ content: t("status"),
+ render: (row) => {
+ const status = row.isPublished ? "published" : "unpublished";
+ return (
+
+ );
+ },
+ },
+ ];
+
+ const handleRowClick = (statusPage) => {
+ if (statusPage.type === "distributed") {
+ navigate(`/status/distributed/${statusPage.url}`);
+ } else if (statusPage.type === "uptime") {
+ navigate(`/status/uptime/${statusPage.url}`);
+ }
+ };
+
+ return (
+ {
+ handleRowClick(row);
+ },
+ }}
+ headers={headers}
+ data={data}
+ />
+ );
+};
+
+export default StatusPagesTable;
diff --git a/client/src/Pages/StatusPage/StatusPages/Hooks/useStatusPagesFetch.jsx b/client/src/Pages/StatusPage/StatusPages/Hooks/useStatusPagesFetch.jsx
new file mode 100644
index 000000000..db7a33396
--- /dev/null
+++ b/client/src/Pages/StatusPage/StatusPages/Hooks/useStatusPagesFetch.jsx
@@ -0,0 +1,34 @@
+import { useState, useEffect } from "react";
+import { networkService } from "../../../../main";
+import { useSelector } from "react-redux";
+import { createToast } from "../../../../Utils/toastUtils";
+
+const useStatusPagesFetch = () => {
+ const { user } = useSelector((state) => state.auth);
+
+ const [isLoading, setIsLoading] = useState(true);
+ const [networkError, setNetworkError] = useState(false);
+ const [statusPages, setStatusPages] = useState(undefined);
+
+ useEffect(() => {
+ const fetchStatusPages = async () => {
+ try {
+ const res = await networkService.getStatusPagesByTeamId({
+ teamId: user.teamId,
+ });
+ setStatusPages(res?.data?.data);
+ } catch (error) {
+ setNetworkError(true);
+ createToast({
+ body: error.message,
+ });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+ fetchStatusPages();
+ }, [user]);
+ return [isLoading, networkError, statusPages];
+};
+
+export { useStatusPagesFetch };
diff --git a/client/src/Pages/StatusPage/StatusPages/index.jsx b/client/src/Pages/StatusPage/StatusPages/index.jsx
new file mode 100644
index 000000000..095023d76
--- /dev/null
+++ b/client/src/Pages/StatusPage/StatusPages/index.jsx
@@ -0,0 +1,71 @@
+// Components
+import { Stack, Typography } from "@mui/material";
+import Breadcrumbs from "../../../Components/Breadcrumbs";
+import Fallback from "../../../Components/Fallback";
+import MonitorCreateHeader from "../../../Components/MonitorCreateHeader";
+import GenericFallback from "../../../Components/GenericFallback";
+import StatusPagesTable from "./Components/StatusPagesTable";
+import SkeletonLayout from "../../../Components/Skeletons/FullPage";
+// Utils
+import { useTheme } from "@emotion/react";
+import { useTranslation } from "react-i18next";
+import { useStatusPagesFetch } from "./Hooks/useStatusPagesFetch";
+import { useIsAdmin } from "../../../Hooks/useIsAdmin";
+const BREADCRUMBS = [{ name: `Status Pages`, path: "" }];
+
+const StatusPages = () => {
+ // Utils
+ const theme = useTheme();
+ const { t } = useTranslation();
+ const isAdmin = useIsAdmin();
+ const [isLoading, networkError, statusPages] = useStatusPagesFetch();
+
+ if (isLoading) {
+ return ;
+ }
+
+ if (networkError === true) {
+ return (
+
+
+ {t("networkError")}
+
+ {t("checkConnection")}
+
+ );
+ }
+
+ if (!isLoading && typeof statusPages !== "undefined" && statusPages.length === 0) {
+ return (
+
+ );
+ }
+
+ return (
+
+
+
+
+
+ );
+};
+
+export default StatusPages;
diff --git a/client/src/Pages/Uptime/BulkImport/Upload.jsx b/client/src/Pages/Uptime/BulkImport/Upload.jsx
new file mode 100644
index 000000000..9f49b54bc
--- /dev/null
+++ b/client/src/Pages/Uptime/BulkImport/Upload.jsx
@@ -0,0 +1,73 @@
+import { useTheme } from "@emotion/react";
+import { useState, useRef } from "react";
+import { Button, Typography } from "@mui/material";
+import { useTranslation } from "react-i18next";
+import PropTypes from "prop-types";
+
+const UploadFile = ({ onFileSelect }) => { // Changed prop to onFileSelect
+ const theme = useTheme();
+ const [file, setFile] = useState();
+ const [error, setError] = useState("");
+ const inputRef = useRef();
+ const { t } = useTranslation();
+
+ const handleSelectFile = () => {
+ inputRef.current.click();
+ };
+
+ const handleFileChange = (e) => {
+ setError("");
+ const selectedFile = e.target.files[0];
+
+ // Basic file validation
+ if (!selectedFile) return;
+
+ if (!selectedFile.name.endsWith('.csv')) {
+ setError(t("bulkImport.invalidFileType"));
+ return;
+ }
+
+ setFile(selectedFile);
+ onFileSelect(selectedFile); // Pass the file directly to parent
+ };
+
+ return (
+
+
+
+ {file?.name || t("bulkImport.noFileSelected")}
+
+
+ {error}
+
+
+ {t("bulkImport.selectFile")}
+
+
+ );
+}
+
+
+UploadFile.prototype = {
+ onFileSelect: PropTypes.func.isRequired,
+};
+
+export default UploadFile;
\ No newline at end of file
diff --git a/client/src/Pages/Uptime/BulkImport/index.jsx b/client/src/Pages/Uptime/BulkImport/index.jsx
new file mode 100644
index 000000000..4d2e716f3
--- /dev/null
+++ b/client/src/Pages/Uptime/BulkImport/index.jsx
@@ -0,0 +1,112 @@
+// React, Redux, Router
+import { useTheme } from "@emotion/react";
+import { useState } from "react";
+// MUI
+import { Box, Stack, Typography, Button, Link } from "@mui/material";
+
+//Components
+import { createToast } from "../../../Utils/toastUtils";
+import Breadcrumbs from "../../../Components/Breadcrumbs";
+import ConfigBox from "../../../Components/ConfigBox";
+import UploadFile from "./Upload";
+import { useSelector } from "react-redux";
+import { useNavigate } from "react-router";
+import { Trans, useTranslation } from "react-i18next";
+import { useBulkMonitors } from "../../../Hooks/useBulkMonitors";
+
+const BulkImport = () => {
+ const theme = useTheme();
+ const { user } = useSelector((state) => state.auth);
+ const navigate = useNavigate();
+ const { t } = useTranslation();
+ const [selectedFile, setSelectedFile] = useState(null);
+
+ const crumbs = [
+ { name: t("uptime"), path: "/uptime" },
+ { name: t("bulkImport.title"), path: `/uptime/bulk-import` },
+ ];
+
+ const [createBulkMonitors, hookLoading] = useBulkMonitors();
+
+ const handleSubmit = async () => {
+ if (!selectedFile) {
+ createToast({ body: t("bulkImport.noFileSelected") });
+ return;
+ }
+
+ const [success, data, error] = await createBulkMonitors(selectedFile, user);
+
+ if (success) {
+ // You can use `data` here if needed
+ createToast({ body: t("bulkImport.uploadSuccess") });
+ navigate("/uptime");
+ } else {
+ createToast({ body: error || t("bulkImport.uploadFailed") });
+ }
+ };
+
+ return (
+
+
+
+
+ {t("bulkImport.title")}
+
+
+
+ {t("bulkImport.selectFileTips")}
+
+
+ ),
+ sample: (
+
+ ),
+ }}
+ />
+
+
+
+
+ setSelectedFile(file)} />
+
+
+
+
+
+ {t("submit")}
+
+
+
+
+ );
+};
+
+export default BulkImport;
diff --git a/Client/src/Pages/Uptime/Configure/index.css b/client/src/Pages/Uptime/Configure/index.css
similarity index 100%
rename from Client/src/Pages/Uptime/Configure/index.css
rename to client/src/Pages/Uptime/Configure/index.css
diff --git a/Client/src/Pages/Uptime/Configure/index.jsx b/client/src/Pages/Uptime/Configure/index.jsx
similarity index 67%
rename from Client/src/Pages/Uptime/Configure/index.jsx
rename to client/src/Pages/Uptime/Configure/index.jsx
index bdb90891b..5afbc4a27 100644
--- a/Client/src/Pages/Uptime/Configure/index.jsx
+++ b/client/src/Pages/Uptime/Configure/index.jsx
@@ -2,10 +2,19 @@ import { useNavigate, useParams } from "react-router";
import { useTheme } from "@emotion/react";
import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react";
-import { Box, Stack, Tooltip, Typography } from "@mui/material";
+import {
+ Box,
+ Stack,
+ Tooltip,
+ Typography,
+ Button,
+ FormControlLabel,
+ Switch,
+} from "@mui/material";
import { monitorValidation } from "../../../Validation/validation";
import { createToast } from "../../../Utils/toastUtils";
import { logger } from "../../../Utils/Logger";
+import { useTranslation } from "react-i18next";
import ConfigBox from "../../../Components/ConfigBox";
import {
updateUptimeMonitor,
@@ -22,9 +31,9 @@ import Checkbox from "../../../Components/Inputs/Checkbox";
import Breadcrumbs from "../../../Components/Breadcrumbs";
import PulseDot from "../../../Components/Animated/PulseDot";
import SkeletonLayout from "./skeleton";
-import LoadingButton from "@mui/lab/LoadingButton";
import "./index.css";
import Dialog from "../../../Components/Dialog";
+import NotificationIntegrationModal from "../../../Components/NotificationIntegrationModal/Components/NotificationIntegrationModal";
/**
* Parses a URL string and returns a URL object.
@@ -49,7 +58,7 @@ const Configure = () => {
const navigate = useNavigate();
const theme = useTheme();
const dispatch = useDispatch();
- const { user, authToken } = useSelector((state) => state.auth);
+ const { user } = useSelector((state) => state.auth);
const { isLoading } = useSelector((state) => state.uptimeMonitors);
const [monitor, setMonitor] = useState({});
const [errors, setErrors] = useState({});
@@ -62,10 +71,22 @@ const Configure = () => {
"notify-email-default": "notification-email",
};
+ const matchMethodOptions = [
+ { _id: "equal", name: "Equal" },
+ { _id: "include", name: "Include" },
+ { _id: "regex", name: "Regex" },
+ ];
+
+ const expectedValuePlaceholders = {
+ regex: "^(success|ok)$",
+ equal: "success",
+ include: "ok",
+ };
+
useEffect(() => {
const fetchMonitor = async () => {
try {
- const action = await dispatch(getUptimeMonitorById({ authToken, monitorId }));
+ const action = await dispatch(getUptimeMonitorById({ monitorId }));
if (getUptimeMonitorById.fulfilled.match(action)) {
const monitor = action.payload.data;
@@ -79,10 +100,10 @@ const Configure = () => {
}
};
fetchMonitor();
- }, [monitorId, authToken, navigate]);
+ }, [monitorId, navigate]);
const handleChange = (event, name) => {
- let { value, id } = event.target;
+ let { checked, value, id } = event.target;
if (!name) name = idMap[id];
if (name.includes("notification-")) {
@@ -114,6 +135,9 @@ const Configure = () => {
if (name === "interval") {
value = value * MS_PER_MINUTE;
}
+ if (name === "ignoreTlsErrors") {
+ value = checked;
+ }
setMonitor((prev) => ({
...prev,
[name]: value,
@@ -136,7 +160,7 @@ const Configure = () => {
const handlePause = async () => {
try {
- const action = await dispatch(pauseUptimeMonitor({ authToken, monitorId }));
+ const action = await dispatch(pauseUptimeMonitor({ monitorId }));
if (pauseUptimeMonitor.fulfilled.match(action)) {
const monitor = action.payload.data;
setMonitor(monitor);
@@ -153,7 +177,7 @@ const Configure = () => {
const handleSubmit = async (event) => {
event.preventDefault();
- const action = await dispatch(updateUptimeMonitor({ authToken, monitor: monitor }));
+ const action = await dispatch(updateUptimeMonitor({ monitor: monitor }));
if (action.meta.requestStatus === "fulfilled") {
createToast({ body: "Monitor updated successfully!" });
} else {
@@ -164,7 +188,7 @@ const Configure = () => {
const [isOpen, setIsOpen] = useState(false);
const handleRemove = async (event) => {
event.preventDefault();
- const action = await dispatch(deleteUptimeMonitor({ authToken, monitor }));
+ const action = await dispatch(deleteUptimeMonitor({ monitor }));
if (action.meta.requestStatus === "fulfilled") {
navigate("/uptime");
} else {
@@ -184,6 +208,17 @@ const Configure = () => {
const parsedUrl = parseUrl(monitor?.url);
const protocol = parsedUrl?.protocol?.replace(":", "") || "";
+ // Notification modal state
+ const [isNotificationModalOpen, setIsNotificationModalOpen] = useState(false);
+
+ const handleOpenNotificationModal = () => {
+ setIsNotificationModalOpen(true);
+ };
+
+ const handleClosenNotificationModal = () => {
+ setIsNotificationModalOpen(false);
+ };
+
const statusColor = {
true: theme.palette.success.main,
false: theme.palette.error.main,
@@ -196,6 +231,8 @@ const Configure = () => {
undefined: "Pending...",
};
+ const { t } = useTranslation();
+
return (
{
},
}}
>
- Editing...
+ {t("editing")}
@@ -292,7 +329,7 @@ const Configure = () => {
ml: "auto",
}}
>
- {
{monitor?.isActive ? (
<>
- Pause
+ {t("pause")}
>
) : (
<>
- Resume
+ {t("resume")}
>
)}
-
-
+ setIsOpen(true)}
>
- Remove
-
+ {t("remove")}
+
- General settings
+ {t("settingsGeneralSettings")}
- Here you can select the URL of the host, together with the type of
- monitor.
+ {t("distributedUptimeCreateSelectURL")}
}
+ startAdornment={
+ monitor?.type === "http" && (
+
+ )
+ }
id="monitor-url"
- label="URL to monitor"
+ label={t("urlMonitor")}
placeholder="google.com"
value={parsedUrl?.host || monitor?.url || ""}
disabled={true}
/>
+ handleChange(event, "port")}
+ error={errors["port"] ? true : false}
+ helperText={errors["port"]}
+ hidden={monitor.type !== "port"}
+ />
{
- Incident notifications
+
+ {t("distributedUptimeCreateIncidentNotification")}
+
- When there is an incident, notify users.
+ {t("distributedUptimeCreateIncidentDescription")}
- When there is a new incident,
+ {t("whenNewIncident")}
{/* {Leaving components commented for future funtionality implimentation} */}
{/* {
value={user?.email}
onChange={(event) => handleChange(event)}
/>
+
+
+ {t("notifications.integrationButton")}
+
+
{/* {
- Advanced settings
+ {t("ignoreTLSError")}
+ {t("ignoreTLSErrorDescription")}
+
+
+ handleChange(event, "ignoreTlsErrors")}
+ sx={{ mr: theme.spacing(2) }}
+ />
+ }
+ label={t("tlsErrorIgnored")}
+ />
+
+
+
+
+
+ {t("distributedUptimeCreateAdvancedSettings")}
+
handleChange(event, "interval")}
items={frequencies}
/>
+ {monitor.type === "http" && (
+ <>
+ handleChange(event, "matchMethod")}
+ items={matchMethodOptions}
+ />
+
+ handleChange(event, "expectedValue")}
+ error={errors["expectedValue"] ? true : false}
+ helperText={errors["expectedValue"]}
+ />
+
+ {t("uptimeCreate")}
+
+
+
+ handleChange(event, "jsonPath")}
+ error={errors["jsonPath"] ? true : false}
+ helperText={errors["jsonPath"]}
+ />
+
+ {t("uptimeCreateJsonPath")}
+
+ jmespath.org
+
+ {t("uptimeCreateJsonPathQuery")}
+
+
+ >
+ )}
{
justifyContent="flex-end"
mt="auto"
>
-
- Save
-
+ {t("settingsSave")}
+
>
@@ -467,6 +613,13 @@ const Configure = () => {
onConfirm={handleRemove}
isLoading={isLoading}
/>
+
+
);
};
diff --git a/Client/src/Pages/Uptime/Configure/skeleton.jsx b/client/src/Pages/Uptime/Configure/skeleton.jsx
similarity index 100%
rename from Client/src/Pages/Uptime/Configure/skeleton.jsx
rename to client/src/Pages/Uptime/Configure/skeleton.jsx
diff --git a/Client/src/Pages/Status/index.css b/client/src/Pages/Uptime/Create/index.css
similarity index 100%
rename from Client/src/Pages/Status/index.css
rename to client/src/Pages/Uptime/Create/index.css
diff --git a/Client/src/Pages/Uptime/CreateUptime/index.jsx b/client/src/Pages/Uptime/Create/index.jsx
similarity index 63%
rename from Client/src/Pages/Uptime/CreateUptime/index.jsx
rename to client/src/Pages/Uptime/Create/index.jsx
index 762d8e764..f73590c91 100644
--- a/Client/src/Pages/Uptime/CreateUptime/index.jsx
+++ b/client/src/Pages/Uptime/Create/index.jsx
@@ -4,16 +4,17 @@ import { useNavigate, useParams } from "react-router-dom";
import { useEffect } from "react";
import { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
+import { useTranslation } from "react-i18next";
// Utility and Network
import { checkEndpointResolution } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
import { monitorValidation } from "../../../Validation/validation";
import { getUptimeMonitorById } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
import { createUptimeMonitor } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
-
// MUI
import { Box, Stack, Typography, Button, ButtonGroup } from "@mui/material";
-import LoadingButton from "@mui/lab/LoadingButton";
+import Switch from "@mui/material/Switch";
+import FormControlLabel from "@mui/material/FormControlLabel";
//Components
import Breadcrumbs from "../../../Components/Breadcrumbs";
@@ -24,6 +25,7 @@ import Radio from "../../../Components/Inputs/Radio";
import Checkbox from "../../../Components/Inputs/Checkbox";
import Select from "../../../Components/Inputs/Select";
import ConfigBox from "../../../Components/ConfigBox";
+import NotificationIntegrationModal from "../../../Components/NotificationIntegrationModal/Components/NotificationIntegrationModal";
const CreateMonitor = () => {
const MS_PER_MINUTE = 60000;
const SELECT_VALUES = [
@@ -34,6 +36,18 @@ const CreateMonitor = () => {
{ _id: 5, name: "5 minutes" },
];
+ const matchMethodOptions = [
+ { _id: "equal", name: "Equal" },
+ { _id: "include", name: "Include" },
+ { _id: "regex", name: "Regex" },
+ ];
+
+ const expectedValuePlaceholders = {
+ regex: "^(success|ok)$",
+ equal: "success",
+ include: "ok",
+ };
+
const monitorTypeMaps = {
http: {
label: "URL to monitor",
@@ -57,7 +71,7 @@ const CreateMonitor = () => {
},
};
- const { user, authToken } = useSelector((state) => state.auth);
+ const { user } = useSelector((state) => state.auth);
const { isLoading } = useSelector((state) => state.uptimeMonitors);
const dispatch = useDispatch();
const navigate = useNavigate();
@@ -69,12 +83,18 @@ const CreateMonitor = () => {
];
// State
+ const [isNotificationModalOpen, setIsNotificationModalOpen] = useState(false);
+
+ const handleOpenNotificationModal = () => {
+ setIsNotificationModalOpen(true);
+ };
const [errors, setErrors] = useState({});
const [https, setHttps] = useState(true);
const [monitor, setMonitor] = useState({
url: "",
name: "",
type: "http",
+ ignoreTlsErrors: false,
notifications: [],
interval: 1,
});
@@ -88,11 +108,18 @@ const CreateMonitor = () => {
? `http${https ? "s" : ""}://` + monitor.url
: monitor.url,
port: monitor.type === "port" ? monitor.port : undefined,
- name: monitor.name === "" ? monitor.url : monitor.name,
+ name: monitor.name || monitor.url.substring(0, 50),
type: monitor.type,
+ ignoreTlsErrors: monitor.ignoreTlsErrors,
interval: monitor.interval * MS_PER_MINUTE,
};
+ if (monitor.type === "http") {
+ form.expectedValue = monitor.expectedValue;
+ form.jsonPath = monitor.jsonPath;
+ form.matchMethod = monitor.matchMethod;
+ }
+
const { error } = monitorValidation.validate(form, {
abortEarly: false,
});
@@ -107,27 +134,14 @@ const CreateMonitor = () => {
return;
}
- if (monitor.type === "http") {
- // const checkEndpointAction = await dispatch(
- // checkEndpointResolution({ authToken, monitorURL: form.url })
- // );
- // if (checkEndpointAction.meta.requestStatus === "rejected") {
- // createToast({
- // body: "The endpoint you entered doesn't resolve. Check the URL again.",
- // });
- // setErrors({ url: "The entered URL is not reachable." });
- // return;
- // }
- }
-
form = {
...form,
- description: form.name,
+ description: monitor.name || monitor.url,
teamId: user.teamId,
userId: user._id,
notifications: monitor.notifications,
};
- const action = await dispatch(createUptimeMonitor({ authToken, monitor: form }));
+ const action = await dispatch(createUptimeMonitor({ monitor: form }));
if (action.meta.requestStatus === "fulfilled") {
createToast({ body: "Monitor created successfully!" });
navigate("/uptime");
@@ -137,18 +151,26 @@ const CreateMonitor = () => {
};
const handleChange = (event, formName) => {
- const { value } = event.target;
- setMonitor({
+ const { type, checked, value } = event.target;
+
+ const newVal = type === "checkbox" ? checked : value;
+
+ const newMonitor = {
...monitor,
- [formName]: value,
- });
+ [formName]: newVal,
+ };
+ if (formName === "type") {
+ newMonitor.url = "";
+ }
+ setMonitor(newMonitor);
const { error } = monitorValidation.validate(
- { [formName]: value },
+ { type: monitor.type, [formName]: newVal },
{ abortEarly: false }
);
setErrors((prev) => ({
...prev,
+ url: undefined,
...(error ? { [formName]: error.details[0].message } : { [formName]: undefined }),
}));
};
@@ -182,7 +204,7 @@ const CreateMonitor = () => {
useEffect(() => {
const fetchMonitor = async () => {
if (monitorId) {
- const action = await dispatch(getUptimeMonitorById({ authToken, monitorId }));
+ const action = await dispatch(getUptimeMonitorById({ monitorId }));
if (action.payload.success) {
const data = action.payload.data;
@@ -205,7 +227,9 @@ const CreateMonitor = () => {
}
};
fetchMonitor();
- }, [monitorId, authToken, dispatch, navigate]);
+ }, [monitorId, dispatch, navigate]);
+
+ const { t } = useTranslation();
return (
@@ -224,7 +248,7 @@ const CreateMonitor = () => {
component="span"
fontSize="inherit"
>
- Create your{" "}
+ {t("createYour")}{" "}
{
fontSize="inherit"
fontWeight="inherit"
>
- monitor
+ {t("monitor")}
-
- General settings
+ {t("distributedUptimeCreateChecks")}
- Here you can select the URL of the host, together with the type of monitor.
-
-
-
- : null
- }
- label={monitorTypeMaps[monitor.type].label || "URL to monitor"}
- https={https}
- placeholder={monitorTypeMaps[monitor.type].placeholder || ""}
- value={monitor.url}
- onChange={(event) => handleChange(event, "url")}
- error={errors["url"] ? true : false}
- helperText={errors["url"]}
- />
- handleChange(event, "port")}
- error={errors["port"] ? true : false}
- helperText={errors["port"]}
- hidden={monitor.type !== "port"}
- />
- handleChange(event, "name")}
- error={errors["name"] ? true : false}
- helperText={errors["name"]}
- />
-
-
-
-
- Checks to perform
-
- You can always add or remove checks after adding your site.
+ {t("distributedUptimeCreateChecksDescription")}
{
filled={https.toString()}
onClick={() => setHttps(true)}
>
- HTTPS
+ {t("https")}
setHttps(false)}
>
- HTTP
+ {t("http")}
) : (
@@ -323,8 +300,8 @@ const CreateMonitor = () => {
{
/>
{
/>
{
- Incident notifications
+ {t("settingsGeneralSettings")}
+ {t("uptimeCreateSelectURL")}
+
+
+ : null
+ }
+ label={monitorTypeMaps[monitor.type].label || "URL to monitor"}
+ https={https}
+ placeholder={monitorTypeMaps[monitor.type].placeholder || ""}
+ value={monitor.url}
+ onChange={(event) => handleChange(event, "url")}
+ error={errors["url"] ? true : false}
+ helperText={errors["url"]}
+ />
+ handleChange(event, "port")}
+ error={errors["port"] ? true : false}
+ helperText={errors["port"]}
+ hidden={monitor.type !== "port"}
+ />
+ handleChange(event, "name")}
+ error={errors["name"] ? true : false}
+ helperText={errors["name"]}
+ />
+
+
+
+
+
+ {t("distributedUptimeCreateIncidentNotification")}
+
- When there is an incident, notify users.
+ {t("distributedUptimeCreateIncidentDescription")}
@@ -380,11 +403,43 @@ const CreateMonitor = () => {
value={user?.email}
onChange={(event) => handleNotifications(event, "email")}
/>
+
+
+
+ {t("notifications.integrationButton")}
+
+
- Advanced settings
+ {t("ignoreTLSError")}
+ {t("ignoreTLSErrorDescription")}
+
+
+ handleChange(event, "ignoreTlsErrors")}
+ sx={{ mr: theme.spacing(2) }}
+ />
+ }
+ label={t("tlsErrorIgnored")}
+ />
+
+
+
+
+
+ {t("distributedUptimeCreateAdvancedSettings")}
+
{
onChange={(event) => handleChange(event, "interval")}
items={SELECT_VALUES}
/>
+ {monitor.type === "http" && (
+ <>
+ handleChange(event, "matchMethod")}
+ items={matchMethodOptions}
+ />
+
+ handleChange(event, "expectedValue")}
+ error={errors["expectedValue"] ? true : false}
+ helperText={errors["expectedValue"]}
+ />
+
+ {t("uptimeCreate")}
+
+
+
+ handleChange(event, "jsonPath")}
+ error={errors["jsonPath"] ? true : false}
+ helperText={errors["jsonPath"]}
+ />
+
+ {t("uptimeCreateJsonPath")}
+
+ jmespath.org
+
+ {t("uptimeCreateJsonPathQuery")}
+
+
+ >
+ )}
- value === undefined)}
loading={isLoading}
>
- Create monitor
-
+ {t("createMonitor")}
+
+
+ setIsNotificationModalOpen(false)}
+ monitor={monitor}
+ setMonitor={setMonitor}
+ />
);
};
diff --git a/client/src/Pages/Uptime/Details/Components/ChartBoxes/index.jsx b/client/src/Pages/Uptime/Details/Components/ChartBoxes/index.jsx
new file mode 100644
index 000000000..068211f5b
--- /dev/null
+++ b/client/src/Pages/Uptime/Details/Components/ChartBoxes/index.jsx
@@ -0,0 +1,147 @@
+// Components
+import { Stack, Typography, Box } from "@mui/material";
+import ChartBox from "../../../../../Components/Charts/ChartBox";
+import UptimeIcon from "../../../../../assets/icons/uptime-icon.svg?react";
+import IncidentsIcon from "../../../../../assets/icons/incidents.svg?react";
+import AverageResponseIcon from "../../../../../assets/icons/average-response-icon.svg?react";
+import UpBarChart from "../Charts/UpBarChart";
+import DownBarChart from "../Charts/DownBarChart";
+import ResponseGaugeChart from "../Charts/ResponseGaugeChart";
+import SkeletonLayout from "./skeleton";
+// Utils
+import { formatDateWithTz } from "../../../../../Utils/timeUtils";
+import PropTypes from "prop-types";
+import { useTheme } from "@emotion/react";
+import { useState } from "react";
+
+const ChartBoxes = ({
+ isLoading = false,
+ monitorData,
+ dateRange,
+ uiTimezone,
+ dateFormat,
+}) => {
+ // Local state
+ const [hoveredUptimeData, setHoveredUptimeData] = useState(null);
+ const [hoveredIncidentsData, setHoveredIncidentsData] = useState(null);
+ const theme = useTheme();
+ if (isLoading) {
+ return ;
+ }
+
+ const noIncidentsMessage = "Great. No Incidents, yet!";
+
+ return (
+
+ }
+ header="Uptime"
+ isEmpty={monitorData?.groupedUpChecks?.length === 0}
+ >
+
+
+ Total Checks
+
+ {hoveredUptimeData !== null
+ ? hoveredUptimeData.totalChecks
+ : (monitorData?.groupedUpChecks?.reduce((count, checkGroup) => {
+ return count + checkGroup.totalChecks;
+ }, 0) ?? 0)}
+
+ {hoveredUptimeData !== null && hoveredUptimeData.time !== null && (
+
+ {formatDateWithTz(hoveredUptimeData._id, dateFormat, uiTimezone)}
+
+ )}
+
+
+
+ {hoveredUptimeData !== null ? "Avg Response Time" : "Uptime Percentage"}
+
+
+ {hoveredUptimeData !== null
+ ? Math.floor(hoveredUptimeData?.originalAvgResponseTime ?? 0)
+ : Math.floor(monitorData?.groupedUptimePercentage ?? 0 * 100)}
+
+ {hoveredUptimeData !== null ? " ms" : " %"}
+
+
+
+
+
+
+ }
+ header="Incidents"
+ noDataMessage={noIncidentsMessage}
+ isEmpty={monitorData?.groupedDownChecks?.length === 0}
+ >
+
+
+
+ {hoveredIncidentsData !== null
+ ? hoveredIncidentsData.totalChecks
+ : (monitorData?.groupedDownChecks?.reduce((count, checkGroup) => {
+ return count + checkGroup.totalChecks;
+ }, 0) ?? 0)}
+
+ {hoveredIncidentsData !== null && hoveredIncidentsData.time !== null && (
+
+ {formatDateWithTz(hoveredIncidentsData._id, dateFormat, uiTimezone)}
+
+ )}
+
+
+
+
+ }
+ header="Average Response Time"
+ >
+
+
+
+ );
+};
+
+export default ChartBoxes;
+
+ChartBoxes.propTypes = {
+ isLoading: PropTypes.bool,
+ monitorData: PropTypes.object,
+ dateRange: PropTypes.string.isRequired,
+ uiTimezone: PropTypes.string.isRequired,
+ dateFormat: PropTypes.string.isRequired,
+ hoveredUptimeData: PropTypes.object,
+ setHoveredUptimeData: PropTypes.func,
+ hoveredIncidentsData: PropTypes.object,
+ setHoveredIncidentsData: PropTypes.func,
+};
diff --git a/client/src/Pages/Uptime/Details/Components/ChartBoxes/skeleton.jsx b/client/src/Pages/Uptime/Details/Components/ChartBoxes/skeleton.jsx
new file mode 100644
index 000000000..750b3b20a
--- /dev/null
+++ b/client/src/Pages/Uptime/Details/Components/ChartBoxes/skeleton.jsx
@@ -0,0 +1,30 @@
+import { Skeleton, Stack } from "@mui/material";
+import { useTheme } from "@emotion/react";
+
+const SkeletonLayout = () => {
+ const theme = useTheme();
+ return (
+
+
+
+
+
+ );
+};
+
+export default SkeletonLayout;
diff --git a/Client/src/Pages/Uptime/Details/Charts/CustomLabels.jsx b/client/src/Pages/Uptime/Details/Components/Charts/CustomLabels.jsx
similarity index 85%
rename from Client/src/Pages/Uptime/Details/Charts/CustomLabels.jsx
rename to client/src/Pages/Uptime/Details/Components/Charts/CustomLabels.jsx
index 10494830f..8df33953f 100644
--- a/Client/src/Pages/Uptime/Details/Charts/CustomLabels.jsx
+++ b/client/src/Pages/Uptime/Details/Components/Charts/CustomLabels.jsx
@@ -1,6 +1,6 @@
import PropTypes from "prop-types";
import { useSelector } from "react-redux";
-import { formatDateWithTz } from "../../../../Utils/timeUtils";
+import { formatDateWithTz } from "../../../../../Utils/timeUtils";
const CustomLabels = ({ x, width, height, firstDataPoint, lastDataPoint, type }) => {
const uiTimezone = useSelector((state) => state.ui.timezone);
@@ -34,8 +34,8 @@ CustomLabels.propTypes = {
x: PropTypes.number.isRequired,
width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
- firstDataPoint: PropTypes.object.isRequired,
- lastDataPoint: PropTypes.object.isRequired,
+ firstDataPoint: PropTypes.object,
+ lastDataPoint: PropTypes.object,
type: PropTypes.string.isRequired,
};
diff --git a/Client/src/Pages/Uptime/Details/Charts/DownBarChart.jsx b/client/src/Pages/Uptime/Details/Components/Charts/DownBarChart.jsx
similarity index 85%
rename from Client/src/Pages/Uptime/Details/Charts/DownBarChart.jsx
rename to client/src/Pages/Uptime/Details/Components/Charts/DownBarChart.jsx
index ae2adda0f..662abc831 100644
--- a/Client/src/Pages/Uptime/Details/Charts/DownBarChart.jsx
+++ b/client/src/Pages/Uptime/Details/Components/Charts/DownBarChart.jsx
@@ -4,7 +4,7 @@ import { ResponsiveContainer, BarChart, XAxis, Bar, Cell } from "recharts";
import PropTypes from "prop-types";
import CustomLabels from "./CustomLabels";
-const DownBarChart = memo(({ monitor, type, onBarHover }) => {
+const DownBarChart = memo(({ groupedDownChecks = [], type, onBarHover }) => {
const theme = useTheme();
const [chartHovered, setChartHovered] = useState(false);
@@ -19,7 +19,7 @@ const DownBarChart = memo(({ monitor, type, onBarHover }) => {
{
setChartHovered(true);
onBarHover({ time: null, totalChecks: 0 });
@@ -40,10 +40,8 @@ const DownBarChart = memo(({ monitor, type, onBarHover }) => {
y={0}
width="100%"
height="100%"
- firstDataPoint={monitor.groupedDownChecks?.[0] ?? {}}
- lastDataPoint={
- monitor.groupedDownChecks?.[monitor.groupedDownChecks.length - 1] ?? {}
- }
+ firstDataPoint={groupedDownChecks?.[0] ?? {}}
+ lastDataPoint={groupedDownChecks?.[groupedDownChecks?.length - 1] ?? {}}
type={type}
/>
}
@@ -53,7 +51,7 @@ const DownBarChart = memo(({ monitor, type, onBarHover }) => {
maxBarSize={7}
background={{ fill: "transparent" }}
>
- {monitor.groupedDownChecks.map((entry, index) => {
+ {groupedDownChecks?.map((entry, index) => {
return (
{
const theme = useTheme();
-
+ const { t } = useTranslation();
let max = 1000; // max ms
const data = [
@@ -17,13 +18,13 @@ const ResponseGaugeChart = ({ avgResponseTime }) => {
? {
category: "Excellent",
main: theme.palette.success.main,
- bg: theme.palette.success.contrastText,
+ bg: theme.palette.success.lowContrast,
}
: responseTime <= 500
? {
category: "Fair",
main: theme.palette.success.main,
- bg: theme.palette.success.contrastText,
+ bg: theme.palette.success.lowContrast,
}
: responseTime <= 600
? {
@@ -34,7 +35,7 @@ const ResponseGaugeChart = ({ avgResponseTime }) => {
: {
category: "Poor",
main: theme.palette.error.main,
- bg: theme.palette.error.contrastText,
+ bg: theme.palette.error.lowContrast,
};
return (
@@ -61,7 +62,7 @@ const ResponseGaugeChart = ({ avgResponseTime }) => {
textAnchor="start"
fontSize={11}
>
- low
+ {t("low")}
{
textAnchor="end"
fontSize={11}
>
- high
+ {t("high")}
{
{responseTime} ms
diff --git a/client/src/Pages/Uptime/Details/Components/Charts/ResponseTimeChart.jsx b/client/src/Pages/Uptime/Details/Components/Charts/ResponseTimeChart.jsx
new file mode 100644
index 000000000..e2d8dea80
--- /dev/null
+++ b/client/src/Pages/Uptime/Details/Components/Charts/ResponseTimeChart.jsx
@@ -0,0 +1,31 @@
+import ChartBox from "../../../../../Components/Charts/ChartBox";
+import MonitorDetailsAreaChart from "../../../../../Components/Charts/MonitorDetailsAreaChart";
+import ResponseTimeIcon from "../../../../../assets/icons/response-time-icon.svg?react";
+import SkeletonLayout from "./ResponseTimeChartSkeleton";
+import PropTypes from "prop-types";
+
+const ResponseTImeChart = ({ isLoading = false, groupedChecks = [], dateRange }) => {
+ if (isLoading) {
+ return ;
+ }
+
+ return (
+ }
+ header="Response Times"
+ >
+
+
+ );
+};
+
+ResponseTImeChart.propTypes = {
+ isLoading: PropTypes.bool,
+ groupedChecks: PropTypes.array,
+ dateRange: PropTypes.string,
+};
+
+export default ResponseTImeChart;
diff --git a/client/src/Pages/Uptime/Details/Components/Charts/ResponseTimeChartSkeleton.jsx b/client/src/Pages/Uptime/Details/Components/Charts/ResponseTimeChartSkeleton.jsx
new file mode 100644
index 000000000..a70757e36
--- /dev/null
+++ b/client/src/Pages/Uptime/Details/Components/Charts/ResponseTimeChartSkeleton.jsx
@@ -0,0 +1,12 @@
+import { Skeleton } from "@mui/material";
+const ResponseTimeChartSkeleton = () => {
+ return (
+
+ );
+};
+
+export default ResponseTimeChartSkeleton;
diff --git a/Client/src/Pages/Uptime/Details/Charts/UpBarChart.jsx b/client/src/Pages/Uptime/Details/Components/Charts/UpBarChart.jsx
similarity index 81%
rename from Client/src/Pages/Uptime/Details/Charts/UpBarChart.jsx
rename to client/src/Pages/Uptime/Details/Components/Charts/UpBarChart.jsx
index 223dc8eef..317147b74 100644
--- a/Client/src/Pages/Uptime/Details/Charts/UpBarChart.jsx
+++ b/client/src/Pages/Uptime/Details/Components/Charts/UpBarChart.jsx
@@ -14,7 +14,7 @@ const getThemeColor = (responseTime) => {
}
};
-const UpBarChart = memo(({ monitor, type, onBarHover }) => {
+const UpBarChart = memo(({ groupedUpChecks = [], type, onBarHover }) => {
const theme = useTheme();
const [chartHovered, setChartHovered] = useState(false);
const [hoveredBarIndex, setHoveredBarIndex] = useState(null);
@@ -28,10 +28,10 @@ const UpBarChart = memo(({ monitor, type, onBarHover }) => {
{
setChartHovered(true);
- onBarHover({ time: null, totalChecks: 0, avgResponseTime: 0 });
+ onBarHover({ time: null, totalChecks: 0, originalAvgResponseTime: 0 });
}}
onMouseLeave={() => {
setChartHovered(false);
@@ -49,8 +49,8 @@ const UpBarChart = memo(({ monitor, type, onBarHover }) => {
y={0}
width="100%"
height="100%"
- firstDataPoint={monitor.groupedUpChecks[0]}
- lastDataPoint={monitor.groupedUpChecks[monitor.groupedUpChecks.length - 1]}
+ firstDataPoint={groupedUpChecks?.[0]}
+ lastDataPoint={groupedUpChecks?.[groupedUpChecks?.length - 1]}
type={type}
/>
}
@@ -60,8 +60,8 @@ const UpBarChart = memo(({ monitor, type, onBarHover }) => {
maxBarSize={7}
background={{ fill: "transparent" }}
>
- {monitor.groupedUpChecks.map((entry, index) => {
- const themeColor = getThemeColor(entry.avgResponseTime);
+ {groupedUpChecks?.map((entry, index) => {
+ const themeColor = getThemeColor(entry.originalAvgResponseTime);
return (
{
hoveredBarIndex === index
? theme.palette[themeColor].main
: chartHovered
- ? theme.palette[themeColor].light // CAIO_REVIEW
+ ? theme.palette[themeColor].light
: theme.palette[themeColor].main
}
onMouseEnter={() => {
diff --git a/client/src/Pages/Uptime/Details/Components/ResponseTable/index.jsx b/client/src/Pages/Uptime/Details/Components/ResponseTable/index.jsx
new file mode 100644
index 000000000..4d482aa07
--- /dev/null
+++ b/client/src/Pages/Uptime/Details/Components/ResponseTable/index.jsx
@@ -0,0 +1,91 @@
+import ChartBox from "../../../../../Components/Charts/ChartBox";
+import PropTypes from "prop-types";
+import HistoryIcon from "../../../../../assets/icons/history-icon.svg?react";
+import Table from "../../../../../Components/Table";
+import TablePagination from "../../../../../Components/Table/TablePagination";
+import { StatusLabel } from "../../../../../Components/Label";
+import { useTranslation } from "react-i18next";
+import { formatDateWithTz } from "../../../../../Utils/timeUtils";
+import SkeletonLayout from "./skeleton";
+const ResponseTable = ({
+ isLoading = false,
+ checks = [],
+ checksCount,
+ uiTimezone,
+ page,
+ setPage,
+ rowsPerPage,
+ setRowsPerPage,
+}) => {
+ const { t } = useTranslation();
+ if (isLoading) {
+ return ;
+ }
+
+ const headers = [
+ {
+ id: "status",
+ content: t("status"),
+ render: (row) => {
+ const status = row.status === true ? "up" : "down";
+
+ return (
+
+ );
+ },
+ },
+ {
+ id: "date",
+ content: t("date&Time"),
+ render: (row) =>
+ formatDateWithTz(row.createdAt, "ddd, MMMM D, YYYY, HH:mm A", uiTimezone),
+ },
+ {
+ id: "statusCode",
+ content: t("statusCode"),
+ render: (row) => (row.statusCode ? row.statusCode : "N/A"),
+ },
+ {
+ id: "message",
+ content: t("message"),
+ render: (row) => row.message,
+ },
+ ];
+
+ return (
+ }
+ header="Response Times"
+ height="100%"
+ >
+
+
+
+ );
+};
+
+ResponseTable.propTypes = {
+ isLoading: PropTypes.bool,
+ checks: PropTypes.array,
+ checksCount: PropTypes.number,
+ uiTimezone: PropTypes.string.isRequired,
+ page: PropTypes.number.isRequired,
+ setPage: PropTypes.func.isRequired,
+ rowsPerPage: PropTypes.number.isRequired,
+ setRowsPerPage: PropTypes.func.isRequired,
+};
+
+export default ResponseTable;
diff --git a/client/src/Pages/Uptime/Details/Components/ResponseTable/skeleton.jsx b/client/src/Pages/Uptime/Details/Components/ResponseTable/skeleton.jsx
new file mode 100644
index 000000000..2665ffaf1
--- /dev/null
+++ b/client/src/Pages/Uptime/Details/Components/ResponseTable/skeleton.jsx
@@ -0,0 +1,13 @@
+import { Skeleton } from "@mui/material";
+
+const SkeletonLayout = () => {
+ return (
+
+ );
+};
+
+export default SkeletonLayout;
diff --git a/client/src/Pages/Uptime/Details/Components/UptimeStatusBoxes/index.jsx b/client/src/Pages/Uptime/Details/Components/UptimeStatusBoxes/index.jsx
new file mode 100644
index 000000000..ddc7e223b
--- /dev/null
+++ b/client/src/Pages/Uptime/Details/Components/UptimeStatusBoxes/index.jsx
@@ -0,0 +1,89 @@
+import StatusBoxes from "../../../../../Components/StatusBoxes";
+import StatBox from "../../../../../Components/StatBox";
+
+import PropTypes from "prop-types";
+import { getHumanReadableDuration } from "../../../../../Utils/timeUtils";
+import { useTheme } from "@mui/material/styles";
+import { Typography } from "@mui/material";
+import useUtils from "../../../Monitors/Hooks/useUtils";
+
+const UptimeStatusBoxes = ({
+ isLoading = false,
+ monitor,
+ monitorStats,
+ certificateExpiry,
+}) => {
+ const theme = useTheme();
+ const { determineState } = useUtils();
+
+ // Determine time since last failure
+ const timeOfLastFailure = monitorStats?.timeOfLastFailure;
+ const timeSinceLastFailure = timeOfLastFailure > 0 ? Date.now() - timeOfLastFailure : 0;
+
+ // Determine time since last check
+ const timeOfLastCheck = monitorStats?.lastCheckTimestamp;
+ const timeSinceLastCheck = Date.now() - timeOfLastCheck;
+
+ const { time: streakTime, units: streakUnits } =
+ getHumanReadableDuration(timeSinceLastFailure);
+
+ const { time: lastCheckTime, units: lastCheckUnits } =
+ getHumanReadableDuration(timeSinceLastCheck);
+ return (
+
+
+ {streakTime}
+ {streakUnits}
+ >
+ }
+ />
+
+ {lastCheckTime}
+ {lastCheckUnits}
+ {"ago"}
+ >
+ }
+ />
+
+ {monitorStats?.lastResponseTime}
+ {"ms"}
+ >
+ }
+ />
+ {monitor?.type === "http" && (
+
+ {certificateExpiry}
+
+ }
+ />
+ )}
+
+ );
+};
+
+UptimeStatusBoxes.propTypes = {
+ shouldRender: PropTypes.bool,
+ monitor: PropTypes.object,
+ monitorStats: PropTypes.object,
+ certificateExpiry: PropTypes.string,
+};
+
+export default UptimeStatusBoxes;
diff --git a/client/src/Pages/Uptime/Details/Hooks/useCertificateFetch.jsx b/client/src/Pages/Uptime/Details/Hooks/useCertificateFetch.jsx
new file mode 100644
index 000000000..ad0db6f70
--- /dev/null
+++ b/client/src/Pages/Uptime/Details/Hooks/useCertificateFetch.jsx
@@ -0,0 +1,44 @@
+import { logger } from "../../../../Utils/Logger";
+import { useEffect, useState } from "react";
+import { networkService } from "../../../../main";
+import { formatDateWithTz } from "../../../../Utils/timeUtils";
+
+const useCertificateFetch = ({
+ monitor,
+ monitorId,
+ certificateDateFormat,
+ uiTimezone,
+}) => {
+ const [certificateExpiry, setCertificateExpiry] = useState(undefined);
+ const [isLoading, setIsLoading] = useState(false);
+
+ useEffect(() => {
+ const fetchCertificate = async () => {
+ if (monitor?.type !== "http") {
+ return;
+ }
+
+ try {
+ setIsLoading(true);
+ const res = await networkService.getCertificateExpiry({
+ monitorId: monitorId,
+ });
+ if (res?.data?.data?.certificateDate) {
+ const date = res.data.data.certificateDate;
+ setCertificateExpiry(
+ formatDateWithTz(date, certificateDateFormat, uiTimezone) ?? "N/A"
+ );
+ }
+ } catch (error) {
+ setCertificateExpiry("N/A");
+ logger.error(error);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+ fetchCertificate();
+ }, [monitorId, certificateDateFormat, uiTimezone, monitor]);
+ return [certificateExpiry, isLoading];
+};
+
+export default useCertificateFetch;
diff --git a/client/src/Pages/Uptime/Details/Hooks/useChecksFetch.jsx b/client/src/Pages/Uptime/Details/Hooks/useChecksFetch.jsx
new file mode 100644
index 000000000..586cc8359
--- /dev/null
+++ b/client/src/Pages/Uptime/Details/Hooks/useChecksFetch.jsx
@@ -0,0 +1,50 @@
+import { useState } from "react";
+import { useEffect } from "react";
+import { networkService } from "../../../../main";
+import { createToast } from "../../../../Utils/toastUtils";
+export const useChecksFetch = ({
+ monitorId,
+ monitorType,
+ dateRange,
+ page,
+ rowsPerPage,
+}) => {
+ const [checks, setChecks] = useState(undefined);
+ const [checksCount, setChecksCount] = useState(undefined);
+ const [isLoading, setIsLoading] = useState(false);
+ const [networkError, setNetworkError] = useState(false);
+
+ useEffect(() => {
+ if (!monitorType) {
+ return;
+ }
+
+ const fetchChecks = async () => {
+ try {
+ setIsLoading(true);
+ const res = await networkService.getChecksByMonitor({
+ monitorId: monitorId,
+ type: monitorType,
+ sortOrder: "desc",
+ limit: null,
+ dateRange: dateRange,
+ filter: null,
+ page: page,
+ rowsPerPage: rowsPerPage,
+ });
+ setChecks(res.data.data.checks);
+ setChecksCount(res.data.data.checksCount);
+ } catch (error) {
+ setNetworkError(true);
+ createToast({ body: error.message });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+ fetchChecks();
+ }, [monitorId, monitorType, dateRange, page, rowsPerPage]);
+
+ return [checks, checksCount, isLoading, networkError];
+};
+
+export default useChecksFetch;
diff --git a/client/src/Pages/Uptime/Details/Hooks/useMonitorFetch.jsx b/client/src/Pages/Uptime/Details/Hooks/useMonitorFetch.jsx
new file mode 100644
index 000000000..9491e7cc3
--- /dev/null
+++ b/client/src/Pages/Uptime/Details/Hooks/useMonitorFetch.jsx
@@ -0,0 +1,33 @@
+import { useEffect, useState } from "react";
+import { networkService } from "../../../../main";
+import { useNavigate } from "react-router-dom";
+import { createToast } from "../../../../Utils/toastUtils";
+
+export const useMonitorFetch = ({ monitorId, dateRange }) => {
+ const [networkError, setNetworkError] = useState(false);
+ const [isLoading, setIsLoading] = useState(true);
+ const [monitor, setMonitor] = useState(undefined);
+ const navigate = useNavigate();
+
+ useEffect(() => {
+ const fetchMonitors = async () => {
+ try {
+ const res = await networkService.getUptimeDetailsById({
+ monitorId: monitorId,
+ dateRange: dateRange,
+ normalize: true,
+ });
+ setMonitor(res?.data?.data ?? {});
+ } catch (error) {
+ setNetworkError(true);
+ createToast({ body: error.message });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+ fetchMonitors();
+ }, [dateRange, monitorId, navigate]);
+ return [monitor, isLoading, networkError];
+};
+
+export default useMonitorFetch;
diff --git a/client/src/Pages/Uptime/Details/index.jsx b/client/src/Pages/Uptime/Details/index.jsx
new file mode 100644
index 000000000..be1ccbcd2
--- /dev/null
+++ b/client/src/Pages/Uptime/Details/index.jsx
@@ -0,0 +1,164 @@
+// Components
+import Breadcrumbs from "../../../Components/Breadcrumbs";
+import MonitorStatusHeader from "../../../Components/MonitorStatusHeader";
+import MonitorTimeFrameHeader from "../../../Components/MonitorTimeFrameHeader";
+import ChartBoxes from "./Components/ChartBoxes";
+import ResponseTimeChart from "./Components/Charts/ResponseTimeChart";
+import ResponseTable from "./Components/ResponseTable";
+import UptimeStatusBoxes from "./Components/UptimeStatusBoxes";
+import GenericFallback from "../../../Components/GenericFallback";
+// MUI Components
+import { Stack, Typography } from "@mui/material";
+
+// Utils
+import { useState } from "react";
+import { useParams } from "react-router-dom";
+import { useSelector } from "react-redux";
+import { useTheme } from "@emotion/react";
+import { useIsAdmin } from "../../../Hooks/useIsAdmin";
+import useFetchUptimeMonitorDetails from "../../../Hooks/useFetchUptimeMonitorDetails";
+import useCertificateFetch from "./Hooks/useCertificateFetch";
+import useChecksFetch from "./Hooks/useChecksFetch";
+import { useTranslation } from "react-i18next";
+
+// Constants
+const BREADCRUMBS = [
+ { name: "uptime", path: "/uptime" },
+ { name: "details", path: "" },
+ // { name: "details", path: `/uptime/${monitorId}` }, Is this needed? We can't click on this anywy
+];
+
+const certificateDateFormat = "MMM D, YYYY h A";
+
+const UptimeDetails = () => {
+ // Redux state
+ const uiTimezone = useSelector((state) => state.ui.timezone);
+
+ // Local state
+ const [dateRange, setDateRange] = useState("recent");
+
+ const [page, setPage] = useState(0);
+ const [rowsPerPage, setRowsPerPage] = useState(5);
+
+ // Utils
+ const dateFormat =
+ dateRange === "day" || dateRange === "recent" ? "MMM D, h A" : "MMM D";
+ const { monitorId } = useParams();
+ const theme = useTheme();
+ const isAdmin = useIsAdmin();
+ const { t } = useTranslation();
+
+ const [monitorData, monitorStats, monitorIsLoading, monitorNetworkError] =
+ useFetchUptimeMonitorDetails({
+ monitorId,
+ dateRange,
+ });
+
+ const monitor = monitorData?.monitor;
+
+ const [certificateExpiry, certificateIsLoading] = useCertificateFetch({
+ monitor,
+ monitorId,
+ certificateDateFormat,
+ uiTimezone,
+ });
+
+ const monitorType = monitor?.type;
+ const [checks, checksCount, checksAreLoading, checksNetworkError] = useChecksFetch({
+ monitorId,
+ monitorType,
+ dateRange,
+ page,
+ rowsPerPage,
+ });
+
+ // Handlers
+ const handlePageChange = (_, newPage) => {
+ setPage(newPage);
+ };
+
+ const handleChangeRowsPerPage = (event) => {
+ setRowsPerPage(event.target.value);
+ };
+
+ if (monitorNetworkError || checksNetworkError) {
+ return (
+
+
+ {t("networkError")}
+
+ {t("checkConnection")}
+
+ );
+ }
+
+ // Empty view, displayed when loading is complete and there are no checks
+ if (!monitorIsLoading && !checksAreLoading && checksCount === 0) {
+ return (
+
+
+
+
+ {t("distributedUptimeDetailsNoMonitorHistory")}
+
+
+ );
+ }
+
+ return (
+
+
+
+
+
+
+
+
+
+ );
+};
+
+export default UptimeDetails;
diff --git a/client/src/Pages/Uptime/Monitors/Components/Filter/index.jsx b/client/src/Pages/Uptime/Monitors/Components/Filter/index.jsx
new file mode 100644
index 000000000..7d9f5a6bf
--- /dev/null
+++ b/client/src/Pages/Uptime/Monitors/Components/Filter/index.jsx
@@ -0,0 +1,156 @@
+import { useTheme } from "@emotion/react";
+import PropTypes from "prop-types";
+import FilterHeader from "../../../../../Components/FilterHeader";
+import { useMemo } from "react";
+import { Box, Button } from "@mui/material";
+import ClearIcon from "@mui/icons-material/Clear";
+import { useTranslation } from "react-i18next";
+
+/**
+ * Filter Component
+ *
+ * A high-level component that provides filtering options for type, status, and state.
+ * It allows users to select multiple options for each filter and reset the filters.
+ *
+ * @component
+ * @param {Object} props - The component props.
+ * @param {string[]} props.selectedTypes - An array of selected type values.
+ * @param {function} props.setSelectedTypes - A function to set the selected type values.
+ * @param {string[]} props.selectedStatus - An array of selected status values.
+ * @param {function} props.setSelectedStatus - A function to set the selected status values.
+ * @param {string[]} props.selectedState - An array of selected state values.
+ * @param {function} props.setSelectedState - A function to set the selected state values.
+ * @param {function} props.setToFilterStatus - A function to set the filter status based on selected status values.
+ * @param {function} props.setToFilterActive - A function to set the filter active state based on selected state values.
+ * @param {function} props.handleReset - A function to reset all filters.
+ *
+ * @returns {JSX.Element} The rendered Filter component.
+ */
+
+const getTypeOptions = () => [
+ { value: "http", label: "HTTP(S)" },
+ { value: "ping", label: "Ping" },
+ { value: "docker", label: "Docker" },
+ { value: "port", label: "Port" },
+];
+
+// These functions were moved inline to ensure translations are applied correctly
+
+const Filter = ({
+ selectedTypes,
+ setSelectedTypes,
+ selectedStatus,
+ setSelectedStatus,
+ selectedState,
+ setSelectedState,
+ setToFilterStatus,
+ setToFilterActive,
+ handleReset,
+}) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+
+ const typeOptions = getTypeOptions();
+ // Create status options with translations
+ const statusOptions = [
+ { value: "Up", label: t("monitorStatus.up") },
+ { value: "Down", label: t("monitorStatus.down") },
+ ];
+ // Create state options with translations
+ const stateOptions = [
+ { value: "Active", label: t("monitorState.active") },
+ { value: "Paused", label: t("monitorState.paused") },
+ ];
+
+ const handleTypeChange = (event) => {
+ const selectedValues = event.target.value;
+ setSelectedTypes(selectedValues.length > 0 ? selectedValues : undefined);
+ };
+
+ const handleStatusChange = (event) => {
+ const selectedValues = event.target.value;
+ setSelectedStatus(selectedValues.length > 0 ? selectedValues : undefined);
+
+ if (selectedValues.length === 0 || selectedValues.length === 2) {
+ setToFilterStatus(undefined);
+ } else {
+ setToFilterStatus(selectedValues[0] === "Up" ? "true" : "false");
+ }
+ };
+
+ const handleStateChange = (event) => {
+ const selectedValues = event.target.value;
+ setSelectedState(selectedValues);
+
+ if (selectedValues.length === 0 || selectedValues.length === 2) {
+ setToFilterActive(undefined);
+ } else {
+ setToFilterActive(selectedValues[0] === "Active" ? "true" : "false");
+ }
+ };
+
+ const isFilterActive = useMemo(() => {
+ return (
+ (selectedTypes?.length ?? 0) > 0 ||
+ (selectedState?.length ?? 0) > 0 ||
+ (selectedStatus?.length ?? 0) > 0
+ );
+ }, [selectedState, selectedTypes, selectedStatus]);
+
+ return (
+
+
+
+
+ }
+ sx={{
+ visibility: isFilterActive ? "visible" : "hidden",
+ }}
+ >
+ {t("reset")}
+
+
+ );
+};
+
+Filter.propTypes = {
+ selectedTypes: PropTypes.arrayOf(PropTypes.string),
+ setSelectedTypes: PropTypes.func.isRequired,
+ selectedStatus: PropTypes.arrayOf(PropTypes.string),
+ setSelectedStatus: PropTypes.func.isRequired,
+ selectedState: PropTypes.arrayOf(PropTypes.string),
+ setSelectedState: PropTypes.func.isRequired,
+ setToFilterStatus: PropTypes.func.isRequired,
+ setToFilterActive: PropTypes.func.isRequired,
+ handleReset: PropTypes.func.isRequired,
+};
+
+export default Filter;
diff --git a/client/src/Pages/Uptime/Monitors/Components/LoadingSpinner/index.jsx b/client/src/Pages/Uptime/Monitors/Components/LoadingSpinner/index.jsx
new file mode 100644
index 000000000..a649473af
--- /dev/null
+++ b/client/src/Pages/Uptime/Monitors/Components/LoadingSpinner/index.jsx
@@ -0,0 +1,46 @@
+import { CircularProgress, Box } from "@mui/material";
+import { useTheme } from "@emotion/react";
+import PropTypes from "prop-types";
+const LoadingSpinner = ({ shouldRender }) => {
+ const theme = useTheme();
+ if (shouldRender === false) {
+ return;
+ }
+
+ return (
+ <>
+
+
+
+
+ >
+ );
+};
+
+LoadingSpinner.propTypes = {
+ shouldRender: PropTypes.bool,
+};
+
+export default LoadingSpinner;
diff --git a/client/src/Pages/Uptime/Monitors/Components/SearchComponent/index.jsx b/client/src/Pages/Uptime/Monitors/Components/SearchComponent/index.jsx
new file mode 100644
index 000000000..0c6eec854
--- /dev/null
+++ b/client/src/Pages/Uptime/Monitors/Components/SearchComponent/index.jsx
@@ -0,0 +1,49 @@
+import { useState } from "react";
+import Search from "../../../../../Components/Inputs/Search";
+import { Box } from "@mui/material";
+import useDebounce from "../../Hooks/useDebounce";
+import { useEffect, useRef } from "react";
+import PropTypes from "prop-types";
+
+const SearchComponent = ({ monitors = [], onSearchChange, setIsSearching }) => {
+ const isFirstRender = useRef(true);
+ const [localSearch, setLocalSearch] = useState("");
+ const debouncedSearch = useDebounce(localSearch, 500);
+ useEffect(() => {
+ if (isFirstRender.current === true) {
+ isFirstRender.current = false;
+ return;
+ }
+ onSearchChange(debouncedSearch);
+ setIsSearching(false);
+ }, [debouncedSearch, onSearchChange, setIsSearching]);
+
+ const handleSearch = (value) => {
+ setLocalSearch(value);
+ setIsSearching(true);
+ };
+
+ return (
+
+
+
+ );
+};
+
+SearchComponent.propTypes = {
+ monitors: PropTypes.array,
+ onSearchChange: PropTypes.func,
+ setIsSearching: PropTypes.func,
+};
+
+export default SearchComponent;
diff --git a/Client/src/Pages/Uptime/Home/skeleton.jsx b/client/src/Pages/Uptime/Monitors/Components/Skeleton/index.jsx
similarity index 100%
rename from Client/src/Pages/Uptime/Home/skeleton.jsx
rename to client/src/Pages/Uptime/Monitors/Components/Skeleton/index.jsx
diff --git a/client/src/Pages/Uptime/Monitors/Components/StatusBoxes/index.jsx b/client/src/Pages/Uptime/Monitors/Components/StatusBoxes/index.jsx
new file mode 100644
index 000000000..5587dad66
--- /dev/null
+++ b/client/src/Pages/Uptime/Monitors/Components/StatusBoxes/index.jsx
@@ -0,0 +1,39 @@
+import PropTypes from "prop-types";
+import { Stack } from "@mui/material";
+import StatusBox from "./statusBox";
+import { useTheme } from "@emotion/react";
+import { useTranslation } from "react-i18next";
+import SkeletonLayout from "./skeleton";
+
+const StatusBoxes = ({ shouldRender, monitorsSummary }) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ if (!shouldRender) return ;
+ return (
+
+
+
+
+
+ );
+};
+
+StatusBoxes.propTypes = {
+ monitorsSummary: PropTypes.object,
+ shouldRender: PropTypes.bool,
+};
+
+export default StatusBoxes;
diff --git a/client/src/Pages/Uptime/Monitors/Components/StatusBoxes/skeleton.jsx b/client/src/Pages/Uptime/Monitors/Components/StatusBoxes/skeleton.jsx
new file mode 100644
index 000000000..df6e08ccd
--- /dev/null
+++ b/client/src/Pages/Uptime/Monitors/Components/StatusBoxes/skeleton.jsx
@@ -0,0 +1,31 @@
+import { Skeleton, Stack } from "@mui/material";
+import { useTheme } from "@emotion/react";
+
+const SkeletonLayout = () => {
+ const theme = useTheme();
+ return (
+
+
+
+
+
+ );
+};
+
+export default SkeletonLayout;
diff --git a/Client/src/Pages/Uptime/Home/StatusBox.jsx b/client/src/Pages/Uptime/Monitors/Components/StatusBoxes/statusBox.jsx
similarity index 60%
rename from Client/src/Pages/Uptime/Home/StatusBox.jsx
rename to client/src/Pages/Uptime/Monitors/Components/StatusBoxes/statusBox.jsx
index d04ebdf5f..b157857ea 100644
--- a/Client/src/Pages/Uptime/Home/StatusBox.jsx
+++ b/client/src/Pages/Uptime/Monitors/Components/StatusBoxes/statusBox.jsx
@@ -1,9 +1,9 @@
import PropTypes from "prop-types";
import { useTheme } from "@emotion/react";
import { Box, Stack, Typography } from "@mui/material";
-import Arrow from "../../../assets/icons/top-right-arrow.svg?react";
-import Background from "../../../assets/Images/background-grid.svg?react";
-import ClockSnooze from "../../../assets/icons/clock-snooze.svg?react";
+import Arrow from "../../../../../assets/icons/top-right-arrow.svg?react";
+import Background from "../../../../../assets/Images/background-grid.svg?react";
+import ClockSnooze from "../../../../../assets/icons/clock-snooze.svg?react";
const StatusBox = ({ title, value }) => {
const theme = useTheme();
@@ -52,47 +52,48 @@ const StatusBox = ({ title, value }) => {
overflow="hidden"
>
-
- {title}
-
- {icon}
-
- {value}
-
-
+
- #
-
+
+ {title}
+
+ {icon}
+
+
+ {value}
+
+
+ #
+
+
);
diff --git a/client/src/Pages/Uptime/Monitors/Components/UptimeDataTable/index.jsx b/client/src/Pages/Uptime/Monitors/Components/UptimeDataTable/index.jsx
new file mode 100644
index 000000000..a6ef105b6
--- /dev/null
+++ b/client/src/Pages/Uptime/Monitors/Components/UptimeDataTable/index.jsx
@@ -0,0 +1,227 @@
+// Components
+import { Box, Stack } from "@mui/material";
+import DataTable from "../../../../../Components/Table";
+import ArrowDownwardRoundedIcon from "@mui/icons-material/ArrowDownwardRounded";
+import ArrowUpwardRoundedIcon from "@mui/icons-material/ArrowUpwardRounded";
+import Host from "../../../../../Components/Host";
+import { StatusLabel } from "../../../../../Components/Label";
+import BarChart from "../../../../../Components/Charts/BarChart";
+import ActionsMenu from "../../../../../Components/ActionsMenu";
+
+import LoadingSpinner from "../LoadingSpinner";
+import TableSkeleton from "../../../../../Components/Table/skeleton";
+
+// Utils
+import { useTheme } from "@emotion/react";
+import useUtils from "../../Hooks/useUtils";
+import { useNavigate } from "react-router-dom";
+import PropTypes from "prop-types";
+import { useTranslation } from "react-i18next";
+
+/**
+ * UptimeDataTable displays a table of uptime monitors with sorting, searching, and action capabilities
+ * @param {Object} props - Component props
+ * @param {boolean} props.isAdmin - Whether the current user has admin privileges
+ * @param {boolean} props.isLoading - Loading state of the table
+ * @param {Array<{
+ * _id: string,
+ * url: string,
+ * title: string,
+ * percentage: number,
+ * percentageColor: string,
+ * monitor: {
+ * _id: string,
+ * type: string,
+ * checks: Array
+ * }
+ * }>} props.monitors - Array of monitor objects to display
+ * @param {number} props.monitorCount - Total count of monitors
+ * @param {Object} props.sort - Current sort configuration
+ * @param {string} props.sort.field - Field to sort by
+ * @param {'asc'|'desc'} props.sort.order - Sort direction
+ * @param {Function} props.setSort - Callback to update sort configuration
+ * @param {string} props.search - Current search query
+ * @param {Function} props.setSearch - Callback to update search query
+ * @param {boolean} props.isSearching - Whether a search is in progress
+ * @param {Function} props.setIsLoading - Callback to update loading state
+ * @param {Function} props.triggerUpdate - Callback to trigger a data refresh
+ * @returns {JSX.Element} Rendered component
+ */
+const UptimeDataTable = ({
+ isAdmin,
+ isSearching,
+ filteredMonitors,
+ sort,
+ setSort,
+ triggerUpdate,
+ monitorsAreLoading,
+}) => {
+ // Utils
+ const navigate = useNavigate();
+ const { determineState } = useUtils();
+ const theme = useTheme();
+ const { t } = useTranslation();
+
+ // Local state
+ // Handlers
+ const handleSort = (field) => {
+ let order = "";
+ if (sort?.field !== field) {
+ order = "desc";
+ } else {
+ order = sort?.order === "asc" ? "desc" : "asc";
+ }
+ setSort({ field, order });
+ };
+
+ const headers = [
+ {
+ id: "name",
+ content: (
+ handleSort("name")}
+ >
+ {t("host")}
+
+ {sort?.order === "asc" ? (
+
+ ) : (
+
+ )}
+
+
+ ),
+ render: (row) => (
+
+ ),
+ },
+ {
+ id: "status",
+ content: (
+ handleSort("status")}
+ >
+ {" "}
+ {t("status")}
+
+ {sort?.order === "asc" ? (
+
+ ) : (
+
+ )}
+
+
+ ),
+ render: (row) => {
+ const status = determineState(row.monitor);
+ return (
+
+ );
+ },
+ },
+ {
+ id: "responseTime",
+ content: t("responseTime"),
+ render: (row) => (
+
+
+
+ ),
+ },
+ {
+ id: "type",
+ content: t("type"),
+ render: (row) => (
+
+ {row.monitor.type === "http" ? "HTTP(s)" : row.monitor.type}
+
+ ),
+ },
+ {
+ id: "actions",
+ content: t("actions"),
+ render: (row) => (
+
+ ),
+ },
+ ];
+
+ if (monitorsAreLoading) {
+ return ;
+ }
+
+ return (
+
+
+ {
+ navigate(`/uptime/${row._id}`);
+ },
+ emptyView: "No monitors found",
+ }}
+ />
+
+ );
+};
+
+UptimeDataTable.propTypes = {
+ isSearching: PropTypes.bool,
+ setSort: PropTypes.func,
+ setSearch: PropTypes.func,
+ triggerUpdate: PropTypes.func,
+ debouncedSearch: PropTypes.string,
+ onSearchChange: PropTypes.func,
+ isAdmin: PropTypes.bool,
+ monitors: PropTypes.array,
+ filteredMonitors: PropTypes.array,
+ monitorCount: PropTypes.number,
+ monitorsAreLoading: PropTypes.bool,
+ sort: PropTypes.shape({
+ field: PropTypes.string,
+ order: PropTypes.oneOf(["asc", "desc"]),
+ }),
+};
+
+export default UptimeDataTable;
diff --git a/Client/src/Utils/debounce.jsx b/client/src/Pages/Uptime/Monitors/Hooks/useDebounce.jsx
similarity index 100%
rename from Client/src/Utils/debounce.jsx
rename to client/src/Pages/Uptime/Monitors/Hooks/useDebounce.jsx
diff --git a/client/src/Pages/Uptime/Monitors/Hooks/useMonitorsFetch.jsx b/client/src/Pages/Uptime/Monitors/Hooks/useMonitorsFetch.jsx
new file mode 100644
index 000000000..1f1d15212
--- /dev/null
+++ b/client/src/Pages/Uptime/Monitors/Hooks/useMonitorsFetch.jsx
@@ -0,0 +1,77 @@
+import { useEffect, useState } from "react";
+import { networkService } from "../../../../main";
+import { createToast } from "../../../../Utils/toastUtils";
+import { useTheme } from "@emotion/react";
+import { useMonitorUtils } from "../../../../Hooks/useMonitorUtils";
+
+export const useMonitorFetch = ({
+ teamId,
+ limit,
+ page,
+ rowsPerPage,
+ filter,
+ field,
+ order,
+ triggerUpdate,
+}) => {
+ const [monitorsAreLoading, setMonitorsAreLoading] = useState(false);
+ const [monitors, setMonitors] = useState(undefined);
+ const [filteredMonitors, setFilteredMonitors] = useState(undefined);
+ const [monitorsSummary, setMonitorsSummary] = useState(undefined);
+ const [networkError, setNetworkError] = useState(false);
+
+ const theme = useTheme();
+ const { getMonitorWithPercentage } = useMonitorUtils();
+ useEffect(() => {
+ const fetchMonitors = async () => {
+ try {
+ setMonitorsAreLoading(true);
+ const res = await networkService.getMonitorsByTeamId({
+ teamId,
+ limit,
+ types: ["http", "ping", "docker", "port"],
+ page,
+ rowsPerPage,
+ filter,
+ field,
+ order,
+ });
+ const { monitors, filteredMonitors, summary } = res.data.data;
+ const mappedMonitors = filteredMonitors.map((monitor) =>
+ getMonitorWithPercentage(monitor, theme)
+ );
+ setMonitors(monitors);
+ setFilteredMonitors(mappedMonitors);
+ setMonitorsSummary(summary);
+ } catch (error) {
+ setNetworkError(true);
+ createToast({
+ body: error.message,
+ });
+ } finally {
+ setMonitorsAreLoading(false);
+ }
+ };
+ fetchMonitors();
+ }, [
+ teamId,
+ limit,
+ field,
+ filter,
+ order,
+ page,
+ rowsPerPage,
+ theme,
+ triggerUpdate,
+ getMonitorWithPercentage,
+ ]);
+ return {
+ monitors,
+ filteredMonitors,
+ monitorsSummary,
+ monitorsAreLoading,
+ networkError,
+ };
+};
+
+export default useMonitorFetch;
diff --git a/Client/src/Pages/Uptime/utils.jsx b/client/src/Pages/Uptime/Monitors/Hooks/useUtils.jsx
similarity index 98%
rename from Client/src/Pages/Uptime/utils.jsx
rename to client/src/Pages/Uptime/Monitors/Hooks/useUtils.jsx
index 0e5fc62ec..ff3288cdf 100644
--- a/Client/src/Pages/Uptime/utils.jsx
+++ b/client/src/Pages/Uptime/Monitors/Hooks/useUtils.jsx
@@ -2,6 +2,7 @@ import { useTheme } from "@mui/material";
const useUtils = () => {
const determineState = (monitor) => {
+ if (typeof monitor === "undefined") return "pending";
if (monitor.isActive === false) return "paused";
if (monitor?.status === undefined) return "pending";
return monitor?.status == true ? "up" : "down";
diff --git a/client/src/Pages/Uptime/Monitors/index.jsx b/client/src/Pages/Uptime/Monitors/index.jsx
new file mode 100644
index 000000000..ce9123816
--- /dev/null
+++ b/client/src/Pages/Uptime/Monitors/index.jsx
@@ -0,0 +1,248 @@
+// Required Data
+// 1. Monitor summary
+// 2. List of monitors filtered by search term with 25 checks each
+// 2a.List of monitors must have the total number of monitors that match.
+
+// Components
+import Breadcrumbs from "../../../Components/Breadcrumbs";
+import Greeting from "../../../Utils/greeting";
+import StatusBoxes from "./Components/StatusBoxes";
+import UptimeDataTable from "./Components/UptimeDataTable";
+import Pagination from "../../../Components/Table/TablePagination";
+import CreateMonitorHeader from "../../../Components/MonitorCreateHeader";
+import Fallback from "../../../Components/Fallback";
+import GenericFallback from "../../../Components/GenericFallback";
+import SearchComponent from "./Components/SearchComponent";
+import Filter from "./Components/Filter";
+
+import MonitorCountHeader from "../../../Components/MonitorCountHeader";
+
+// MUI Components
+import { Stack, Box, Button, Typography } from "@mui/material";
+
+// Utils
+import { useState, useCallback } from "react";
+import { useIsAdmin } from "../../../Hooks/useIsAdmin";
+import { useTheme } from "@emotion/react";
+import { useNavigate } from "react-router-dom";
+import { useSelector, useDispatch } from "react-redux";
+import { setRowsPerPage } from "../../../Features/UI/uiSlice";
+import PropTypes from "prop-types";
+import useFetchMonitorsWithSummary from "../../../Hooks/useFetchMonitorsWithSummary";
+import useFetchMonitorsWithChecks from "../../../Hooks/useFetchMonitorsWithChecks";
+import { useTranslation } from "react-i18next";
+const TYPES = ["http", "ping", "docker", "port"];
+const CreateMonitorButton = ({ shouldRender }) => {
+ // Utils
+ const navigate = useNavigate();
+ const { t } = useTranslation();
+ if (shouldRender === false) {
+ return;
+ }
+
+ return (
+
+ {
+ navigate("/uptime/create");
+ }}
+ >
+ {t("createNew")}
+
+
+ );
+};
+
+CreateMonitorButton.propTypes = {
+ shouldRender: PropTypes.bool,
+};
+
+const UptimeMonitors = () => {
+ // Redux state
+ const { user } = useSelector((state) => state.auth);
+ const rowsPerPage = useSelector((state) => state.ui.monitors.rowsPerPage);
+
+ // Local state
+ const [search, setSearch] = useState(undefined);
+ const [page, setPage] = useState(undefined);
+ const [sort, setSort] = useState(undefined);
+ const [isSearching, setIsSearching] = useState(false);
+ const [monitorUpdateTrigger, setMonitorUpdateTrigger] = useState(false);
+ const [selectedTypes, setSelectedTypes] = useState(undefined);
+ const [selectedState, setSelectedState] = useState(undefined);
+ const [selectedStatus, setSelectedStatus] = useState(undefined);
+ const [toFilterStatus, setToFilterStatus] = useState(undefined);
+ const [toFilterActive, setToFilterActive] = useState(undefined);
+
+ // Utils
+ const theme = useTheme();
+ const navigate = useNavigate();
+ const isAdmin = useIsAdmin();
+ const dispatch = useDispatch();
+ const { t } = useTranslation();
+
+ const BREADCRUMBS = [{ name: t("menu.uptime"), path: "/uptime" }];
+
+ // Handlers
+ const handleChangePage = (event, newPage) => {
+ setPage(newPage);
+ };
+
+ const handleChangeRowsPerPage = (event) => {
+ dispatch(
+ setRowsPerPage({
+ value: parseInt(event.target.value, 10),
+ table: "monitors",
+ })
+ );
+ setPage(0);
+ };
+
+ const triggerUpdate = useCallback(() => {
+ setMonitorUpdateTrigger((prev) => !prev);
+ }, []);
+
+ const teamId = user.teamId;
+
+ const [monitors, monitorsSummary, monitorsWithSummaryIsLoading, networkError] =
+ useFetchMonitorsWithSummary({
+ teamId,
+ types: TYPES,
+ monitorUpdateTrigger,
+ });
+
+ const handleReset = () => {
+ setSelectedState(undefined);
+ setSelectedTypes(undefined);
+ setSelectedStatus(undefined);
+ setToFilterStatus(undefined);
+ setToFilterActive(undefined);
+ };
+
+ const filterLookup = new Map([
+ [toFilterStatus, "status"],
+ [toFilterActive, "isActive"],
+ ]);
+
+ const activeFilter = [...filterLookup].find(([key]) => key !== undefined);
+ const field = activeFilter?.[1] || sort?.field;
+ const filter = activeFilter?.[0] || search;
+
+ const effectiveTypes = selectedTypes?.length ? selectedTypes : TYPES;
+
+ const [
+ monitorsWithChecks,
+ monitorsWithChecksCount,
+ monitorsWithChecksIsLoading,
+ monitorsWithChecksNetworkError,
+ ] = useFetchMonitorsWithChecks({
+ teamId,
+ types: effectiveTypes,
+ limit: 25,
+ page: page,
+ rowsPerPage: rowsPerPage,
+ filter: filter,
+ field: field,
+ order: sort?.order,
+ monitorUpdateTrigger,
+ });
+
+ const isLoading = monitorsWithSummaryIsLoading || monitorsWithChecksIsLoading;
+ if (networkError) {
+ return (
+
+
+ {t("networkError")}
+
+ {t("checkConnection")}
+
+ );
+ }
+ if (
+ !isLoading &&
+ (monitorsSummary?.totalMonitors === 0 ||
+ typeof monitorsSummary?.totalMonitors === "undefined")
+ ) {
+ return (
+
+ );
+ }
+ return (
+
+
+
+
+
+
+
+ 0 && !monitorsWithSummaryIsLoading}
+ monitorCount={monitorsSummary?.totalMonitors}
+ >
+
+
+
+
+
+
+ );
+};
+
+export default UptimeMonitors;
diff --git a/client/src/Routes/index.jsx b/client/src/Routes/index.jsx
new file mode 100644
index 000000000..e334af912
--- /dev/null
+++ b/client/src/Routes/index.jsx
@@ -0,0 +1,303 @@
+import { Navigate, Route, Routes as LibRoutes } from "react-router";
+import HomeLayout from "../Components/Layouts/HomeLayout";
+import NotFound from "../Pages/NotFound";
+
+// Auth
+import AuthLogin from "../Pages/Auth/Login/Login";
+import AuthRegister from "../Pages/Auth/Register/Register";
+import AuthForgotPassword from "../Pages/Auth/ForgotPassword";
+import AuthCheckEmail from "../Pages/Auth/CheckEmail";
+import AuthSetNewPassword from "../Pages/Auth/SetNewPassword";
+import AuthNewPasswordConfirmed from "../Pages/Auth/NewPasswordConfirmed";
+
+// Uptime
+import Uptime from "../Pages/Uptime/Monitors";
+import UptimeDetails from "../Pages/Uptime/Details";
+import UptimeCreate from "../Pages/Uptime/Create";
+import UptimeConfigure from "../Pages/Uptime/Configure";
+
+// PageSpeed
+import PageSpeed from "../Pages/PageSpeed/Monitors";
+import PageSpeedCreate from "../Pages/PageSpeed/Create";
+import PageSpeedDetails from "../Pages/PageSpeed/Details";
+import PageSpeedConfigure from "../Pages/PageSpeed/Configure";
+
+// Infrastructure
+import Infrastructure from "../Pages/Infrastructure/Monitors";
+import InfrastructureCreate from "../Pages/Infrastructure/Create";
+import InfrastructureDetails from "../Pages/Infrastructure/Details";
+
+// Distributed Uptime
+import DistributedUptimeMonitors from "../Pages/DistributedUptime/Monitors";
+import CreateDistributedUptime from "../Pages/DistributedUptime/Create";
+import DistributedUptimeDetails from "../Pages/DistributedUptime/Details";
+
+// Distributed Uptime Status
+import CreateDistributedUptimeStatus from "../Pages/DistributedUptimeStatus/Create";
+import DistributedUptimeStatus from "../Pages/DistributedUptimeStatus/Status";
+
+// Server Status
+import ServerUnreachable from "../Pages/ServerUnreachable";
+
+// Incidents
+import Incidents from "../Pages/Incidents";
+
+// Status pages
+import CreateStatus from "../Pages/StatusPage/Create";
+import StatusPages from "../Pages/StatusPage/StatusPages";
+import Status from "../Pages/StatusPage/Status";
+
+import Integrations from "../Pages/Integrations";
+
+// Settings
+import Account from "../Pages/Account";
+import Settings from "../Pages/Settings";
+
+import Maintenance from "../Pages/Maintenance";
+
+import ProtectedRoute from "../Components/ProtectedRoute";
+import ProtectedDistributedUptimeRoute from "../Components/ProtectedDistributedUptimeRoute";
+import CreateNewMaintenanceWindow from "../Pages/Maintenance/CreateMaintenance";
+import withAdminCheck from "../Components/HOC/withAdminCheck";
+import BulkImport from "../Pages/Uptime/BulkImport";
+
+const Routes = () => {
+ const AdminCheckedRegister = withAdminCheck(AuthRegister);
+ return (
+
+
+
+
+ }
+ >
+ }
+ />
+ }
+ />
+
+ }
+ />
+
+ }
+ />
+ }
+ />
+ }
+ />
+ {/*
+ {" "}
+
+ }
+ /> */}
+
+ {/*
+
+
+ }
+ />
+
+
+
+ }
+ /> */}
+ {/*
+
+
+ }
+ /> */}
+
+ }
+ />
+ }
+ />
+ }
+ />
+ }
+ />
+ }
+ />
+ }
+ />
+ }
+ />
+ }
+ />
+ }
+ />
+
+ }
+ />
+
+ }
+ />
+
+ {/*
+
+
+ }
+ /> */}
+
+ }
+ />
+
+ {/*
+
+
+ }
+ /> */}
+
+ }
+ />
+
+ {/*
+
+
+ }
+ /> */}
+
+ }
+ />
+ }
+ />
+ }
+ />
+ }
+ />
+ }
+ />
+ }
+ />
+ }
+ />
+
+
+ }
+ />
+
+ }
+ />
+
+ }
+ />
+
+ }
+ />
+ }
+ />
+ }
+ />
+ }
+ />
+ }
+ />
+ {/* }
+ /> */}
+
+ }
+ />
+ }
+ />
+
+ );
+};
+
+export { Routes };
diff --git a/Client/src/Utils/Logger.js b/client/src/Utils/Logger.js
similarity index 100%
rename from Client/src/Utils/Logger.js
rename to client/src/Utils/Logger.js
diff --git a/Client/src/Utils/NetworkService.js b/client/src/Utils/NetworkService.js
similarity index 68%
rename from Client/src/Utils/NetworkService.js
rename to client/src/Utils/NetworkService.js
index c73890218..4adf8ff8b 100644
--- a/Client/src/Utils/NetworkService.js
+++ b/client/src/Utils/NetworkService.js
@@ -1,9 +1,9 @@
import axios from "axios";
+import i18next from "i18next";
const BASE_URL = import.meta.env.VITE_APP_API_BASE_URL;
const FALLBACK_BASE_URL = "http://localhost:5000/api/v1";
import { clearAuthState } from "../Features/Auth/authSlice";
import { clearUptimeMonitorState } from "../Features/UptimeMonitors/uptimeMonitorsSlice";
-import { createToast } from "./toastUtils";
class NetworkService {
constructor(store, dispatch, navigate) {
@@ -24,10 +24,38 @@ class NetworkService {
}
this.setBaseUrl(baseURL);
});
+ this.axiosInstance.interceptors.request.use(
+ (config) => {
+ const currentLanguage = i18next.language || "en";
+
+ const { authToken } = store.getState().auth;
+
+ config.headers = {
+ Authorization: `Bearer ${authToken}`,
+ "Accept-Language": currentLanguage === "gb" ? "en" : currentLanguage,
+ ...config.headers,
+ };
+
+ return config;
+ },
+ (error) => {
+ return Promise.reject(error);
+ }
+ );
this.axiosInstance.interceptors.response.use(
(response) => response,
(error) => {
- if (!error.request && error.response && error.response.status === 401) {
+ // Handle network errors (server unreachable)
+ if (error.code === "ERR_NETWORK") {
+ // Navigate to server unreachable page
+ navigate("/server-unreachable");
+ // Return an empty resolved promise to stop the error propagation
+ return Promise.reject(error);
+ }
+
+ // Handle authentication errors
+
+ if (error.response && error.response.status === 401) {
dispatch(clearAuthState());
dispatch(clearUptimeMonitorState());
navigate("/login");
@@ -57,7 +85,6 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} config.monitorId - The monitor ID to be sent in the param.
* @returns {Promise} The response from the axios GET request.
*/
@@ -65,7 +92,6 @@ class NetworkService {
async getMonitorById(config) {
return this.axiosInstance.get(`/monitors/${config.monitorId}`, {
headers: {
- Authorization: `Bearer ${config.authToken}`,
"Content-Type": "application/json",
},
});
@@ -79,17 +105,13 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {Object} config.monitor - The monitor object to be sent in the request body.
* @returns {Promise} The response from the axios POST request.
*/
async createMonitor(config) {
- return this.axiosInstance.post(`/monitors`, config.monitor, {
- headers: {
- Authorization: `Bearer ${config.authToken}`,
- "Content-Type": "application/json",
- },
- });
+ const { monitor } = config;
+
+ return this.axiosInstance.post(`/monitors`, monitor);
}
/**
@@ -100,19 +122,17 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {Object} config.monitorURL - The monitor url to be sent in the request body.
* @returns {Promise} The response from the axios POST request.
*/
async checkEndpointResolution(config) {
- const { authToken, monitorURL } = config;
+ const { monitorURL } = config;
const params = new URLSearchParams();
if (monitorURL) params.append("monitorURL", monitorURL);
return this.axiosInstance.get(`/monitors/resolution/url?${params.toString()}`, {
headers: {
- Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
});
@@ -126,7 +146,6 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} config.teamId - Team ID
* @param {Array} config.types - Array of monitor types
* @returns {Promise} The response from the axios POST request.
@@ -143,7 +162,6 @@ class NetworkService {
`/monitors/team/summary/${config.teamId}?${params.toString()}`,
{
headers: {
- Authorization: `Bearer ${config.authToken}`,
"Content-Type": "application/json",
},
}
@@ -157,7 +175,6 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} config.teamId - The ID of the team whose monitors are to be retrieved.
* @param {number} [config.limit] - The maximum number of checks to retrieve. 0 for all, -1 for none
* @param {Array} [config.types] - The types of monitors to retrieve.
@@ -170,9 +187,7 @@ class NetworkService {
*/
async getMonitorsByTeamId(config) {
- const { authToken, teamId, limit, types, page, rowsPerPage, filter, field, order } =
- config;
-
+ const { teamId, limit, types, page, rowsPerPage, filter, field, order } = config;
const params = new URLSearchParams();
if (limit) params.append("limit", limit);
@@ -189,7 +204,6 @@ class NetworkService {
return this.axiosInstance.get(`/monitors/team/${teamId}?${params.toString()}`, {
headers: {
- Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
});
@@ -202,7 +216,6 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} config.monitorId - The ID of the monitor whose statistics are to be retrieved.
* @param {string} config.sortOrder - The order in which to sort the retrieved statistics.
* @param {number} config.limit - The maximum number of statistics to retrieve.
@@ -220,12 +233,7 @@ class NetworkService {
if (config.normalize) params.append("normalize", config.normalize);
return this.axiosInstance.get(
- `/monitors/stats/${config.monitorId}?${params.toString()}`,
- {
- headers: {
- Authorization: `Bearer ${config.authToken}`,
- },
- }
+ `/monitors/stats/${config.monitorId}?${params.toString()}`
);
}
@@ -234,12 +242,7 @@ class NetworkService {
if (config.dateRange) params.append("dateRange", config.dateRange);
return this.axiosInstance.get(
- `/monitors/hardware/details/${config.monitorId}?${params.toString()}`,
- {
- headers: {
- Authorization: `Bearer ${config.authToken}`,
- },
- }
+ `/monitors/hardware/details/${config.monitorId}?${params.toString()}`
);
}
async getUptimeDetailsById(config) {
@@ -248,12 +251,7 @@ class NetworkService {
if (config.normalize) params.append("normalize", config.normalize);
return this.axiosInstance.get(
- `/monitors/uptime/details/${config.monitorId}?${params.toString()}`,
- {
- headers: {
- Authorization: `Bearer ${config.authToken}`,
- },
- }
+ `/monitors/uptime/details/${config.monitorId}?${params.toString()}`
);
}
@@ -264,15 +262,15 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} config.monitorId - The ID of the monitor to be updated.
* @param {Object} config.updatedFields - The fields to be updated for the monitor.
* @returns {Promise} The response from the axios PUT request.
*/
async updateMonitor(config) {
- return this.axiosInstance.put(`/monitors/${config.monitorId}`, config.updatedFields, {
+ const { monitorId, updatedFields } = config;
+ const payload = updatedFields;
+ return this.axiosInstance.put(`/monitors/${monitorId}`, payload, {
headers: {
- Authorization: `Bearer ${config.authToken}`,
"Content-Type": "application/json",
},
});
@@ -285,14 +283,12 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} config.monitorId - The ID of the monitor to be deleted.
* @returns {Promise} The response from the axios DELETE request.
*/
async deleteMonitorById(config) {
return this.axiosInstance.delete(`/monitors/${config.monitorId}`, {
headers: {
- Authorization: `Bearer ${config.authToken}`,
"Content-Type": "application/json",
},
});
@@ -305,14 +301,12 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} config.teamId - The team ID of the monitors to be deleted.
* @returns {Promise} The response from the axios DELETE request.
*/
async deleteChecksByTeamId(config) {
return this.axiosInstance.delete(`/checks/team/${config.teamId}`, {
headers: {
- Authorization: `Bearer ${config.authToken}`,
"Content-Type": "application/json",
},
});
@@ -324,7 +318,6 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} config.monitorId - The ID of the monitor to be paused.
* @returns {Promise} The response from the axios POST request.
*/
@@ -334,7 +327,6 @@ class NetworkService {
{},
{
headers: {
- Authorization: `Bearer ${config.authToken}`,
"Content-Type": "application/json",
},
}
@@ -348,7 +340,6 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @returns {Promise} The response from the axios POST request.
*/
async addDemoMonitors(config) {
@@ -357,7 +348,6 @@ class NetworkService {
{},
{
headers: {
- Authorization: `Bearer ${config.authToken}`,
"Content-Type": "application/json",
},
}
@@ -371,13 +361,11 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @returns {Promise} The response from the axios DELETE request.
*/
async deleteAllMonitors(config) {
return this.axiosInstance.delete(`/monitors/`, {
headers: {
- Authorization: `Bearer ${config.authToken}`,
"Content-Type": "application/json",
},
});
@@ -390,17 +378,12 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} config.monitorId - The ID of the monitor whose certificate expiry is to be retrieved.
* @returns {Promise} The response from the axios GET request.
*
*/
async getCertificateExpiry(config) {
- return this.axiosInstance.get(`/monitors/certificate/${config.monitorId}`, {
- headers: {
- Authorization: `Bearer ${config.authToken}`,
- },
- });
+ return this.axiosInstance.get(`/monitors/certificate/${config.monitorId}`);
}
/**
@@ -437,18 +420,13 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} config.userId - The ID of the user to be updated.
* @param {Object} config.form - The form data for the user to be updated.
* @returns {Promise} The response from the axios PUT request.
*
*/
async updateUser(config) {
- return this.axiosInstance.put(`/auth/user/${config.userId}`, config.form, {
- headers: {
- Authorization: `Bearer ${config.authToken}`,
- },
- });
+ return this.axiosInstance.put(`/auth/user/${config.userId}`, config.form);
}
/**
@@ -458,14 +436,11 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} config.userId - The ID of the user to be deleted.
*
**/
async deleteUser(config) {
- return this.axiosInstance.delete(`/auth/user/${config.userId}`, {
- headers: { Authorization: `Bearer ${config.authToken}` },
- });
+ return this.axiosInstance.delete(`/auth/user/${config.userId}`);
}
/**
@@ -538,14 +513,11 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @returns {Promise} The response from the axios GET request.
*
*/
async getAllUsers(config) {
- return this.axiosInstance.get("/auth/users", {
- headers: { Authorization: `Bearer ${config.authToken}` },
- });
+ return this.axiosInstance.get("/auth/users");
}
/**
@@ -555,20 +527,31 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} config.email - The email of the user to be invited.
* @param {string} config.role - The role of the user to be invited.
* @returns {Promise} The response from the axios POST request.
*
*/
async requestInvitationToken(config) {
- return this.axiosInstance.post(
- `/invite`,
- { email: config.email, role: config.role },
- {
- headers: { Authorization: `Bearer ${config.authToken}` },
- }
- );
+ return this.axiosInstance.post(`/invite`, { email: config.email, role: config.role });
+ }
+ /**
+ * ************************************
+ * Sends an invitation token
+ * ************************************
+ *
+ * @async
+ * @param {Object} config - The configuration object.
+ * @param {string} config.email - The email of the user to be invited.
+ * @param {string} config.role - The role of the user to be invited.
+ * @returns {Promise} The response from the axios POST request.
+ *
+ */
+ async sendInvitationToken(config) {
+ return this.axiosInstance.post(`/invite/send`, {
+ email: config.email,
+ role: config.role,
+ });
}
/**
@@ -594,7 +577,6 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} config.monitorId - The ID of the monitor.
* @param {string} config.sortOrder - The order in which to sort the checks.
* @param {number} config.limit - The maximum number of checks to retrieve.
@@ -608,16 +590,16 @@ class NetworkService {
async getChecksByMonitor(config) {
const params = new URLSearchParams();
+ if (config.type) params.append("type", config.type);
if (config.sortOrder) params.append("sortOrder", config.sortOrder);
if (config.limit) params.append("limit", config.limit);
if (config.dateRange) params.append("dateRange", config.dateRange);
if (config.filter) params.append("filter", config.filter);
if (config.page) params.append("page", config.page);
if (config.rowsPerPage) params.append("rowsPerPage", config.rowsPerPage);
+ if (config.status !== undefined) params.append("status", config.status);
- return this.axiosInstance.get(`/checks/${config.monitorId}?${params.toString()}`, {
- headers: { Authorization: `Bearer ${config.authToken}` },
- });
+ return this.axiosInstance.get(`/checks/${config.monitorId}?${params.toString()}`);
}
/**
@@ -627,7 +609,6 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} config.userId - The ID of the user.
* @param {string} config.sortOrder - The order in which to sort the checks.
* @param {number} config.limit - The maximum number of checks to retrieve.
@@ -646,9 +627,8 @@ class NetworkService {
if (config.filter) params.append("filter", config.filter);
if (config.page) params.append("page", config.page);
if (config.rowsPerPage) params.append("rowsPerPage", config.rowsPerPage);
- return this.axiosInstance.get(`/checks/team/${config.teamId}?${params.toString()}`, {
- headers: { Authorization: `Bearer ${config.authToken}` },
- });
+ if (config.status !== undefined) params.append("status", config.status);
+ return this.axiosInstance.get(`/checks/team/${config.teamId}?${params.toString()}`);
}
/**
@@ -658,7 +638,6 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {number} config.ttl - TTL for checks
* @returns {Promise} The response from the axios GET request.
*
@@ -669,7 +648,6 @@ class NetworkService {
{ ttl: config.ttl },
{
headers: {
- Authorization: `Bearer ${config.authToken}`,
"Content-Type": "application/json",
},
}
@@ -683,7 +661,6 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @returns {Promise} The response from the axios GET request.
*
*/
@@ -691,7 +668,6 @@ class NetworkService {
async getAppSettings(config) {
return this.axiosInstance.get("/settings", {
headers: {
- Authorization: `Bearer ${config.authToken}`,
"Content-Type": "application/json",
},
});
@@ -705,19 +681,43 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {Object} config.settings - The monitor object to be sent in the request body.
* @returns {Promise} The response from the axios POST request.
*/
async updateAppSettings(config) {
return this.axiosInstance.put(`/settings`, config.settings, {
headers: {
- Authorization: `Bearer ${config.authToken}`,
"Content-Type": "application/json",
},
});
}
+ /**
+ * ************************************
+ * Test a notification integration
+ * ************************************
+ *
+ * @async
+ * @param {Object} config - The configuration object.
+ * @param {string} config.platform - The notification platform (slack, discord, telegram, webhook).
+ * @param {Object} config.payload - The payload with configuration for the notification.
+ * @returns {Promise} The response from the axios POST request.
+ */
+ async testNotification(config) {
+ return this.axiosInstance.post(
+ "/notifications/test-webhook",
+ {
+ platform: config.platform,
+ ...config.payload,
+ },
+ {
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }
+ );
+ }
+
/**
* ************************************
* Creates a maintenance window
@@ -725,7 +725,6 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {Object} config.maintenanceWindow - The maintenance window object to be sent in the request body.
* @returns {Promise} The response from the axios POST request.
*
@@ -734,7 +733,6 @@ class NetworkService {
async createMaintenanceWindow(config) {
return this.axiosInstance.post(`/maintenance-window`, config.maintenanceWindow, {
headers: {
- Authorization: `Bearer ${config.authToken}`,
"Content-Type": "application/json",
},
});
@@ -747,7 +745,6 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {Object} config.maintenanceWindowId - The maintenance window id.
* @param {Object} config.maintenanceWindow - The maintenance window object to be sent in the request body.
* @returns {Promise} The response from the axios POST request.
@@ -760,7 +757,6 @@ class NetworkService {
config.maintenanceWindow,
{
headers: {
- Authorization: `Bearer ${config.authToken}`,
"Content-Type": "application/json",
},
}
@@ -774,17 +770,15 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} [config.maintenanceWindowId] - The id of the maintenance window to delete.
* @returns {Promise} The response from the axios POST request.
*
*/
async getMaintenanceWindowById(config) {
- const { authToken, maintenanceWindowId } = config;
+ const { maintenanceWindowId } = config;
return this.axiosInstance.get(`/maintenance-window/${maintenanceWindowId}`, {
headers: {
- Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
});
@@ -797,7 +791,6 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} [config.active] - The status of the maintenance windows to retrieve.
* @param {number} [config.page] - The page number for pagination.
* @param {number} [config.rowsPerPage] - The number of rows per page for pagination.
@@ -808,7 +801,7 @@ class NetworkService {
*/
async getMaintenanceWindowsByTeamId(config) {
- const { authToken, active, page, rowsPerPage, field, order } = config;
+ const { active, page, rowsPerPage, field, order } = config;
const params = new URLSearchParams();
if (active) params.append("status", active);
@@ -819,7 +812,6 @@ class NetworkService {
return this.axiosInstance.get(`/maintenance-window/team?${params.toString()}`, {
headers: {
- Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
});
@@ -831,17 +823,15 @@ class NetworkService {
*
* @async
* @param {Object} config - The configuration object.
- * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} [config.maintenanceWindowId] - The id of the maintenance window to delete.
* @returns {Promise} The response from the axios POST request.
*
*/
async deleteMaintenanceWindow(config) {
- const { authToken, maintenanceWindowId } = config;
+ const { maintenanceWindowId } = config;
return this.axiosInstance.delete(`/maintenance-window/${maintenanceWindowId}`, {
headers: {
- Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
});
@@ -858,9 +848,318 @@ class NetworkService {
*/
async fetchGithubLatestRelease() {
return this.axiosInstance.get(
- "https://api.github.com/repos/bluewave-labs/bluewave-uptime/releases/latest"
+ "https://api.github.com/repos/bluewave-labs/bluewave-uptime/releases/latest",
+ {
+ headers: {
+ Authorization: null, // No authorization header for this request
+ },
+ }
);
}
+
+ getDistributedUptimeMonitors(config) {
+ const { teamId, limit, types, page, rowsPerPage, filter, field, order } = config;
+
+ const params = new URLSearchParams();
+
+ if (limit) params.append("limit", limit);
+ if (types) {
+ types.forEach((type) => {
+ params.append("type", type);
+ });
+ }
+ if (page) params.append("page", page);
+ if (rowsPerPage) params.append("rowsPerPage", rowsPerPage);
+ if (filter) params.append("filter", filter);
+ if (field) params.append("field", field);
+ if (order) params.append("order", order);
+
+ if (this.eventSource) {
+ this.eventSource.close();
+ }
+
+ const url = `${this.axiosInstance.defaults.baseURL}/distributed-uptime/monitors/${teamId}/initial?${params.toString()}`;
+ return this.axiosInstance.get(url);
+ }
+
+ subscribeToDistributedUptimeMonitors(config) {
+ const {
+ teamId,
+ onUpdate,
+ onError,
+ onOpen,
+ limit,
+ types,
+ page,
+ rowsPerPage,
+ filter,
+ field,
+ order,
+ } = config;
+
+ const params = new URLSearchParams();
+
+ if (limit) params.append("limit", limit);
+ if (types) {
+ types.forEach((type) => {
+ params.append("type", type);
+ });
+ }
+ if (page) params.append("page", page);
+ if (rowsPerPage) params.append("rowsPerPage", rowsPerPage);
+ if (filter) params.append("filter", filter);
+ if (field) params.append("field", field);
+ if (order) params.append("order", order);
+
+ if (this.eventSource) {
+ this.eventSource.close();
+ }
+
+ const url = `${this.axiosInstance.defaults.baseURL}/distributed-uptime/monitors/${teamId}?${params.toString()}`;
+ this.eventSource = new EventSource(url);
+
+ this.eventSource.onopen = () => {
+ onOpen?.();
+ };
+
+ this.eventSource.addEventListener("open", (e) => {});
+
+ this.eventSource.onmessage = (event) => {
+ const data = JSON.parse(event.data);
+ onUpdate(data);
+ };
+
+ this.eventSource.onerror = (error) => {
+ console.error("Monitor stream error:", error);
+ onError?.();
+ this.eventSource.close();
+ };
+
+ // Returns a cleanup function
+ return () => {
+ if (this.eventSource) {
+ this.eventSource.close();
+ this.eventSource = null;
+ }
+ return () => {
+ console.log("Nothing to cleanup");
+ };
+ };
+ }
+
+ getDistributedUptimeDetails(config) {
+ const params = new URLSearchParams();
+ const { monitorId, dateRange, normalize, isPublic } = config;
+ if (dateRange) params.append("dateRange", dateRange);
+ if (normalize) params.append("normalize", normalize);
+ let url;
+ if (isPublic) {
+ url = `${this.axiosInstance.defaults.baseURL}/distributed-uptime/monitors/details/public/${monitorId}/initial?${params.toString()}`;
+ } else {
+ url = `${this.axiosInstance.defaults.baseURL}/distributed-uptime/monitors/details/${monitorId}/initial?${params.toString()}`;
+ }
+ return this.axiosInstance.get(url);
+ }
+
+ subscribeToDistributedUptimeDetails(config) {
+ const params = new URLSearchParams();
+ const { monitorId, onUpdate, onOpen, onError, dateRange, normalize } = config;
+ if (dateRange) params.append("dateRange", dateRange);
+ if (normalize) params.append("normalize", normalize);
+
+ const url = `${this.axiosInstance.defaults.baseURL}/distributed-uptime/monitors/details/${monitorId}?${params.toString()}`;
+ this.eventSource = new EventSource(url);
+
+ this.eventSource.onopen = (e) => {
+ onOpen?.();
+ };
+
+ this.eventSource.onmessage = (event) => {
+ const data = JSON.parse(event.data);
+ onUpdate(data);
+ };
+
+ this.eventSource.onerror = (error) => {
+ console.error("Monitor stream error:", error);
+ onError?.();
+ this.eventSource.close();
+ };
+ return () => {
+ if (this.eventSource) {
+ this.eventSource.close();
+ this.eventSource = null;
+ }
+ };
+ }
+
+ async getStatusPage() {
+ return this.axiosInstance.get(`/status-page`, {
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ }
+
+ async getStatusPageByUrl(config) {
+ const { url, type } = config;
+ const params = new URLSearchParams();
+ params.append("type", type);
+
+ return this.axiosInstance.get(`/status-page/${url}?${params.toString()}`, {
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ }
+ async getDistributedStatusPageByUrl(config) {
+ const { url, type, timeFrame } = config;
+ const params = new URLSearchParams();
+ params.append("type", type);
+ params.append("timeFrame", timeFrame);
+ return this.axiosInstance.get(
+ `/status-page/distributed/${url}?${params.toString()}`,
+ {
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }
+ );
+ }
+
+ async getStatusPagesByTeamId(config) {
+ const { teamId } = config;
+ return this.axiosInstance.get(`/status-page/team/${teamId}`, {
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ }
+
+ async createStatusPage(config) {
+ const { user, form, isCreate } = config;
+
+ const fd = new FormData();
+ fd.append("teamId", user.teamId);
+ fd.append("userId", user._id);
+ fd.append("type", form.type);
+ form.isPublished !== undefined && fd.append("isPublished", form.isPublished);
+ form.companyName && fd.append("companyName", form.companyName);
+ form.url && fd.append("url", form.url);
+ form.timezone && fd.append("timezone", form.timezone);
+ form.color && fd.append("color", form.color);
+ form.showCharts && fd.append("showCharts", form.showCharts);
+ form.showUptimePercentage &&
+ fd.append("showUptimePercentage", form.showUptimePercentage);
+ form.monitors &&
+ form.monitors.forEach((monitorId) => {
+ fd.append("monitors[]", monitorId);
+ });
+ // Handle subMonitors, even if it's an empty array
+ if (form.subMonitors && form.subMonitors.length > 0) {
+ form.subMonitors.forEach((monitorId) => {
+ fd.append("subMonitors[]", monitorId);
+ });
+ } else {
+ fd.append("deleteSubmonitors", true);
+ }
+
+ if (form?.logo?.src && form?.logo?.src !== "") {
+ const imageResult = await axios.get(form.logo.src, {
+ responseType: "blob",
+ });
+ fd.append("logo", imageResult.data);
+ // Cleanup blob
+ if (form.logo.src.startsWith("blob:")) {
+ URL.revokeObjectURL(form.logo.src);
+ }
+ }
+
+ if (isCreate) {
+ return this.axiosInstance.post(`/status-page`, fd, {});
+ }
+
+ return this.axiosInstance.put(`/status-page`, fd, {});
+ }
+
+ async deleteStatusPage(config) {
+ const { url } = config;
+ const encodedUrl = encodeURIComponent(url);
+
+ return this.axiosInstance.delete(`/status-page/${encodedUrl}`, {});
+ }
+
+ // ************************************
+ // Create bulk monitors
+ // ************************************
+
+ async createBulkMonitors(formData) {
+ const response = await this.axiosInstance.post(`/monitors/bulk`, formData, {
+ headers: {
+ "Content-Type": "multipart/form-data",
+ },
+ });
+ return response.data;
+ }
+
+ // ************************************
+ // Fetch monitors with summary by TeamID
+ // ************************************
+ async getMonitorsWithSummaryByTeamId(config) {
+ const { teamId, types } = config;
+ const params = new URLSearchParams();
+
+ if (types) {
+ types.forEach((type) => {
+ params.append("type", type);
+ });
+ }
+
+ return this.axiosInstance.get(
+ `/monitors/summary/team/${teamId}?${params.toString()}`,
+ {
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }
+ );
+ }
+
+ // ************************************
+ // Fetch monitors with checks by TeamID
+ // ************************************
+ async getMonitorsWithChecksByTeamId(config) {
+ const { teamId, limit, types, page, rowsPerPage, filter, field, order } = config;
+ const params = new URLSearchParams();
+
+ if (limit) params.append("limit", limit);
+ if (types) {
+ types.forEach((type) => {
+ params.append("type", type);
+ });
+ }
+ if (page) params.append("page", page);
+ if (rowsPerPage) params.append("rowsPerPage", rowsPerPage);
+ if (filter) params.append("filter", filter);
+ if (field) params.append("field", field);
+ if (order) params.append("order", order);
+
+ return this.axiosInstance.get(
+ `/monitors/team/${teamId}/with-checks?${params.toString()}`,
+ {
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }
+ );
+ }
+
+ // ************************************
+ // Send tes t email
+ // ************************************
+ async sendTestEmail(config) {
+ const { to } = config;
+ return this.axiosInstance.post(`/monitors/test-email`, { to });
+ }
}
export default NetworkService;
diff --git a/Client/src/Utils/NetworkServiceProvider.jsx b/client/src/Utils/NetworkServiceProvider.jsx
similarity index 68%
rename from Client/src/Utils/NetworkServiceProvider.jsx
rename to client/src/Utils/NetworkServiceProvider.jsx
index 9fb65f1ca..684152e69 100644
--- a/Client/src/Utils/NetworkServiceProvider.jsx
+++ b/client/src/Utils/NetworkServiceProvider.jsx
@@ -1,14 +1,15 @@
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router";
import { setNetworkService } from "./NetworkService";
-import NetworkService from "./NetworkService";
+import NetworkService, { networkService } from "./NetworkService";
import { store } from "../store";
const NetworkServiceProvider = ({ children }) => {
const dispatch = useDispatch();
const navigate = useNavigate();
- const networkService = new NetworkService(store, dispatch, navigate);
- setNetworkService(networkService);
+ if (!networkService) {
+ setNetworkService(new NetworkService(store, dispatch, navigate));
+ }
return children;
};
diff --git a/Client/src/Utils/ReadMe.md b/client/src/Utils/ReadMe.md
similarity index 100%
rename from Client/src/Utils/ReadMe.md
rename to client/src/Utils/ReadMe.md
diff --git a/Client/src/Utils/Theme/constants.js b/client/src/Utils/Theme/constants.js
similarity index 77%
rename from Client/src/Utils/Theme/constants.js
rename to client/src/Utils/Theme/constants.js
index 11357e06d..920a55f69 100644
--- a/Client/src/Utils/Theme/constants.js
+++ b/client/src/Utils/Theme/constants.js
@@ -1,6 +1,6 @@
import { lighten, darken } from "@mui/material/styles"; // CAIO_REVIEW
-const typographyBase = 14;
+const typographyBase = 13;
/* TODO
Check for px in codebase. All font sizes should be in REM and should live here.
@@ -40,7 +40,6 @@ const paletteColors = {
blueGray150: "#667085",
blueGray200: "#475467",
blueGray400: "#344054",
- blueGray900: "#1c2130",
blueBlueWave: "#1570EF",
blue700: "#4E5BA6",
purple300: "#664EFF",
@@ -89,11 +88,14 @@ const newColors = {
gray100: "#F3F3F3",
gray200: "#EFEFEF",
gray500: "#A2A3A3",
+ gray900: "#1c1c1c",
blueGray50: "#E8F0FE",
blueGray500: "#475467",
blueGray600: "#344054",
blueGray800: "#1C2130",
+ blueGray900: "#515151",
blueBlueWave: "#1570EF",
+ lightBlueWave: "#CDE2FF",
/* I changed green 100 and green 700. Need to change red and warning as well, and refactor the object following the structure */
green100: "#67cd78",
green200: "#4B9B77",
@@ -152,10 +154,22 @@ const newSemanticColors = {
light: newColors.blueGray600,
dark: newColors.gray200,
},
+ contrastTextSecondaryDarkBg: {
+ light: newColors.gray200,
+ dark: newColors.gray200,
+ },
contrastTextTertiary: {
light: newColors.blueGray500,
dark: newColors.gray500,
},
+ contrastBorder: {
+ light: newColors.gray500,
+ dark: newColors.blueGray600,
+ },
+ contrastBorderDisabled: {
+ light: newColors.gray100,
+ dark: newColors.blueGray800,
+ },
lowContrast: {
light: newColors.gray200,
dark: newColors.blueGray600,
@@ -166,6 +180,10 @@ const newSemanticColors = {
light: newColors.gray200,
dark: "#313131" /* newColors.blueGray600 */,
},
+ light: {
+ light: newColors.lightBlueWave,
+ dark: newColors.lightBlueWave,
+ },
contrastText: {
light: newColors.blueGray600,
dark: newColors.gray200,
@@ -195,6 +213,20 @@ const newSemanticColors = {
dark: newColors.green200,
},
},
+ successSecondary: {
+ main: {
+ light: undefined,
+ dark: "#073C2D",
+ },
+ contrastText: {
+ light: undefined,
+ dark: "#34D399",
+ },
+ lowContrast: {
+ light: undefined,
+ dark: "#094434",
+ },
+ },
warning: {
main: {
light: newColors.orange700,
@@ -209,6 +241,21 @@ const newSemanticColors = {
dark: newColors.orange600,
},
},
+ /* Custom palette for PageSpeed warning box */
+ warningSecondary: {
+ main: {
+ light: paletteColors.orange50,
+ dark: paletteColors.orange800,
+ },
+ contrastText: {
+ light: paletteColors.orange600,
+ dark: paletteColors.orange100,
+ },
+ lowContrast: {
+ light: paletteColors.orange300,
+ dark: paletteColors.orange400,
+ },
+ },
error: {
main: {
light: newColors.red700,
@@ -223,6 +270,7 @@ const newSemanticColors = {
dark: newColors.red600,
},
},
+
/* These are temporary, just for everything not to break */
gradient: {
color1: {
@@ -246,6 +294,41 @@ const newSemanticColors = {
dark: paletteColors.gray850,
},
},
+
+ map: {
+ main: {
+ light: newColors.offWhite,
+ dark: undefined,
+ },
+ lowContrast: {
+ light: newColors.gray200,
+ dark: undefined,
+ },
+ highContrast: {
+ light: newColors.gray500,
+ dark: undefined,
+ },
+ },
+ chatbot: {
+ background: {
+ light: newColors.gray200,
+ dark: "#112B2B",
+ },
+ textAccent: {
+ light: "#C084FC",
+ dark: "#C084FC",
+ },
+ },
+ alert: {
+ main: {
+ light: newColors.gray200,
+ dark: newColors.gray900,
+ },
+ contrastText: {
+ light: newColors.blueGray600,
+ dark: newColors.blueGray900,
+ },
+ },
};
export { typographyLevels, semanticColors as colors, newSemanticColors };
diff --git a/Client/src/Utils/Theme/darkTheme.js b/client/src/Utils/Theme/darkTheme.js
similarity index 100%
rename from Client/src/Utils/Theme/darkTheme.js
rename to client/src/Utils/Theme/darkTheme.js
diff --git a/Client/src/Utils/Theme/extractColorObject.js b/client/src/Utils/Theme/extractColorObject.js
similarity index 100%
rename from Client/src/Utils/Theme/extractColorObject.js
rename to client/src/Utils/Theme/extractColorObject.js
diff --git a/client/src/Utils/Theme/globalTheme.js b/client/src/Utils/Theme/globalTheme.js
new file mode 100644
index 000000000..631f056dd
--- /dev/null
+++ b/client/src/Utils/Theme/globalTheme.js
@@ -0,0 +1,643 @@
+import { typographyLevels } from "./constants";
+const fontFamilyPrimary = '"Inter" , sans-serif';
+// const fontFamilySecondary = '"Avenir", sans-serif';
+
+/* TODO take the color out from here */
+const shadow =
+ "0px 4px 24px -4px rgba(16, 24, 40, 0.08), 0px 3px 3px -3px rgba(16, 24, 40, 0.03)";
+
+const baseTheme = (palette) => ({
+ typography: {
+ fontFamily: fontFamilyPrimary,
+ fontSize: typographyLevels.base,
+ h1: {
+ fontSize: typographyLevels.xl,
+ color: palette.primary.contrastText,
+ fontWeight: 500,
+ },
+ h2: {
+ fontSize: typographyLevels.l,
+ color: palette.primary.contrastTextSecondary,
+ fontWeight: 400,
+ },
+ // CAIO_REVIEW, need a brighter color for dark bg
+ h2DarkBg: {
+ fontSize: typographyLevels.l,
+ color: palette.primary.contrastTextSecondaryDarkBg,
+ fontWeight: 400,
+ },
+ body1: {
+ fontSize: typographyLevels.m,
+ color: palette.primary.contrastTextTertiary,
+ fontWeight: 400,
+ },
+ body2: {
+ fontSize: typographyLevels.s,
+ color: palette.primary.contrastTextTertiary,
+ fontWeight: 400,
+ },
+ },
+ /* TODO change to 4 */
+ spacing: 2,
+ /* TODO we can skip using the callback functions on the next lines since we are already accessing it on line 10. That was the last thing I managed to do, so we are sort of doing it twice*/
+ /* TODO All these should live inside of a component*/
+ components: {
+ MuiButton: {
+ defaultProps: {
+ disableRipple: true,
+ },
+
+ styleOverrides: {
+ root: ({ theme }) => ({
+ variants: [
+ {
+ props: (props) => props.color === "accent",
+ style: {
+ "&:hover": {
+ backgroundColor: theme.palette.accent.darker,
+ },
+ },
+ },
+ {
+ props: (props) => props.color === "error",
+ style: {
+ "&.Mui-disabled": {
+ backgroundColor: theme.palette.error.lowContrast,
+ },
+ "& .MuiButton-loadingIndicator": {
+ // styles for error variant loading indicator
+ color: theme.palette.error.contrastText,
+ },
+ },
+ },
+ {
+ props: (props) => props.variant === "group",
+ style: {
+ /* color: theme.palette.secondary.contrastText, */
+ color: theme.palette.primary.contrastText,
+ backgroundColor: theme.palette.primary.main,
+ border: 1,
+ borderStyle: "solid",
+ borderColor: theme.palette.primary.lowContrast,
+ },
+ },
+ {
+ props: (props) => props.variant === "group" && props.filled === "true",
+ style: {
+ backgroundColor: theme.palette.secondary.main,
+ },
+ },
+ /* {
+ props: (props) => props.variant === "contained",
+ style: {
+ backgroundColor: `${theme.palette.accent.main} !important`,
+ },
+ }, */
+
+ {
+ props: (props) =>
+ props.variant === "contained" && props.color === "secondary",
+ style: {
+ border: 1,
+ borderStyle: "solid",
+ borderColor: theme.palette.primary.lowContrast,
+ },
+ },
+ {
+ props: (props) => {
+ return (
+ props.variant === "contained" &&
+ props.disabled &&
+ props?.classes?.loadingIndicator === undefined // Do not apply to loading button
+ );
+ },
+ style: {
+ backgroundColor: `${theme.palette.secondary.main} !important`,
+ color: `${theme.palette.secondary.contrastText} !important`,
+ },
+ },
+
+ {
+ props: { variant: "text", color: "info" },
+ style: {
+ textDecoration: "underline",
+ color: theme.palette.primary.contrastText,
+ padding: 0,
+ margin: 0,
+ fontSize: typographyLevels.m,
+ fontWeight: theme.typography.body2.fontWeight,
+ backgroundColor: "transparent",
+ "&:hover": {
+ backgroundColor: "transparent",
+ textDecoration: "underline",
+ },
+ "&.Mui-disabled": {
+ backgroundColor: "transparent",
+ color: theme.palette.text.primary,
+ opacity: 0.5,
+ "&.MuiButton-text": {
+ backgroundColor: "transparent",
+ },
+ },
+ minWidth: 0,
+ boxShadow: "none",
+ border: "none",
+ },
+ },
+ ],
+ height: 34,
+ fontWeight: 400,
+ borderRadius: 4,
+ boxShadow: "none",
+ textTransform: "none",
+ "&:focus": {
+ outline: "none",
+ },
+ "&:hover": {
+ boxShadow: "none",
+ },
+ "&.Mui-disabled": {
+ backgroundColor: theme.palette.secondary.main,
+ color: theme.palette.primary.contrastText,
+ },
+ "&.MuiButton-root": {
+ "&:disabled": {
+ backgroundColor: theme.palette.secondary.main,
+ color: theme.palette.primary.contrastText,
+ },
+ "&.MuiButton-colorAccent:hover": {
+ boxShadow: `0 0 0 1px ${theme.palette.accent.main}`, // CAIO_REVIEW, this should really have a solid BG color
+ },
+ },
+ "&.MuiButton-loading": {
+ "&:disabled": {
+ color: "transparent",
+ },
+
+ "& .MuiButton-loadingIndicator": {
+ color: theme.palette.primary.contrastText,
+ },
+ },
+ }),
+ },
+ },
+
+ MuiIconButton: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ padding: 4,
+ transition: "none",
+ "&:hover": {
+ backgroundColor: theme.palette.primary.lowContrast,
+ },
+ }),
+ },
+ },
+ MuiPaper: {
+ styleOverrides: {
+ root: ({ theme }) => {
+ return {
+ marginTop: 4,
+ padding: 0,
+ border: 1,
+ borderStyle: "solid",
+ borderColor: theme.palette.primary.lowContrast,
+ borderRadius: 4,
+ boxShadow: shadow,
+ backgroundColor: theme.palette.primary.main,
+ backgroundImage: "none",
+ };
+ },
+ },
+ },
+ MuiList: {
+ styleOverrides: {
+ root: {
+ padding: 0,
+ },
+ },
+ },
+ MuiListItemButton: {
+ styleOverrides: {
+ root: {
+ transition: "none",
+ },
+ },
+ },
+ MuiListItemText: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ "& .MuiTypography-root": {
+ color: theme.palette.primary.contrastText,
+ },
+ }),
+ },
+ },
+ MuiMenuItem: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ borderRadius: 4,
+ backgroundColor: "inherit",
+ padding: "4px 6px",
+ color: theme.palette.primary.contrastTextSecondary,
+ fontSize: 13,
+ margin: 2,
+ minWidth: 100,
+ "&:hover, &.Mui-selected, &.Mui-selected:hover, &.Mui-selected.Mui-focusVisible":
+ {
+ backgroundColor: theme.palette.primary.lowContrast,
+ },
+ }),
+ },
+ },
+ MuiTableCell: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ fontSize: typographyLevels.base,
+ borderBottomColor: theme.palette.primary.lowContrast,
+ }),
+ },
+ },
+ MuiTableHead: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ backgroundColor: theme.palette.tertiary.main,
+ }),
+ },
+ },
+ MuiPagination: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ backgroundColor: theme.palette.primary.main,
+ border: 1,
+ borderStyle: "solid",
+ borderColor: theme.palette.primary.lowContrast,
+ "& button": {
+ color: theme.palette.primary.contrastTextTertiary,
+ borderRadius: 4,
+ },
+ "& li:first-of-type button, & li:last-of-type button": {
+ border: 1,
+ borderStyle: "solid",
+ borderColor: theme.palette.primary.lowContrast,
+ },
+ }),
+ },
+ },
+ MuiPaginationItem: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ "&:not(.MuiPaginationItem-ellipsis):hover, &.Mui-selected": {
+ backgroundColor: theme.palette.primary.lowContrast,
+ },
+ }),
+ },
+ },
+ MuiSkeleton: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ backgroundColor: theme.palette.primary.lowContrast,
+ }),
+ },
+ },
+
+ MuiTextField: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ "& fieldset": {
+ borderColor: theme.palette.primary.contrastBorder,
+ borderRadius: theme.shape.borderRadius,
+ },
+
+ "& .MuiInputBase-input": {
+ padding: ".75em",
+ minHeight: "var(--env-var-height-2)",
+ fontSize: "var(--env-var-font-size-medium)",
+ fontWeight: 400,
+ color: palette.primary.contrastTextSecondary,
+ "&.Mui-disabled": {
+ opacity: 0.3,
+ WebkitTextFillColor: "unset",
+ },
+ "& .Mui-focused": {
+ /* color: "#ff0000", */
+ /* borderColor: theme.palette.primary.contrastText, */
+ },
+ },
+ "& .MuiInputBase-input:-webkit-autofill": {
+ transition: "background-color 5000s ease-in-out 0s",
+ WebkitBoxShadow: `0 0 0px 1000px ${theme.palette.primary.main} inset`,
+ WebkitTextFillColor: theme.palette.primary.contrastText,
+ },
+ "& .MuiInputBase-input.MuiOutlinedInput-input": {
+ padding: "0 var(--env-var-spacing-1-minus) !important",
+ },
+ "& .MuiOutlinedInput-root": {
+ color: theme.palette.primary.contrastTextSecondary,
+ borderRadius: 4,
+ },
+ "& .MuiOutlinedInput-notchedOutline": {
+ borderRadius: 4,
+ },
+
+ "& .MuiFormHelperText-root": {
+ color: palette.error.main,
+ opacity: 0.8,
+ fontSize: "var(--env-var-font-size-medium)",
+ marginLeft: 0,
+ },
+ "& .MuiFormHelperText-root.Mui-error": {
+ opacity: 0.8,
+ fontSize: "var(--env-var-font-size-medium)",
+ color: palette.error.main,
+ whiteSpace: "nowrap",
+ },
+ }),
+ },
+ },
+ MuiOutlinedInput: {
+ styleOverrides: {
+ root: {
+ "&.Mui-disabled .MuiOutlinedInput-notchedOutline": {
+ borderColor: palette.primary.contrastBorderDisabled,
+ },
+ "&.Mui-disabled:hover .MuiOutlinedInput-notchedOutline": {
+ borderColor: palette.primary.contrastBorderDisabled,
+ },
+ "&:hover .MuiOutlinedInput-notchedOutline": {
+ borderColor: palette.primary.contrastText, // Adjust hover border color
+ },
+ "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
+ borderColor: palette.accent.main, // Adjust focus border color
+ },
+ color: palette.primary.contrastTextTertiary,
+ },
+ },
+ },
+ MuiTab: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ color: theme.palette.tertiary.contrastText,
+ height: "34px",
+ minHeight: "34px",
+ borderRadius: 0,
+ textTransform: "none",
+ minWidth: "fit-content",
+ padding: `${theme.spacing(6)}px ${theme.spacing(4)}px`,
+ fontWeight: 400,
+ "&:focus-visible": {
+ color: theme.palette.primary.contrastText,
+ borderColor: theme.palette.tertiary.contrastText,
+ borderRightColor: theme.palette.primary.lowContrast,
+ },
+ "&.Mui-selected": {
+ color: theme.palette.secondary.contrastText,
+ },
+ "&:hover": {
+ borderColor: theme.palette.primary.lowContrast,
+ },
+ }),
+ },
+ variants: [
+ {
+ props: { orientation: "vertical" },
+ style: ({ theme }) => ({
+ alignItems: "flex-start",
+ padding: `${theme.spacing(1)}px ${theme.spacing(2)}px ${theme.spacing(1)}px ${theme.spacing(6)}px`,
+ minHeight: theme.spacing(12),
+ color: theme.palette.primary.contrastText,
+ backgroundColor: theme.palette.primary.main,
+ border: "none",
+ borderBottom: "none",
+ borderRight: "none",
+ borderRadius: theme.shape.borderRadius * 3,
+ margin: `${theme.spacing(1)}px ${theme.spacing(2)}px`,
+ "&.Mui-selected": {
+ color: theme.palette.primary.contrastText,
+ backgroundColor: theme.palette.tertiary.main,
+ opacity: 1,
+ border: "none",
+ borderBottom: "none",
+ borderRight: "none",
+ borderRadius: theme.shape.borderRadius * 3,
+ minHeight: theme.spacing(14),
+ },
+ "&:hover": {
+ backgroundColor: theme.palette.tertiary.main,
+ border: "none",
+ borderRadius: theme.shape.borderRadius * 3,
+ minHeight: theme.spacing(14),
+ },
+ }),
+ },
+ ],
+ },
+ MuiSvgIcon: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ color: theme.palette.primary.contrastTextTertiary,
+ }),
+ },
+ },
+ MuiTabs: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ display: "inline-flex",
+ borderRadius: 0,
+ "& .MuiTabs-indicator": {
+ backgroundColor: theme.palette.tertiary.contrastText,
+ },
+ }),
+ },
+ variants: [
+ {
+ props: { orientation: "vertical" },
+ style: {
+ "& .MuiTabs-indicator": {
+ display: "none",
+ },
+ },
+ },
+ ],
+ },
+ MuiSwitch: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ width: 42,
+ height: 26,
+ padding: 0,
+ "& .MuiSwitch-switchBase": {
+ padding: 0,
+ margin: 2,
+ transitionDuration: "300ms",
+ "&.Mui-checked": {
+ transform: "translateX(16px)",
+ color: "#fff",
+ "& + .MuiSwitch-track": {
+ backgroundColor: theme.palette.accent.main,
+ opacity: 1,
+ border: 0,
+ },
+ },
+ },
+ "& .MuiSwitch-thumb": {
+ boxSizing: "border-box",
+ width: 22,
+ height: 22,
+ },
+ "& .MuiSwitch-track": {
+ borderRadius: 13,
+ backgroundColor: theme.palette.secondary.light,
+ opacity: 1,
+ },
+ }),
+ },
+ },
+ MuiSelect: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ "& .MuiOutlinedInput-input": {
+ color: theme.palette.primary.contrastText,
+ },
+ "& .MuiOutlinedInput-notchedOutline": {
+ borderColor: theme.palette.primary.lowContrast,
+ borderRadius: theme.shape.borderRadius,
+ },
+ "& .MuiSelect-icon": {
+ color: theme.palette.primary.contrastTextSecondary, // Dropdown + color
+ },
+ "&:hover": {
+ backgroundColor: theme.palette.primary.main, // Background on hover
+ },
+ "&:hover .MuiOutlinedInput-notchedOutline": {
+ borderColor: theme.palette.primary.lowContrast,
+ },
+ }),
+ },
+ },
+ MuiButtonGroup: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ ml: "auto",
+ "& .MuiButtonBase-root, & .MuiButtonBase-root:hover": {
+ borderColor: theme.palette.primary.contrastBorder,
+ width: "auto",
+ whiteSpace: "nowrap",
+ },
+ }),
+ },
+ },
+
+ // This code is added for clock in maintenance page
+ // code starts from here.
+ MuiClock: {
+ // Directly target the clock component
+ styleOverrides: {
+ root: ({ theme }) => ({
+ backgroundColor: theme.palette.primary.main, // Alternative target
+ "& .MuiClock-clock": {
+ // Inner clock face
+ backgroundColor: theme.palette.secondary.main,
+ },
+ }),
+ },
+ },
+ MuiClockPicker: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ backgroundColor: theme.palette.secondary.main, // Outer container background
+ "& .MuiClock-root": {
+ color: theme.palette.primary.lowContrast,
+ },
+ "& .MuiClock-clock": {
+ backgroundColor: theme.palette.background.default, // Clock face background
+ borderColor: theme.palette.secondary.lowContrast,
+ },
+ }),
+ },
+ },
+ // The clock pointer ( pointer to number like hour/minute hand)
+ MuiClockPointer: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ // Main pointer line color
+ backgroundColor: theme.palette.accent.main,
+ "& .MuiClockPointer-thumb": {
+ backgroundColor: theme.palette.grey[500], // Use your desired grey
+ },
+ }),
+ },
+ },
+ // This is for numbers in the clock (circular one's)
+ MuiClockNumber: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ color: theme.palette.primary.contrastText,
+ "&.Mui-selected": {
+ color: theme.palette.accent.contrastText,
+ backgroundColor: theme.palette.accent.main,
+ },
+ }),
+ },
+ },
+ // This is for 00:00 am and pm (top bar)
+ MuiTimePickerToolbar: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ backgroundColor: theme.palette.secondary.lowContrast,
+ // General text color
+ "& .MuiTypography-root": {
+ color: theme.palette.primary.contrastTextTertiary,
+ },
+ // Selected time (hour/minute) color
+ "& .Mui-selected": {
+ color: `${theme.palette.accent.main} !important`,
+ },
+ // AM/PM buttons color
+ "& .MuiButtonBase-root": {
+ "&.Mui-selected": {
+ backgroundColor: theme.palette.accent.main,
+ },
+ },
+ }),
+ },
+ },
+ // left and right direction style
+ MuiPickersArrowSwitcher: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ "& .MuiIconButton-root": {
+ color: theme.palette.primary.contrastText,
+ },
+ }),
+ },
+ },
+ // cancel and okay actions style
+ MuiDialogActions: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ backgroundColor: theme.palette.primary.main,
+ }),
+ },
+ },
+ // code ends here.
+
+ // For labels of input fields
+ MuiInputLabel: {
+ styleOverrides: {
+ root: ({ theme }) => ({
+ "&.Mui-focused": {
+ color: theme.palette.accent.main,
+ },
+ }),
+ },
+ },
+ },
+ shape: {
+ borderRadius: 2,
+ borderThick: 2,
+ boxShadow: shadow,
+ },
+});
+
+export { baseTheme };
diff --git a/Client/src/Utils/Theme/lightTheme.js b/client/src/Utils/Theme/lightTheme.js
similarity index 100%
rename from Client/src/Utils/Theme/lightTheme.js
rename to client/src/Utils/Theme/lightTheme.js
diff --git a/client/src/Utils/debounce.jsx b/client/src/Utils/debounce.jsx
new file mode 100644
index 000000000..11d639f14
--- /dev/null
+++ b/client/src/Utils/debounce.jsx
@@ -0,0 +1,18 @@
+import { useState, useEffect } from "react";
+
+const useDebounce = (value, delay) => {
+ const [debouncedValue, setDebouncedValue] = useState(value);
+
+ useEffect(() => {
+ const handler = setTimeout(() => {
+ setDebouncedValue(value);
+ }, delay);
+
+ return () => {
+ clearTimeout(handler);
+ };
+ }, [value, delay]);
+ return debouncedValue;
+};
+
+export default useDebounce;
diff --git a/Client/src/Utils/fileUtils.js b/client/src/Utils/fileUtils.js
similarity index 100%
rename from Client/src/Utils/fileUtils.js
rename to client/src/Utils/fileUtils.js
diff --git a/Client/src/Utils/greeting.jsx b/client/src/Utils/greeting.jsx
similarity index 94%
rename from Client/src/Utils/greeting.jsx
rename to client/src/Utils/greeting.jsx
index 0193ae688..269d4c73b 100644
--- a/Client/src/Utils/greeting.jsx
+++ b/client/src/Utils/greeting.jsx
@@ -3,6 +3,7 @@ import { useTheme } from "@emotion/react";
import { Box, Typography } from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import { useEffect } from "react";
+import { useTranslation } from "react-i18next";
import { setGreeting } from "../Features/UI/uiSlice";
const early = [
@@ -133,6 +134,7 @@ const evening = [
const Greeting = ({ type = "" }) => {
const theme = useTheme();
const dispatch = useDispatch();
+ const { t } = useTranslation();
const { firstName } = useSelector((state) => state.auth.user);
const index = useSelector((state) => state.ui.greeting.index);
const lastUpdate = useSelector((state) => state.ui.greeting.lastUpdate);
@@ -147,7 +149,7 @@ const Greeting = ({ type = "" }) => {
let random = Math.floor(Math.random() * 5);
dispatch(setGreeting({ index: random, lastUpdate: hour }));
}
- }, [dispatch, hour]);
+ }, [dispatch, hour, lastUpdate]);
let greetingArray =
hour < 6 ? early : hour < 12 ? morning : hour < 18 ? afternoon : evening;
@@ -165,7 +167,7 @@ const Greeting = ({ type = "" }) => {
fontSize="inherit"
color={theme.palette.primary.contrastTextTertiary}
>
- {prepend},{" "}
+ {t("greeting.prepend", { defaultValue: prepend })}, {" "}
{
lineHeight={1}
color={theme.palette.primary.contrastTextTertiary}
>
- {append} — Here’s an overview of your {type} monitors.
+ {t("greeting.append", { defaultValue: append })} — {t("greeting.overview", { type: t(`menu.${type}`) })}
);
diff --git a/client/src/Utils/i18n.js b/client/src/Utils/i18n.js
new file mode 100644
index 000000000..985762a4e
--- /dev/null
+++ b/client/src/Utils/i18n.js
@@ -0,0 +1,37 @@
+import i18n from "i18next";
+import { initReactI18next } from "react-i18next";
+import { setLanguage } from "../Features/UI/uiSlice";
+import store from "../store";
+
+const primaryLanguage = "gb";
+
+const translations = import.meta.glob("../locales/*.json", { eager: true });
+
+const resources = {};
+Object.keys(translations).forEach((path) => {
+ const langCode = path.match(/\/([^/]+)\.json$/)[1];
+ resources[langCode] = {
+ translation: translations[path].default || translations[path],
+ };
+});
+
+const savedLanguage = store.getState()?.ui?.language;
+const initialLanguage = savedLanguage;
+
+i18n.use(initReactI18next).init({
+ resources,
+ lng: initialLanguage,
+ fallbackLng: primaryLanguage,
+ debug: import.meta.env.MODE === "development",
+ ns: ["translation"],
+ defaultNS: "translation",
+ interpolation: {
+ escapeValue: false,
+ },
+});
+
+i18n.on("languageChanged", (lng) => {
+ store.dispatch(setLanguage(lng));
+});
+
+export default i18n;
diff --git a/Client/src/Utils/monitorUtils.js b/client/src/Utils/monitorUtils.js
similarity index 100%
rename from Client/src/Utils/monitorUtils.js
rename to client/src/Utils/monitorUtils.js
diff --git a/client/src/Utils/stringUtils.js b/client/src/Utils/stringUtils.js
new file mode 100644
index 000000000..bb62d0169
--- /dev/null
+++ b/client/src/Utils/stringUtils.js
@@ -0,0 +1,46 @@
+/**
+ * Helper function to get first letter capitalized string
+ * @param {string} str String whose first letter is to be capitalized
+ * @returns A string with first letter capitalized
+ */
+export const capitalizeFirstLetter = (str) => {
+ if (str === null || str === undefined) {
+ return "";
+ }
+ if (typeof str !== "string") {
+ throw new TypeError("Input must be a string");
+ }
+ if (str.length === 0) {
+ return "";
+ }
+ return str.charAt(0).toUpperCase() + str.slice(1);
+};
+
+/**
+ * Helper function to get first letter as a lower case string
+ * @param {string} str String whose first letter is to be lower cased
+ * @returns A string with first letter lower cased
+ */
+
+export const toLowerCaseFirstLetter = (str) => {
+ if (str === null || str === undefined) {
+ return "";
+ }
+ if (typeof str !== "string") {
+ throw new TypeError("Input must be a string");
+ }
+ if (str.length === 0) {
+ return "";
+ }
+ return str.charAt(0).toLowerCase() + str.slice(1);
+};
+
+/**
+ * Checks if a string is null, undefined, or empty (including strings with only whitespace).
+ * @param {string} str - The string to check.
+ * @returns {boolean} - Returns true if the string is null, undefined, or empty.
+ */
+export const isEmpty = (str) => {
+ // Check if string is null, undefined, or empty (including whitespace only)
+ return str === null || typeof str === "undefined" || str.trim().length === 0;
+};
diff --git a/Client/src/Utils/timeUtils.js b/client/src/Utils/timeUtils.js
similarity index 74%
rename from Client/src/Utils/timeUtils.js
rename to client/src/Utils/timeUtils.js
index 1a84d0ea5..3a84dfcf4 100644
--- a/Client/src/Utils/timeUtils.js
+++ b/client/src/Utils/timeUtils.js
@@ -1,4 +1,5 @@
import dayjs from "dayjs";
+import duration from "dayjs/plugin/duration";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import customParseFormat from "dayjs/plugin/customParseFormat";
@@ -6,6 +7,7 @@ import customParseFormat from "dayjs/plugin/customParseFormat";
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(customParseFormat);
+dayjs.extend(duration);
export const MS_PER_SECOND = 1000;
export const MS_PER_MINUTE = 60 * MS_PER_SECOND;
@@ -75,6 +77,26 @@ export const formatDurationSplit = (ms) => {
: { time: 0, format: "seconds" };
};
+export const getHumanReadableDuration = (ms) => {
+ const durationObj = dayjs.duration(ms);
+ if (durationObj.asDays() >= 1) {
+ const days = Math.floor(durationObj.asDays());
+ return { time: days, units: days === 1 ? "day" : "days" };
+ } else if (durationObj.asHours() >= 1) {
+ const hoursRounded = Math.round(durationObj.asHours() * 10) / 10;
+ const hours = Number.isInteger(hoursRounded)
+ ? Math.floor(hoursRounded)
+ : hoursRounded;
+ return { time: hours, units: hours <= 1 ? "hour" : "hours" };
+ } else if (durationObj.asMinutes() >= 1) {
+ const minutes = Math.floor(durationObj.asMinutes());
+ return { time: minutes, units: minutes === 1 ? "minute" : "minutes" };
+ } else {
+ const seconds = Math.floor(durationObj.asSeconds());
+ return { time: seconds, units: seconds === 1 ? "second" : "seconds" };
+ }
+};
+
export const formatDate = (date, customOptions) => {
const options = {
year: "numeric",
diff --git a/Client/src/Utils/timezones.json b/client/src/Utils/timezones.json
similarity index 100%
rename from Client/src/Utils/timezones.json
rename to client/src/Utils/timezones.json
diff --git a/Client/src/Utils/toastUtils.jsx b/client/src/Utils/toastUtils.jsx
similarity index 97%
rename from Client/src/Utils/toastUtils.jsx
rename to client/src/Utils/toastUtils.jsx
index 5920d06a7..dbec9117e 100644
--- a/Client/src/Utils/toastUtils.jsx
+++ b/client/src/Utils/toastUtils.jsx
@@ -12,7 +12,7 @@ import Alert from "../Components/Alert";
*/
export const createToast = ({
- variant = "secondary",
+ variant = "info",
title,
body,
hasIcon = false,
diff --git a/client/src/Utils/utils.js b/client/src/Utils/utils.js
new file mode 100644
index 000000000..8bd9c9019
--- /dev/null
+++ b/client/src/Utils/utils.js
@@ -0,0 +1,7 @@
+export const safelyParseFloat = (value) => {
+ const parsedValue = parseFloat(value);
+ if (isNaN(parsedValue)) {
+ return 0;
+ }
+ return parsedValue;
+};
diff --git a/Client/src/Validation/error.js b/client/src/Validation/error.js
similarity index 74%
rename from Client/src/Validation/error.js
rename to client/src/Validation/error.js
index 017fa9a46..8f043f997 100644
--- a/Client/src/Validation/error.js
+++ b/client/src/Validation/error.js
@@ -1,6 +1,16 @@
+/**
+ * Update errors if passed id matches the error.details[0].path, otherwise remove
+ * the error for the id
+ * @param {*} prev Previous errors *
+ * @param {*} id ID of the field whose error is to be either updated or removed
+ * @param {*} error the error object
+ * @returns the Update Errors with the specific field with id being either removed or updated
+ */
+
+
const buildErrors = (prev, id, error) => {
const updatedErrors = { ...prev };
- if (error) {
+ if (error && id == error.details[0].path) {
updatedErrors[id] = error.details[0].message ?? "Validation error";
} else {
delete updatedErrors[id];
@@ -32,7 +42,15 @@ const getTouchedFieldErrors = (validation, touchedErrors) => {
return newErrors;
};
-
+/**
+ *
+ * @param {*} form The form object of the submitted form data
+ * @param {*} validation The Joi validation rules
+ * @param {*} setErrors The function used to set the local errors
+ * @returns true if there is no error or false if there is error after validating the form
+ * the error will be reset to {} if returns false; otherwise the errors object will be set with
+ * the new value
+ */
const hasValidationErrors = (form, validation, setErrors) => {
const { error } = validation.validate(form, {
abortEarly: false,
@@ -48,6 +66,10 @@ const hasValidationErrors = (form, validation, setErrors) => {
"refreshTokenTTL",
"jwtTTL",
"notify-email-list",
+ "_id",
+ "__v",
+ "createdAt",
+ "updatedAt"
].includes(err.path[0])
) {
newErrors[err.path[0]] = err.message ?? "Validation error";
@@ -66,8 +88,6 @@ const hasValidationErrors = (form, validation, setErrors) => {
newErrors["usage_temperature"] = null;
}
});
-
- console.log("newErrors", newErrors);
if (Object.values(newErrors).some((v) => v)) {
setErrors(newErrors);
return true;
@@ -76,6 +96,7 @@ const hasValidationErrors = (form, validation, setErrors) => {
return false;
}
}
+ setErrors({});
return false;
};
export { buildErrors, hasValidationErrors, getTouchedFieldErrors };
diff --git a/Client/src/Validation/validation.js b/client/src/Validation/validation.js
similarity index 54%
rename from Client/src/Validation/validation.js
rename to client/src/Validation/validation.js
index e40a9c174..be6cb19f7 100644
--- a/Client/src/Validation/validation.js
+++ b/client/src/Validation/validation.js
@@ -7,11 +7,23 @@ const nameSchema = joi
.string()
.max(50)
.trim()
- .pattern(/^[A-Za-z]+$/)
+ .pattern(/^[\p{L}\p{M}''\- ]+$/u)
.messages({
"string.empty": "Name is required",
- "string.max": "Name must be less than 50 characters long",
- "string.pattern.base": "Name must contain only letters",
+ "string.max": "Name must be less than 50 characters",
+ "string.pattern.base":
+ "Name must contain only letters, spaces, apostrophes, or hyphens",
+ });
+
+const lastnameSchema = joi
+ .string()
+ .max(50)
+ .trim()
+ .pattern(/^[\p{L}\p{M}''\- ]+$/u)
+ .messages({
+ "string.empty": "Surname is required",
+ "string.max": "Surname must be less than 50 characters",
+ "string.pattern.base": "Surname must contain only letters, spaces, apostrophes, or hyphens"
});
const passwordSchema = joi
@@ -53,7 +65,7 @@ const passwordSchema = joi
const credentials = joi.object({
firstName: nameSchema,
- lastName: nameSchema,
+ lastName: lastnameSchema,
email: joi
.string()
.trim()
@@ -66,8 +78,8 @@ const credentials = joi.object({
return lowercasedValue;
})
.messages({
- "string.empty": "Email is required",
- "string.email": "Must be a valid email address",
+ "string.empty": "authRegisterEmailRequired",
+ "string.email": "authRegisterEmailInvalid",
}),
password: passwordSchema,
newPassword: passwordSchema,
@@ -92,66 +104,93 @@ const credentials = joi.object({
const monitorValidation = joi.object({
url: joi
- .string()
- .trim()
- .custom((value, helpers) => {
- // Regex from https://gist.github.com/dperini/729294
- var urlRegex = new RegExp(
- "^" +
- // protocol identifier (optional)
- // short syntax // still required
- "(?:(?:https?|ftp):\\/\\/)?" +
- // user:pass BasicAuth (optional)
- "(?:" +
- // IP address dotted notation octets
- // excludes loopback network 0.0.0.0
- // excludes reserved space >= 224.0.0.0
- // excludes network & broadcast addresses
- // (first & last IP address of each class)
- "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
- "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
- "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
- "|" +
- // host & domain names, may end with dot
- // can be replaced by a shortest alternative
- // (?![-_])(?:[-\\w\\u00a1-\\uffff]{0,63}[^-_]\\.)+
- "(?:" +
- "(?:" +
- "[a-z0-9\\u00a1-\\uffff]" +
- "[a-z0-9\\u00a1-\\uffff_-]{0,62}" +
- ")?" +
- "[a-z0-9\\u00a1-\\uffff]\\." +
- ")+" +
- // TLD identifier name, may end with dot
- "(?:[a-z\\u00a1-\\uffff]{2,}\\.?)" +
- ")" +
- // port number (optional)
- "(?::\\d{2,5})?" +
- // resource path (optional)
- "(?:[/?#]\\S*)?" +
- "$",
- "i"
- );
- if (!urlRegex.test(value)) {
- return helpers.error("string.invalidUrl");
- }
+ .when("type", {
+ is: "docker",
+ then: joi
+ .string()
+ .trim()
+ .regex(/^[a-z0-9]{64}$/),
+ otherwise: joi
+ .string()
+ .trim()
+ .custom((value, helpers) => {
+ // Regex from https://gist.github.com/dperini/729294
+ var urlRegex = new RegExp(
+ "^" +
+ // protocol identifier (optional)
+ // short syntax // still required
+ "(?:(?:https?|ftp):\\/\\/)?" +
+ // user:pass BasicAuth (optional)
+ "(?:" +
+ // IP address dotted notation octets
+ // excludes loopback network 0.0.0.0
+ // excludes reserved space >= 224.0.0.0
+ // excludes network & broadcast addresses
+ // (first & last IP address of each class)
+ "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
+ "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
+ "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
+ "|" +
+ // host & domain names, may end with dot
+ // can be replaced by a shortest alternative
+ // (?![-_])(?:[-\\w\\u00a1-\\uffff]{0,63}[^-_]\\.)+
+ "(?:" +
+ "(?:" +
+ "[a-z0-9\\u00a1-\\uffff]" +
+ "[a-z0-9\\u00a1-\\uffff_-]{0,62}" +
+ ")?" +
+ "[a-z0-9\\u00a1-\\uffff]\\." +
+ ")+" +
+ // TLD identifier name, may end with dot
+ "(?:[a-z\\u00a1-\\uffff]{2,}\\.?)" +
+ ")" +
+ // port number (optional)
+ "(?::\\d{2,5})?" +
+ // resource path (optional)
+ "(?:[/?#]\\S*)?" +
+ "$",
+ "i"
+ );
+ if (!urlRegex.test(value)) {
+ return helpers.error("string.invalidUrl");
+ }
- return value;
+ return value;
+ }),
})
.messages({
"string.empty": "This field is required.",
"string.uri": "The URL you provided is not valid.",
"string.invalidUrl": "Please enter a valid URL with optional port",
+ "string.pattern.base": "Please enter a valid container ID.",
+ }),
+ port: joi
+ .number()
+ .integer()
+ .min(1)
+ .max(65535)
+ .when("type", {
+ is: "port",
+ then: joi.required().messages({
+ "number.base": "Port must be a number.",
+ "number.min": "Port must be at least 1.",
+ "number.max": "Port must be at most 65535.",
+ "any.required": "Port is required for port monitors.",
+ }),
+ otherwise: joi.optional(),
}),
- port: joi.number(),
name: joi.string().trim().max(50).allow("").messages({
"string.max": "This field should not exceed the 50 characters limit.",
}),
type: joi.string().trim().messages({ "string.empty": "This field is required." }),
+ ignoreTlsErrors: joi.boolean(),
interval: joi.number().messages({
"number.base": "Frequency must be a number.",
"any.required": "Frequency is required.",
}),
+ expectedValue: joi.string().allow(""),
+ jsonPath: joi.string().allow(""),
+ matchMethod: joi.string(),
});
const imageValidation = joi.object({
@@ -169,10 +208,76 @@ const imageValidation = joi.object({
}),
});
-const settingsValidation = joi.object({
- ttl: joi.number().required().messages({
- "string.empty": "TTL is required",
+const logoImageValidation = joi
+ .object({
+ src: joi.string(),
+ name: joi.string(),
+ type: joi
+ .string()
+ .valid("image/jpeg", "image/png")
+ .allow(null) // Allow null and empty string
+ .messages({
+ "any.only": "Invalid file format.",
+ "string.empty": "File type required.",
+ })
+ .optional(),
+ size: joi
+ .number()
+ .max(3000000)
+ .allow(null) // Allow null and empty string
+ .messages({
+ "number.base": "File size must be a number.",
+ "number.max": "File size must be less than 3MB.",
+ "number.empty": "File size required.",
+ })
+ .optional(),
+ })
+ .allow(null)
+ .optional(); // Make entire object optional
+
+const statusPageValidation = joi.object({
+ type: joi.string().valid("uptime", "distributed").required(),
+ isPublished: joi.bool(),
+ companyName: joi
+ .string()
+ .trim()
+ .messages({ "string.empty": "Company name is required." }),
+ url: joi
+ .string()
+ .pattern(/^[a-zA-Z0-9_-]+$/) // Only allow alphanumeric, underscore, and hyphen
+ .required()
+ .messages({
+ "string.pattern.base":
+ "URL can only contain letters, numbers, underscores, and hyphens",
+ }),
+ timezone: joi.string().trim().messages({ "string.empty": "Timezone is required." }),
+ color: joi.string().trim().messages({ "string.empty": "Color is required." }),
+ theme: joi.string(),
+ monitors: joi.array().min(1).required().messages({
+ "string.pattern.base": "Must be a valid monitor ID",
+ "array.base": "Monitors must be an array",
+ "array.min": "At least one monitor is required",
+ "array.empty": "At least one monitor is required",
+ "any.required": "At least one monitor is required",
}),
+ subMonitors: joi.array().optional(),
+ logo: logoImageValidation,
+ showUptimePercentage: joi.boolean(),
+ showCharts: joi.boolean(),
+});
+const settingsValidation = joi.object({
+ checkTTL: joi.number().required().messages({
+ "string.empty": "Please enter a value",
+ "number.base": "Please enter a valid number",
+ "any.required": "Please enter a value",
+ }),
+ pagespeedApiKey: joi.string().allow("").optional(),
+ language: joi.string().required(),
+ systemEmailHost: joi.string().allow(""),
+ systemEmailPort: joi.number().allow(null, ""),
+ systemEmailAddress: joi.string().allow(""),
+ systemEmailPassword: joi.string().allow(""),
+ systemEmailUser: joi.string().allow(""),
});
const dayjsValidator = (value, helpers) => {
@@ -273,6 +378,15 @@ const infrastructureMonitorValidation = joi.object({
"number.base": "Frequency must be a number.",
"any.required": "Frequency is required.",
}),
+ notifications: joi.array().items(
+ joi.object({
+ type: joi.string().valid("email").required(),
+ address: joi
+ .string()
+ .email({ tlds: { allow: false } })
+ .required(),
+ })
+ ),
});
export {
@@ -283,4 +397,6 @@ export {
maintenanceWindowValidation,
advancedSettingsValidation,
infrastructureMonitorValidation,
+ statusPageValidation,
+ logoImageValidation,
};
diff --git a/Client/src/assets/Images/Google.png b/client/src/assets/Images/Google.png
similarity index 100%
rename from Client/src/assets/Images/Google.png
rename to client/src/assets/Images/Google.png
diff --git a/Client/src/assets/Images/avatar_placeholder.png b/client/src/assets/Images/avatar_placeholder.png
similarity index 100%
rename from Client/src/assets/Images/avatar_placeholder.png
rename to client/src/assets/Images/avatar_placeholder.png
diff --git a/Client/src/assets/Images/background-grid.svg b/client/src/assets/Images/background-grid.svg
similarity index 100%
rename from Client/src/assets/Images/background-grid.svg
rename to client/src/assets/Images/background-grid.svg
diff --git a/Client/src/assets/Images/bwl-logo.svg b/client/src/assets/Images/bwl-logo.svg
similarity index 100%
rename from Client/src/assets/Images/bwl-logo.svg
rename to client/src/assets/Images/bwl-logo.svg
diff --git a/Client/src/assets/Images/create-placeholder-dark.svg b/client/src/assets/Images/create-placeholder-dark.svg
similarity index 100%
rename from Client/src/assets/Images/create-placeholder-dark.svg
rename to client/src/assets/Images/create-placeholder-dark.svg
diff --git a/Client/src/assets/Images/create-placeholder.svg b/client/src/assets/Images/create-placeholder.svg
similarity index 100%
rename from Client/src/assets/Images/create-placeholder.svg
rename to client/src/assets/Images/create-placeholder.svg
diff --git a/Client/src/assets/Images/data_placeholder.svg b/client/src/assets/Images/data_placeholder.svg
similarity index 100%
rename from Client/src/assets/Images/data_placeholder.svg
rename to client/src/assets/Images/data_placeholder.svg
diff --git a/Client/src/assets/Images/data_placeholder_dark.svg b/client/src/assets/Images/data_placeholder_dark.svg
similarity index 100%
rename from Client/src/assets/Images/data_placeholder_dark.svg
rename to client/src/assets/Images/data_placeholder_dark.svg
diff --git a/client/src/assets/Images/jupiter_logo_banner_dark.svg b/client/src/assets/Images/jupiter_logo_banner_dark.svg
new file mode 100644
index 000000000..3d3e23b14
--- /dev/null
+++ b/client/src/assets/Images/jupiter_logo_banner_dark.svg
@@ -0,0 +1,35 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/client/src/assets/Images/jupiter_logo_banner_light.svg b/client/src/assets/Images/jupiter_logo_banner_light.svg
new file mode 100644
index 000000000..4744e0bcb
--- /dev/null
+++ b/client/src/assets/Images/jupiter_logo_banner_light.svg
@@ -0,0 +1,35 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/client/src/assets/Images/logo_placeholder.svg b/client/src/assets/Images/logo_placeholder.svg
new file mode 100644
index 000000000..82f307b2d
--- /dev/null
+++ b/client/src/assets/Images/logo_placeholder.svg
@@ -0,0 +1,5 @@
+
+
+
+
\ No newline at end of file
diff --git a/client/src/assets/Images/solana_logo_banner_dark.svg b/client/src/assets/Images/solana_logo_banner_dark.svg
new file mode 100644
index 000000000..08ec87cb1
--- /dev/null
+++ b/client/src/assets/Images/solana_logo_banner_dark.svg
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/client/src/assets/Images/solana_logo_banner_light.svg b/client/src/assets/Images/solana_logo_banner_light.svg
new file mode 100644
index 000000000..774018a6a
--- /dev/null
+++ b/client/src/assets/Images/solana_logo_banner_light.svg
@@ -0,0 +1,49 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Client/src/assets/Images/sushi_404.svg b/client/src/assets/Images/sushi_404.svg
similarity index 100%
rename from Client/src/assets/Images/sushi_404.svg
rename to client/src/assets/Images/sushi_404.svg
diff --git a/Client/src/assets/icons/average-response-icon.svg b/client/src/assets/icons/average-response-icon.svg
similarity index 100%
rename from Client/src/assets/icons/average-response-icon.svg
rename to client/src/assets/icons/average-response-icon.svg
diff --git a/client/src/assets/icons/bwu-icon.svg b/client/src/assets/icons/bwu-icon.svg
new file mode 100644
index 000000000..80ab50ad9
--- /dev/null
+++ b/client/src/assets/icons/bwu-icon.svg
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/Client/src/assets/icons/calendar-check.svg b/client/src/assets/icons/calendar-check.svg
similarity index 100%
rename from Client/src/assets/icons/calendar-check.svg
rename to client/src/assets/icons/calendar-check.svg
diff --git a/Client/src/assets/icons/calendar.svg b/client/src/assets/icons/calendar.svg
similarity index 100%
rename from Client/src/assets/icons/calendar.svg
rename to client/src/assets/icons/calendar.svg
diff --git a/Client/src/assets/icons/certificate.svg b/client/src/assets/icons/certificate.svg
similarity index 100%
rename from Client/src/assets/icons/certificate.svg
rename to client/src/assets/icons/certificate.svg
diff --git a/Client/src/assets/icons/changeLog.svg b/client/src/assets/icons/changeLog.svg
similarity index 100%
rename from Client/src/assets/icons/changeLog.svg
rename to client/src/assets/icons/changeLog.svg
diff --git a/Client/src/assets/icons/check-outlined.svg b/client/src/assets/icons/check-outlined.svg
similarity index 100%
rename from Client/src/assets/icons/check-outlined.svg
rename to client/src/assets/icons/check-outlined.svg
diff --git a/Client/src/assets/icons/check.svg b/client/src/assets/icons/check.svg
similarity index 100%
rename from Client/src/assets/icons/check.svg
rename to client/src/assets/icons/check.svg
diff --git a/Client/src/assets/icons/checkbox-filled.svg b/client/src/assets/icons/checkbox-filled.svg
similarity index 100%
rename from Client/src/assets/icons/checkbox-filled.svg
rename to client/src/assets/icons/checkbox-filled.svg
diff --git a/Client/src/assets/icons/checkbox-green.svg b/client/src/assets/icons/checkbox-green.svg
similarity index 100%
rename from Client/src/assets/icons/checkbox-green.svg
rename to client/src/assets/icons/checkbox-green.svg
diff --git a/Client/src/assets/icons/checkbox-outline.svg b/client/src/assets/icons/checkbox-outline.svg
similarity index 100%
rename from Client/src/assets/icons/checkbox-outline.svg
rename to client/src/assets/icons/checkbox-outline.svg
diff --git a/Client/src/assets/icons/checkbox-red.svg b/client/src/assets/icons/checkbox-red.svg
similarity index 100%
rename from Client/src/assets/icons/checkbox-red.svg
rename to client/src/assets/icons/checkbox-red.svg
diff --git a/Client/src/assets/icons/checkmate-icon.svg b/client/src/assets/icons/checkmate-icon.svg
similarity index 100%
rename from Client/src/assets/icons/checkmate-icon.svg
rename to client/src/assets/icons/checkmate-icon.svg
diff --git a/Client/src/assets/icons/clock-snooze.svg b/client/src/assets/icons/clock-snooze.svg
similarity index 100%
rename from Client/src/assets/icons/clock-snooze.svg
rename to client/src/assets/icons/clock-snooze.svg
diff --git a/Client/src/assets/icons/cpu-chip.svg b/client/src/assets/icons/cpu-chip.svg
similarity index 100%
rename from Client/src/assets/icons/cpu-chip.svg
rename to client/src/assets/icons/cpu-chip.svg
diff --git a/Client/src/assets/icons/dashboard.svg b/client/src/assets/icons/dashboard.svg
similarity index 100%
rename from Client/src/assets/icons/dashboard.svg
rename to client/src/assets/icons/dashboard.svg
diff --git a/Client/src/assets/icons/discord-icon.svg b/client/src/assets/icons/discord-icon.svg
similarity index 100%
rename from Client/src/assets/icons/discord-icon.svg
rename to client/src/assets/icons/discord-icon.svg
diff --git a/client/src/assets/icons/discussions.svg b/client/src/assets/icons/discussions.svg
new file mode 100644
index 000000000..293cd51f2
--- /dev/null
+++ b/client/src/assets/icons/discussions.svg
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
diff --git a/client/src/assets/icons/distributed-uptime.svg b/client/src/assets/icons/distributed-uptime.svg
new file mode 100644
index 000000000..e612081e4
--- /dev/null
+++ b/client/src/assets/icons/distributed-uptime.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/Client/src/assets/icons/docs.svg b/client/src/assets/icons/docs.svg
similarity index 100%
rename from Client/src/assets/icons/docs.svg
rename to client/src/assets/icons/docs.svg
diff --git a/Client/src/assets/icons/dots-vertical.svg b/client/src/assets/icons/dots-vertical.svg
similarity index 100%
rename from Client/src/assets/icons/dots-vertical.svg
rename to client/src/assets/icons/dots-vertical.svg
diff --git a/Client/src/assets/icons/down-arrow.svg b/client/src/assets/icons/down-arrow.svg
similarity index 100%
rename from Client/src/assets/icons/down-arrow.svg
rename to client/src/assets/icons/down-arrow.svg
diff --git a/Client/src/assets/icons/edit.svg b/client/src/assets/icons/edit.svg
similarity index 100%
rename from Client/src/assets/icons/edit.svg
rename to client/src/assets/icons/edit.svg
diff --git a/Client/src/assets/icons/email.svg b/client/src/assets/icons/email.svg
similarity index 100%
rename from Client/src/assets/icons/email.svg
rename to client/src/assets/icons/email.svg
diff --git a/Client/src/assets/icons/folder.svg b/client/src/assets/icons/folder.svg
similarity index 100%
rename from Client/src/assets/icons/folder.svg
rename to client/src/assets/icons/folder.svg
diff --git a/client/src/assets/icons/groups.svg b/client/src/assets/icons/groups.svg
new file mode 100644
index 000000000..fa2cae03c
--- /dev/null
+++ b/client/src/assets/icons/groups.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/Client/src/assets/icons/history-icon.svg b/client/src/assets/icons/history-icon.svg
similarity index 100%
rename from Client/src/assets/icons/history-icon.svg
rename to client/src/assets/icons/history-icon.svg
diff --git a/Client/src/assets/icons/incidents.svg b/client/src/assets/icons/incidents.svg
similarity index 100%
rename from Client/src/assets/icons/incidents.svg
rename to client/src/assets/icons/incidents.svg
diff --git a/Client/src/assets/icons/integrations.svg b/client/src/assets/icons/integrations.svg
similarity index 100%
rename from Client/src/assets/icons/integrations.svg
rename to client/src/assets/icons/integrations.svg
diff --git a/Client/src/assets/icons/interval-check.svg b/client/src/assets/icons/interval-check.svg
similarity index 100%
rename from Client/src/assets/icons/interval-check.svg
rename to client/src/assets/icons/interval-check.svg
diff --git a/client/src/assets/icons/jupiter_ag_logo.svg b/client/src/assets/icons/jupiter_ag_logo.svg
new file mode 100644
index 000000000..b344961c8
--- /dev/null
+++ b/client/src/assets/icons/jupiter_ag_logo.svg
@@ -0,0 +1,52 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/client/src/assets/icons/jupiter_logo_banner_dark.svg b/client/src/assets/icons/jupiter_logo_banner_dark.svg
new file mode 100644
index 000000000..3d3e23b14
--- /dev/null
+++ b/client/src/assets/icons/jupiter_logo_banner_dark.svg
@@ -0,0 +1,35 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/client/src/assets/icons/jupiter_logo_banner_light.svg b/client/src/assets/icons/jupiter_logo_banner_light.svg
new file mode 100644
index 000000000..4744e0bcb
--- /dev/null
+++ b/client/src/assets/icons/jupiter_logo_banner_light.svg
@@ -0,0 +1,35 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Client/src/assets/icons/key.svg b/client/src/assets/icons/key.svg
similarity index 100%
rename from Client/src/assets/icons/key.svg
rename to client/src/assets/icons/key.svg
diff --git a/Client/src/assets/icons/left-arrow-double.svg b/client/src/assets/icons/left-arrow-double.svg
similarity index 100%
rename from Client/src/assets/icons/left-arrow-double.svg
rename to client/src/assets/icons/left-arrow-double.svg
diff --git a/Client/src/assets/icons/left-arrow-long.svg b/client/src/assets/icons/left-arrow-long.svg
similarity index 100%
rename from Client/src/assets/icons/left-arrow-long.svg
rename to client/src/assets/icons/left-arrow-long.svg
diff --git a/Client/src/assets/icons/left-arrow.svg b/client/src/assets/icons/left-arrow.svg
similarity index 100%
rename from Client/src/assets/icons/left-arrow.svg
rename to client/src/assets/icons/left-arrow.svg
diff --git a/Client/src/assets/icons/lock.svg b/client/src/assets/icons/lock.svg
similarity index 100%
rename from Client/src/assets/icons/lock.svg
rename to client/src/assets/icons/lock.svg
diff --git a/Client/src/assets/icons/logout.svg b/client/src/assets/icons/logout.svg
similarity index 100%
rename from Client/src/assets/icons/logout.svg
rename to client/src/assets/icons/logout.svg
diff --git a/Client/src/assets/icons/mail.svg b/client/src/assets/icons/mail.svg
similarity index 100%
rename from Client/src/assets/icons/mail.svg
rename to client/src/assets/icons/mail.svg
diff --git a/Client/src/assets/icons/maintenance.svg b/client/src/assets/icons/maintenance.svg
similarity index 100%
rename from Client/src/assets/icons/maintenance.svg
rename to client/src/assets/icons/maintenance.svg
diff --git a/Client/src/assets/icons/monitor-graph-line.svg b/client/src/assets/icons/monitor-graph-line.svg
similarity index 100%
rename from Client/src/assets/icons/monitor-graph-line.svg
rename to client/src/assets/icons/monitor-graph-line.svg
diff --git a/Client/src/assets/icons/monitors.svg b/client/src/assets/icons/monitors.svg
similarity index 100%
rename from Client/src/assets/icons/monitors.svg
rename to client/src/assets/icons/monitors.svg
diff --git a/Client/src/assets/icons/open-in-new-page.svg b/client/src/assets/icons/open-in-new-page.svg
similarity index 100%
rename from Client/src/assets/icons/open-in-new-page.svg
rename to client/src/assets/icons/open-in-new-page.svg
diff --git a/Client/src/assets/icons/page-speed.svg b/client/src/assets/icons/page-speed.svg
similarity index 100%
rename from Client/src/assets/icons/page-speed.svg
rename to client/src/assets/icons/page-speed.svg
diff --git a/Client/src/assets/icons/pause-icon.svg b/client/src/assets/icons/pause-icon.svg
similarity index 100%
rename from Client/src/assets/icons/pause-icon.svg
rename to client/src/assets/icons/pause-icon.svg
diff --git a/Client/src/assets/icons/performance-report.svg b/client/src/assets/icons/performance-report.svg
similarity index 100%
rename from Client/src/assets/icons/performance-report.svg
rename to client/src/assets/icons/performance-report.svg
diff --git a/Client/src/assets/icons/radio-checked.svg b/client/src/assets/icons/radio-checked.svg
similarity index 100%
rename from Client/src/assets/icons/radio-checked.svg
rename to client/src/assets/icons/radio-checked.svg
diff --git a/Client/src/assets/icons/response-time-icon.svg b/client/src/assets/icons/response-time-icon.svg
similarity index 100%
rename from Client/src/assets/icons/response-time-icon.svg
rename to client/src/assets/icons/response-time-icon.svg
diff --git a/Client/src/assets/icons/resume-icon.svg b/client/src/assets/icons/resume-icon.svg
similarity index 100%
rename from Client/src/assets/icons/resume-icon.svg
rename to client/src/assets/icons/resume-icon.svg
diff --git a/Client/src/assets/icons/right-arrow-double.svg b/client/src/assets/icons/right-arrow-double.svg
similarity index 100%
rename from Client/src/assets/icons/right-arrow-double.svg
rename to client/src/assets/icons/right-arrow-double.svg
diff --git a/Client/src/assets/icons/right-arrow.svg b/client/src/assets/icons/right-arrow.svg
similarity index 100%
rename from Client/src/assets/icons/right-arrow.svg
rename to client/src/assets/icons/right-arrow.svg
diff --git a/Client/src/assets/icons/ruler-icon.svg b/client/src/assets/icons/ruler-icon.svg
similarity index 100%
rename from Client/src/assets/icons/ruler-icon.svg
rename to client/src/assets/icons/ruler-icon.svg
diff --git a/Client/src/assets/icons/search.svg b/client/src/assets/icons/search.svg
similarity index 100%
rename from Client/src/assets/icons/search.svg
rename to client/src/assets/icons/search.svg
diff --git a/Client/src/assets/icons/selector-vertical.svg b/client/src/assets/icons/selector-vertical.svg
similarity index 100%
rename from Client/src/assets/icons/selector-vertical.svg
rename to client/src/assets/icons/selector-vertical.svg
diff --git a/Client/src/assets/icons/settings-bold.svg b/client/src/assets/icons/settings-bold.svg
similarity index 100%
rename from Client/src/assets/icons/settings-bold.svg
rename to client/src/assets/icons/settings-bold.svg
diff --git a/Client/src/assets/icons/settings.svg b/client/src/assets/icons/settings.svg
similarity index 100%
rename from Client/src/assets/icons/settings.svg
rename to client/src/assets/icons/settings.svg
diff --git a/Client/src/assets/icons/slack-icon.svg b/client/src/assets/icons/slack-icon.svg
similarity index 100%
rename from Client/src/assets/icons/slack-icon.svg
rename to client/src/assets/icons/slack-icon.svg
diff --git a/client/src/assets/icons/solana_logo.svg b/client/src/assets/icons/solana_logo.svg
new file mode 100644
index 000000000..bd349af26
--- /dev/null
+++ b/client/src/assets/icons/solana_logo.svg
@@ -0,0 +1,28 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/client/src/assets/icons/solana_logo_banner.svg b/client/src/assets/icons/solana_logo_banner.svg
new file mode 100644
index 000000000..08ec87cb1
--- /dev/null
+++ b/client/src/assets/icons/solana_logo_banner.svg
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Client/src/assets/icons/spedometer-icon.svg b/client/src/assets/icons/spedometer-icon.svg
similarity index 100%
rename from Client/src/assets/icons/spedometer-icon.svg
rename to client/src/assets/icons/spedometer-icon.svg
diff --git a/client/src/assets/icons/speedometer-icon.svg b/client/src/assets/icons/speedometer-icon.svg
new file mode 100644
index 000000000..19b13f44e
--- /dev/null
+++ b/client/src/assets/icons/speedometer-icon.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/Client/src/assets/icons/status-pages.svg b/client/src/assets/icons/status-pages.svg
similarity index 100%
rename from Client/src/assets/icons/status-pages.svg
rename to client/src/assets/icons/status-pages.svg
diff --git a/Client/src/assets/icons/support.svg b/client/src/assets/icons/support.svg
similarity index 100%
rename from Client/src/assets/icons/support.svg
rename to client/src/assets/icons/support.svg
diff --git a/Client/src/assets/icons/top-right-arrow.svg b/client/src/assets/icons/top-right-arrow.svg
similarity index 100%
rename from Client/src/assets/icons/top-right-arrow.svg
rename to client/src/assets/icons/top-right-arrow.svg
diff --git a/Client/src/assets/icons/trash-bin.svg b/client/src/assets/icons/trash-bin.svg
similarity index 100%
rename from Client/src/assets/icons/trash-bin.svg
rename to client/src/assets/icons/trash-bin.svg
diff --git a/Client/src/assets/icons/up-arrow.svg b/client/src/assets/icons/up-arrow.svg
similarity index 100%
rename from Client/src/assets/icons/up-arrow.svg
rename to client/src/assets/icons/up-arrow.svg
diff --git a/client/src/assets/icons/upt_logo.png b/client/src/assets/icons/upt_logo.png
new file mode 100644
index 000000000..d443d0897
Binary files /dev/null and b/client/src/assets/icons/upt_logo.png differ
diff --git a/Client/src/assets/icons/uptime-icon.svg b/client/src/assets/icons/uptime-icon.svg
similarity index 100%
rename from Client/src/assets/icons/uptime-icon.svg
rename to client/src/assets/icons/uptime-icon.svg
diff --git a/Client/src/assets/icons/user-edit.svg b/client/src/assets/icons/user-edit.svg
similarity index 100%
rename from Client/src/assets/icons/user-edit.svg
rename to client/src/assets/icons/user-edit.svg
diff --git a/Client/src/assets/icons/user-two.svg b/client/src/assets/icons/user-two.svg
similarity index 100%
rename from Client/src/assets/icons/user-two.svg
rename to client/src/assets/icons/user-two.svg
diff --git a/Client/src/assets/icons/user.svg b/client/src/assets/icons/user.svg
similarity index 100%
rename from Client/src/assets/icons/user.svg
rename to client/src/assets/icons/user.svg
diff --git a/Client/src/assets/icons/zapier-icon.svg b/client/src/assets/icons/zapier-icon.svg
similarity index 100%
rename from Client/src/assets/icons/zapier-icon.svg
rename to client/src/assets/icons/zapier-icon.svg
diff --git a/Client/src/index.css b/client/src/index.css
similarity index 100%
rename from Client/src/index.css
rename to client/src/index.css
diff --git a/client/src/locales/gb.json b/client/src/locales/gb.json
new file mode 100644
index 000000000..3391baec7
--- /dev/null
+++ b/client/src/locales/gb.json
@@ -0,0 +1,539 @@
+{
+ "dontHaveAccount": "Don't have account",
+ "doNotHaveAccount": "Do not have an account?",
+ "registerHere": "Register here",
+ "email": "E-mail",
+ "forgotPassword": "Forgot Password",
+ "password": "Password",
+ "signUp": "Sign Up",
+ "submit": "Submit",
+ "title": "Title",
+ "continue": "Continue",
+ "enterEmail": "Enter your email",
+ "authLoginTitle": "Log In",
+ "authLoginEnterPassword": "Enter your password",
+ "commonPassword": "Password",
+ "commonBack": "Back",
+ "authForgotPasswordTitle": "Forgot password?",
+ "authForgotPasswordResetPassword": "Reset password",
+ "authForgotPasswordInstructions": "No worries, we'll send you reset instructions.",
+ "createPassword": "Create your password",
+ "createAPassword": "Password",
+ "authRegisterAlreadyHaveAccount": "Already have an account?",
+ "authRegisterLoginLink": "Log In",
+ "commonAppName": "Checkmate",
+ "welcomeBack": "Welcome back! You're successfully logged in.",
+ "authLoginEnterEmail": "Enter your email",
+ "authRegisterTitle": "Create an account",
+ "authRegisterStepOneTitle": "Create your account",
+ "authRegisterStepOneDescription": "Enter your details to get started",
+ "authRegisterStepTwoTitle": "Set up your profile",
+ "authRegisterStepTwoDescription": "Tell us more about yourself",
+ "authRegisterStepThreeTitle": "Almost done!",
+ "authRegisterStepThreeDescription": "Review your information",
+ "authForgotPasswordDescription": "No worries, we'll send you reset instructions.",
+ "authForgotPasswordSendInstructions": "Send instructions",
+ "authForgotPasswordBackTo": "Back to",
+ "authCheckEmailTitle": "Check your email",
+ "authCheckEmailDescription": "We sent a password reset link to",
+ "authCheckEmailResendEmail": "Resend email",
+ "authCheckEmailBackTo": "Back to",
+ "goBackTo": "Go back to",
+ "authCheckEmailDidntReceiveEmail": "Didn't receive the email?",
+ "authCheckEmailClickToResend": "Click to resend",
+ "authSetNewPasswordTitle": "Set new password",
+ "authSetNewPasswordDescription": "Your new password must be different from previously used passwords.",
+ "authSetNewPasswordNewPassword": "New password",
+ "authSetNewPasswordConfirmPassword": "Confirm password",
+ "confirmPassword": "Re-enter password to confirm",
+ "authSetNewPasswordResetPassword": "Reset password",
+ "authSetNewPasswordBackTo": "Back to",
+ "authPasswordMustBeAtLeast": "Must be at least",
+ "authPasswordCharactersLong": "8 characters long",
+ "authPasswordMustContainAtLeast": "Must contain at least",
+ "authPasswordSpecialCharacter": "one special character",
+ "authPasswordOneNumber": "one number",
+ "authPasswordUpperCharacter": "one upper character",
+ "authPasswordLowerCharacter": "one lower character",
+ "authPasswordConfirmAndPassword": "Confirm password and password",
+ "authPasswordMustMatch": "Passwords must match",
+ "validationNameRequired": "Please enter your name",
+ "validationNameTooLong": "Name should be less than 50 characters",
+ "validationNameInvalidCharacters": "Please use only letters, spaces, apostrophes, or hyphens",
+ "authRegisterCreateAccount": "Create your account to get started",
+ "authRegisterCreateSuperAdminAccount": "Create your super admin account to get started",
+ "authRegisterSignUpWithEmail": "Create super admin account",
+ "authRegisterBySigningUp": "By creating an account, you agree to our Terms of Service and Privacy Policy .",
+ "distributedStatusHeaderText": "Real-time, real-device coverage",
+ "distributedStatusSubHeaderText": "Powered by millions devices worldwide, view a system performance by global region, country or city",
+ "settingsGeneralSettings": "General settings",
+ "settingsDisplayTimezone": "Display timezone",
+ "settingsDisplayTimezoneDescription": "Select the timezone used to display dates and times throughout the application.",
+ "settingsAppearance": "Appearance",
+ "settingsAppearanceDescription": "Switch between light and dark mode, or change user interface language",
+ "settingsThemeMode": "Theme Mode",
+ "settingsThemeModeLight": "Light",
+ "settingsThemeModeDark": "Dark",
+ "settingsLanguage": "Language",
+ "settingsDistributedUptime": "Distributed uptime",
+ "settingsDistributedUptimeDescription": "Enable/disable distributed uptime monitoring.",
+ "settingsEnabled": "Enabled",
+ "settingsDisabled": "Disabled",
+ "settingsHistoryAndMonitoring": "History of monitoring",
+ "settingsHistoryAndMonitoringDescription": "Define how long you want to retain historical data. You can also clear all existing data.",
+ "settingsTTLLabel": "The days you want to keep monitoring history.",
+ "settingsTTLOptionalLabel": "0 for infinite",
+ "settingsClearAllStats": "Clear all stats. This is irreversible.",
+ "settingsClearAllStatsButton": "Clear all stats",
+ "settingsClearAllStatsDialogTitle": "Do you want to clear all stats?",
+ "settingsClearAllStatsDialogDescription": "Once removed, the monitoring history and stats cannot be retrieved.",
+ "settingsClearAllStatsDialogConfirm": "Yes, clear all stats",
+ "settingsClearAllStatsDialogCancel": "Cancel",
+ "settingsDemoMonitors": "Demo monitors",
+ "settingsDemoMonitorsDescription": "Add sample monitors for demonstration purposes.",
+ "settingsAddDemoMonitors": "Adding demo monitors",
+ "settingsAddDemoMonitorsButton": "Add demo monitors",
+ "settingsSystemReset": "System reset",
+ "settingsSystemResetDescription": "Remove all monitors from your system.",
+ "settingsRemoveAllMonitors": "Removing all monitors",
+ "settingsRemoveAllMonitorsButton": "Remove all monitors",
+ "settingsRemoveAllMonitorsDialogTitle": "Do you want to remove all monitors?",
+ "settingsRemoveAllMonitorsDialogConfirm": "Yes, remove all monitors",
+ "settingsWallet": "Wallet",
+ "settingsWalletDescription": "Connect your wallet here. This is required for the Distributed Uptime monitor to connect to multiple nodes globally.",
+ "settingsAbout": "About",
+ "settingsDevelopedBy": "Developed by Bluewave Labs.",
+ "settingsSave": "Save",
+ "settingsSuccessSaved": "Settings saved successfully",
+ "settingsFailedToSave": "Failed to save settings",
+ "settingsStatsCleared": "Stats cleared successfully",
+ "settingsFailedToClearStats": "Failed to clear stats",
+ "settingsDemoMonitorsAdded": "Successfully added demo monitors",
+ "settingsFailedToAddDemoMonitors": "Failed to add demo monitors",
+ "settingsMonitorsDeleted": "Successfully deleted all monitors",
+ "settingsFailedToDeleteMonitors": "Failed to delete all monitors",
+ "settingsEmail": "Email settings",
+ "settingsEmailDescription": "Configure email settings",
+ "settingsEmailHost": "Email host",
+ "settingsEmailPort": "Email port",
+ "settingsEmailAddress": "Email address",
+ "settingsEmailPassword": "Email password",
+ "settingsEmailUser": "Email user",
+ "settingsEmailFieldResetLabel": "Password is set. Click Reset to change it.",
+ "backendUnreachable": "Server Connection Error",
+ "backendUnreachableMessage": "We're unable to connect to the server. Please check your internet connection or verify your deployment configuration if the problem persists.",
+ "backendUnreachableError": "Cannot connect to the server. Please try again later.",
+ "retryConnection": "Retry connection",
+ "retryingConnection": "Connecting...",
+ "backendReconnected": "Successfully reconnected to the server.",
+ "backendStillUnreachable": "Server is still unreachable. Please try again later.",
+ "backendConnectionError": "Error connecting to the server. Please check your network connection.",
+ "starPromptTitle": "Star Checkmate",
+ "starPromptDescription": "See the latest releases and help grow the community on GitHub",
+ "https": "HTTPS",
+ "http": "HTTP",
+ "monitor": "monitor",
+ "aboutus": "About Us",
+ "state": "State",
+ "now": "Now",
+ "delete": "Delete",
+ "configure": "Configure",
+ "networkError": "Network error",
+ "responseTime": "Response time",
+ "ms": "ms",
+ "bar": "Bar",
+ "area": "Area",
+ "country": "COUNTRY",
+ "city": "CITY",
+ "response": "RESPONSE",
+ "checkConnection": "Please check your connection",
+ "passwordreset": "Password Reset",
+ "authRegisterStepOnePersonalDetails": "Enter your personal details",
+ "authCheckEmailOpenEmailButton": "Open email app",
+ "authNewPasswordConfirmed": "Your password has been successfully reset. Click below to log in magically.",
+ "monitorStatusUp": "Monitor {name} ({url}) is now UP and responding",
+ "monitorStatusDown": "Monitor {name} ({url}) is DOWN and not responding",
+ "webhookSendSuccess": "Webhook notification sent successfully",
+ "webhookSendError": "Error sending webhook notification to {platform}",
+ "webhookUnsupportedPlatform": "Unsupported platform: {platform}",
+ "distributedRightCategoryTitle": "Monitor",
+ "distributedStatusServerMonitors": "Server Monitors",
+ "distributedStatusServerMonitorsDescription": "Monitor status of related servers",
+ "distributedUptimeCreateSelectURL": "Here you can select the URL of the host, together with the type of monitor.",
+ "distributedUptimeCreateChecks": "Checks to perform",
+ "distributedUptimeCreateChecksDescription": "You can always add or remove checks after adding your site.",
+ "distributedUptimeCreateIncidentNotification": "Incident notifications",
+ "distributedUptimeCreateIncidentDescription": "When there is an incident, notify users.",
+ "distributedUptimeCreateAdvancedSettings": "Advanced settings",
+ "distributedUptimeDetailsNoMonitorHistory": "There is no check history for this monitor yet.",
+ "distributedUptimeDetailsFooterHeading": "Made with ❤️ by UpRock & Bluewave Labs",
+ "distributedUptimeDetailsFooterBuilt": "Built on",
+ "distributedUptimeDetailsFooterSolana": "Solana",
+ "distributedUptimeDetailsMonitorHeader": "Distributed Uptime Monitoring powered by DePIN",
+ "distributedUptimeDetailsStatusHeaderUptime": "Uptime:",
+ "distributedUptimeDetailsStatusHeaderLastUpdate": "Last updated",
+ "notifications": {
+ "enableNotifications": "Enable {{platform}} notifications",
+ "testNotification": "Test notification",
+ "addOrEditNotifications": "Add or edit notifications",
+ "slack": {
+ "label": "Slack",
+ "description": "To enable Slack notifications, create a Slack app and enable incoming webhooks. After that, simply provide the webhook URL here.",
+ "webhookLabel": "Webhook URL",
+ "webhookPlaceholder": "https://hooks.slack.com/services/...",
+ "webhookRequired": "Slack webhook URL is required"
+ },
+ "discord": {
+ "label": "Discord",
+ "description": "To send data to a Discord channel from Checkmate via Discord notifications using webhooks, you can use Discord's incoming Webhooks feature.",
+ "webhookLabel": "Discord Webhook URL",
+ "webhookPlaceholder": "https://discord.com/api/webhooks/...",
+ "webhookRequired": "Discord webhook URL is required"
+ },
+ "telegram": {
+ "label": "Telegram",
+ "description": "To enable Telegram notifications, create a Telegram bot using BotFather, an official bot for creating and managing Telegram bots. Then, get the API token and chat ID and write them down here.",
+ "tokenLabel": "Your bot token",
+ "tokenPlaceholder": "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11",
+ "chatIdLabel": "Your Chat ID",
+ "chatIdPlaceholder": "-1001234567890",
+ "fieldsRequired": "Telegram token and chat ID are required"
+ },
+ "webhook": {
+ "label": "Webhooks",
+ "description": "You can set up a custom webhook to receive notifications when incidents occur.",
+ "urlLabel": "Webhook URL",
+ "urlPlaceholder": "https://your-server.com/webhook",
+ "urlRequired": "Webhook URL is required"
+ },
+ "testNotificationDevelop": "Test notification 2",
+ "integrationButton": "Notification Integration",
+ "testSuccess": "Test notification sent successfully!",
+ "testFailed": "Failed to send test notification",
+ "unsupportedType": "Unsupported notification type",
+ "networkError": "Network error occurred"
+ },
+ "testLocale": "testLocale",
+ "add": "Add",
+ "monitors": "monitors",
+ "distributedUptimeStatusCreateStatusPage": "status page",
+ "distributedUptimeStatusCreateStatusPageAccess": "Access",
+ "distributedUptimeStatusCreateStatusPageReady": "If your status page is ready, you can mark it as published.",
+ "distributedUptimeStatusBasicInfoHeader": "Basic Information",
+ "distributedUptimeStatusBasicInfoDescription": "Define company name and the subdomain that your status page points to.",
+ "distributedUptimeStatusLogoHeader": "Logo",
+ "distributedUptimeStatusLogoDescription": "Upload a logo for your status page",
+ "distributedUptimeStatusLogoUploadButton": "Upload logo",
+ "distributedUptimeStatusStandardMonitorsHeader": "Standard Monitors",
+ "distributedUptimeStatusStandardMonitorsDescription": "Attach standard monitors to your status page.",
+ "distributedUptimeStatusCreateYour": "Create your",
+ "distributedUptimeStatusEditYour": "Edit your",
+ "distributedUptimeStatusPublishedLabel": "Published and visible to the public",
+ "distributedUptimeStatusCompanyNameLabel": "Company name",
+ "distributedUptimeStatusPageAddressLabel": "Your status page address",
+ "distributedUptimeStatus30Days": "30 days",
+ "distributedUptimeStatus60Days": "60 days",
+ "distributedUptimeStatus90Days": "90 days",
+ "distributedUptimeStatusPageNotSetUp": "A status page is not set up.",
+ "distributedUptimeStatusContactAdmin": "Please contact your administrator",
+ "distributedUptimeStatusPageNotPublic": "This status page is not public.",
+ "distributedUptimeStatusPageDeleteDialog": "Do you want to delete this status page?",
+ "distributedUptimeStatusPageDeleteConfirm": "Yes, delete status page",
+ "distributedUptimeStatusPageDeleteDescription": "Once deleted, your status page cannot be retrieved.",
+ "distributedUptimeStatusDevices": "Devices",
+ "distributedUptimeStatusUpt": "UPT",
+ "distributedUptimeStatusUptBurned": "UPT Burned",
+ "distributedUptimeStatusUptLogo": "Upt Logo",
+ "incidentsTableNoIncidents": "No incidents recorded",
+ "incidentsTablePaginationLabel": "incidents",
+ "incidentsTableMonitorName": "Monitor Name",
+ "incidentsTableStatus": "Status",
+ "incidentsTableDateTime": "Date & Time",
+ "incidentsTableStatusCode": "Status Code",
+ "incidentsTableMessage": "Message",
+ "incidentsOptionsHeader": "Incidents for:",
+ "incidentsOptionsHeaderFilterBy": "Filter by:",
+ "incidentsOptionsHeaderFilterAll": "All",
+ "incidentsOptionsHeaderFilterDown": "Down",
+ "incidentsOptionsHeaderFilterCannotResolve": "Cannot resolve",
+ "incidentsOptionsHeaderShow": "Show:",
+ "incidentsOptionsHeaderLastHour": "Last hour",
+ "incidentsOptionsHeaderLastDay": "Last day",
+ "incidentsOptionsHeaderLastWeek": "Last week",
+ "incidentsOptionsPlaceholderAllServers": "All servers",
+ "infrastructureCreateYour": "Create your",
+ "infrastructureCreateGeneralSettingsDescription": "Here you can select the URL of the host, together with the friendly name and authorization secret to connect to the server agent.",
+ "infrastructureServerRequirement": "The server you are monitoring must be running the",
+ "infrastructureCustomizeAlerts": "Customize alerts",
+ "infrastructureAlertNotificationDescription": "Send a notification to user(s) when thresholds exceed a specified percentage.",
+ "infrastructureCreateMonitor": "Create Infrastructure Monitor",
+ "infrastructureProtocol": "Protocol",
+ "infrastructureServerUrlLabel": "Server URL",
+ "infrastructureDisplayNameLabel": "Display name",
+ "infrastructureAuthorizationSecretLabel": "Authorization secret",
+ "gb": "GB",
+ "mb": "MB",
+ "mem": "Mem",
+ "memoryUsage": "Memory usage",
+ "cpu": "CPU",
+ "cpuUsage": "CPU usage",
+ "cpuTemperature": "CPU Temperature",
+ "diskUsage": "Disk Usage",
+ "used": "Used",
+ "total": "Total",
+ "cores": "Cores",
+ "frequency": "Frequency",
+ "status": "Status",
+ "cpuPhysical": "CPU (Physical)",
+ "cpuLogical": "CPU (Logical)",
+ "cpuFrequency": "CPU Frequency",
+ "avgCpuTemperature": "Average CPU Temperature",
+ "memory": "Memory",
+ "disk": "Disk",
+ "uptime": "Uptime",
+ "os": "OS",
+ "host": "Host",
+ "actions": "Actions",
+ "integrations": "Integrations",
+ "integrationsPrism": "Connect Prism to your favorite service.",
+ "integrationsSlack": "Slack",
+ "integrationsSlackInfo": "Connect with Slack and see incidents in a channel",
+ "integrationsDiscord": "Discord",
+ "integrationsDiscordInfo": "Connect with Discord and view incidents directly in a channel",
+ "integrationsZapier": "Zapier",
+ "integrationsZapierInfo": "Send all incidents to Zapier, and then see them everywhere",
+ "commonSave": "Save",
+ "commonSaving": "Saving...",
+ "createYour": "Create your",
+ "createMonitor": "Create monitor",
+ "pause": "Pause",
+ "resume": "Resume",
+ "editing": "Editing...",
+ "url": "URL",
+ "access": "Access",
+ "timezone": "Timezone",
+ "features": "Features",
+ "administrator": "Administrator?",
+ "loginHere": "Login here",
+ "displayName": "Display name",
+ "urlMonitor": "URL to monitor",
+ "portToMonitor": "Port to monitor",
+ "websiteMonitoring": "Website monitoring",
+ "websiteMonitoringDescription": "Use HTTP(s) to monitor your website or API endpoint.",
+ "pingMonitoring": "Ping monitoring",
+ "pingMonitoringDescription": "Check whether your server is available or not.",
+ "dockerContainerMonitoring": "Docker container monitoring",
+ "dockerContainerMonitoringDescription": "Check whether your Docker container is running or not.",
+ "portMonitoring": "Port monitoring",
+ "portMonitoringDescription": "Check whether your port is open or not.",
+ "createMaintenanceWindow": "Create maintenance window",
+ "createMaintenance": "Create maintenance",
+ "editMaintenance": "Edit maintenance",
+ "maintenanceWindowName": "Maintenance Window Name",
+ "friendlyNameInput": "Friendly name",
+ "friendlyNamePlaceholder": "Maintenance at __ : __ for ___ minutes",
+ "maintenanceRepeat": "Maintenance Repeat",
+ "maintenance": "maintenance",
+ "duration": "Duration",
+ "addMonitors": "Add monitors",
+ "window": "window",
+ "cancel": "Cancel",
+ "message": "Message",
+ "low": "low",
+ "high": "high",
+ "statusCode": "Status code",
+ "date&Time": "Date & Time",
+ "type": "Type",
+ "statusPageName": "Status page name",
+ "publicURL": "Public URL",
+ "repeat": "Repeat",
+ "edit": "Edit",
+ "createA": "Create a",
+ "remove": "Remove",
+ "maintenanceWindowDescription": "Your pings won't be sent during this time frame",
+ "startTime": "Start time",
+ "timeZoneInfo": "All dates and times are in GMT+0 time zone.",
+ "monitorsToApply": "Monitors to apply maintenance window to",
+ "nextWindow": "Next window",
+ "notFoundButton": "Go to the main dashboard",
+ "pageSpeedConfigureSettingsDescription": "Here you can select the URL of the host, together with the type of monitor.",
+ "monitorDisplayName": "Monitor display name",
+ "whenNewIncident": "When there is a new incident,",
+ "notifySMS": "Notify via SMS (coming soon)",
+ "notifyEmails": "Also notify via email to multiple addresses (coming soon)",
+ "seperateEmails": "You can separate multiple emails with a comma",
+ "checkFrequency": "Check frequency",
+ "matchMethod": "Match Method",
+ "expectedValue": "Expected value",
+ "deleteDialogTitle": "Do you really want to delete this monitor?",
+ "deleteDialogDescription": "Once deleted, this monitor cannot be retrieved.",
+ "pageSpeedMonitor": "PageSpeed monitor",
+ "shown": "Shown",
+ "ago": "ago",
+ "companyName": "Company name",
+ "pageSpeedDetailsPerformanceReport": "Values are estimated and may vary.",
+ "pageSpeedDetailsPerformanceReportCalculator": "See calculator",
+ "checkingEvery": "Checking every",
+ "statusPageCreateSettings": "If your status page is ready, you can mark it as published.",
+ "basicInformation": "Basic Information",
+ "statusPageCreateBasicInfoDescription": "Define company name and the subdomain that your status page points to.",
+ "statusPageCreateSelectTimeZoneDescription": "Select the timezone that your status page will be displayed in.",
+ "statusPageCreateAppearanceDescription": "Define the default look and feel of your public status page.",
+ "statusPageCreateSettingsCheckboxLabel": "Published and visible to the public",
+ "statusPageCreateBasicInfoStatusPageAddress": "Your status page address",
+ "statusPageCreateTabsContent": "Status page servers",
+ "statusPageCreateTabsContentDescription": "You can add any number of servers that you monitor to your status page. You can also reorder them for the best viewing experience.",
+ "statusPageCreateTabsContentFeaturesDescription": "Show more details on the status page",
+ "showCharts": "Show charts",
+ "showUptimePercentage": "Show uptime percentage",
+ "removeLogo": "Remove Logo",
+ "statusPageStatus": "A public status page is not set up.",
+ "statusPageStatusContactAdmin": "Please contact to your administrator",
+ "statusPageStatusNotPublic": "This status page is not public.",
+ "statusPageStatusNoPage": "There's no status page here.",
+ "statusPageStatusServiceStatus": "Service status",
+ "statusBreadCrumbsStatusPages": "Status Pages",
+ "statusBreadCrumbsDetails": "Details",
+ "deleteStatusPage": "Do you want to delete this status page?",
+ "deleteStatusPageConfirm": "Yes, delete status page",
+ "deleteStatusPageDescription": "Once deleted, your status page cannot be retrieved.",
+ "uptimeCreate": "The expected value is used to match against response result, and the match determines the status.",
+ "uptimeCreateJsonPath": "This expression will be evaluated against the reponse JSON data and the result will be used to match against the expected value. See",
+ "uptimeCreateJsonPathQuery": "for query language documentation.",
+ "maintenanceTableActionMenuDialogTitle": "Do you really want to remove this maintenance window?",
+ "infrastructureEditYour": "Edit your",
+ "infrastructureEditMonitor": "Save Infrastructure Monitor",
+ "infrastructureMonitorCreated": "Infrastructure monitor created successfully!",
+ "infrastructureMonitorUpdated": "Infrastructure monitor updated successfully!",
+ "errorInvalidTypeId": "Invalid notification type provided",
+ "errorInvalidFieldId": "Invalid field ID provided",
+ "inviteNoTokenFound": "No invite token found",
+ "pageSpeedWarning": "Warning: You haven't added a Google PageSpeed API key yet. Without it, the PageSpeed monitor won't function.",
+ "pageSpeedLearnMoreLink": "Click here",
+ "pageSpeedAddApiKey": "to add your API key.",
+ "update": "Update",
+ "invalidFileFormat": "Unsupported file format!",
+ "invalidFileSize": "File size is too large!",
+ "ClickUpload": "Click to upload",
+ "DragandDrop": "drag and drop",
+ "MaxSize": "Maximum Size",
+ "SupportedFormats": "Supported formats",
+ "FirstName": "First name",
+ "LastName": "Last name",
+ "EmailDescriptionText": "This is your current email address — it cannot be changed.",
+ "ignoreTLSError": "Ignore TLS/SSL error",
+ "tlsErrorIgnored": "TLS/SSL errors ignored",
+ "ignoreTLSErrorDescription": "Ignore TLS/SSL errors and continue checking the website's availability",
+ "YourPhoto": "Profile photo",
+ "PhotoDescriptionText": "This photo will be displayed in your profile page.",
+ "save": "Save",
+ "DeleteAccountTitle": "Remove account",
+ "DeleteAccountButton": "Remove account",
+ "DeleteDescriptionText": "This will remove the account and all associated data from the server. This isn't reversible.",
+ "DeleteAccountWarning": "Removing your account means you won't be able to sign in again and all your data will be removed. This isn't reversible.",
+ "DeleteWarningTitle": "Really remove this account?",
+ "authRegisterFirstName": "Name",
+ "authRegisterLastName": "Surname",
+ "authRegisterEmail": "Email",
+ "authRegisterEmailRequired": "To continue, please enter your email address",
+ "authRegisterEmailInvalid": "Please enter a valid email address",
+ "bulkImport": {
+ "title": "Bulk Import",
+ "selectFileTips": "Select CSV file to upload",
+ "selectFileDescription": "You can download our template or sample ",
+ "selectFile": "Select File",
+ "parsingFailed": "Parsing failed",
+ "uploadSuccess": "Monitors created successfully!",
+ "validationFailed": "Validation failed",
+ "noFileSelected": "No file selected",
+ "fallbackPage": "Import a file to upload a list of servers in bulk"
+ },
+ "publicLink": "Public link",
+ "maskedPageSpeedKeyPlaceholder": "*************************************",
+ "pageSpeedApiKeyFieldTitle": "Google PageSpeed API key",
+ "pageSpeedApiKeyFieldLabel": "PageSpeed API key",
+ "pageSpeedApiKeyFieldDescription": "Enter your Google PageSpeed API key to enable pagespeed monitoring. Click Reset to update the key.",
+ "pageSpeedApiKeyFieldResetLabel": "API key is set. Click Reset to change it.",
+
+ "reset": "Reset",
+ "createNew": "Create new",
+ "greeting": {
+ "prepend": "Hey there",
+ "append": "The afternoon is your playground—let's make it epic!",
+ "overview": "Here's an overview of your {{type}} monitors."
+ },
+ "monitorStatus": {
+ "up": "up",
+ "down": "down",
+ "paused": "paused"
+ },
+ "roles": {
+ "superAdmin": "Super admin",
+ "admin": "Admin",
+ "teamMember": "Team member",
+ "demoUser": "Demo user"
+ },
+ "teamPanel": {
+ "teamMembers": "Team members",
+ "filter": {
+ "all": "All",
+ "member": "Member"
+ },
+ "inviteTeamMember": "Invite a team member",
+ "inviteNewTeamMember": "Invite new team member",
+ "inviteDescription": "When you add a new team member, they will get access to all monitors.",
+ "email": "Email",
+ "selectRole": "Select role",
+ "inviteLink": "Invite link",
+ "cancel": "Cancel",
+ "noMembers": "There are no team members with this role",
+ "getToken": "Get token",
+ "emailToken": "E-mail token",
+ "table": {
+ "name": "Name",
+ "email": "Email",
+ "role": "Role",
+ "created": "Created"
+ }
+ },
+ "monitorState": {
+ "paused": "Paused",
+ "resumed": "Resumed",
+ "active": "Active"
+ },
+ "menu": {
+ "uptime": "Uptime",
+ "pagespeed": "Pagespeed",
+ "infrastructure": "Infrastructure",
+ "distributedUptime": "Distributed Uptime",
+ "incidents": "Incidents",
+ "statusPages": "Status pages",
+ "maintenance": "Maintenance",
+ "integrations": "Integrations",
+ "settings": "Settings",
+ "support": "Support",
+ "discussions": "Discussions",
+ "docs": "Docs",
+ "changelog": "Changelog",
+ "profile": "Profile",
+ "password": "Password",
+ "team": "Team",
+ "logOut": "Log out"
+ },
+ "navControls": "Controls",
+ "statusBreadCrumbsStatusPages": "Status Pages",
+ "statusBreadCrumbsDetails": "Details",
+ "incidentsPageTitle": "Incidents",
+ "passwordPanel": {
+ "passwordChangedSuccess": "Your password was changed successfully.",
+ "passwordInputIncorrect": "Your password input was incorrect.",
+ "currentPassword": "Current password",
+ "enterCurrentPassword": "Enter your current password",
+ "newPassword": "New password",
+ "enterNewPassword": "Enter your new password",
+ "confirmNewPassword": "Confirm new password",
+ "passwordRequirements": "New password must contain at least 8 characters and must have at least one uppercase letter, one lowercase letter, one number and one special character.",
+ "saving": "Saving..."
+ },
+ "uptimeCreateSelectURL": "Enter the URL or IP to monitor (e.g., https://example.com/ or 192.168.1.100) and add a clear display name that appears on the dashboard."
+}
diff --git a/client/src/locales/ru.json b/client/src/locales/ru.json
new file mode 100644
index 000000000..df1e5a5a7
--- /dev/null
+++ b/client/src/locales/ru.json
@@ -0,0 +1,480 @@
+{
+ "dontHaveAccount": "Нет аккаунта",
+ "doNotHaveAccount": "У вас нет учетной записи?",
+ "registerHere": "Зарегистрироваться здесь",
+ "email": "Почта",
+ "forgotPassword": "Забыли пароль",
+ "password": "Пароль",
+ "signUp": "Зарегистрироваться",
+ "submit": "Подтвердить",
+ "title": "Название",
+ "continue": "Продолжить",
+ "enterEmail": "Введите свой email",
+ "authLoginTitle": "Войти",
+ "authLoginEnterPassword": "Введите свой пароль",
+ "commonPassword": "Пароль",
+ "commonBack": "Назад",
+ "authForgotPasswordTitle": "Забыли пароль?",
+ "authForgotPasswordResetPassword": "Сбросить пароль",
+ "authForgotPasswordInstructions": "Не волнуйтесь, мы отправим вам инструкции по сбросу.",
+ "createPassword": "Создайте свой пароль",
+ "createAPassword": "Пароль",
+ "authRegisterAlreadyHaveAccount": "Уже есть аккаунт?",
+ "authRegisterLoginLink": "Войти",
+ "commonAppName": "Checkmate",
+ "welcomeBack": "Добро пожаловать обратно! Вы успешно вошли в систему.",
+ "authLoginEnterEmail": "Введите свой email",
+ "authRegisterTitle": "Создать аккаунт",
+ "authRegisterStepOneTitle": "Создайте свой аккаут",
+ "authRegisterStepOneDescription": "Введите свои данные, чтобы начать",
+ "authRegisterStepTwoTitle": "Настройте свой профиль",
+ "authRegisterStepTwoDescription": "Расскажите нам о себе",
+ "authRegisterStepThreeTitle": "Почти готово!",
+ "authRegisterStepThreeDescription": "Проверьте свою информацию",
+ "authForgotPasswordDescription": "Не волнуйтесь, мы вышлем вам инструкции по сбросу настроек.",
+ "authForgotPasswordSendInstructions": "Отправить инструкции",
+ "authForgotPasswordBackTo": "Назад к",
+ "authCheckEmailTitle": "Проверьте свою почту",
+ "authCheckEmailDescription": "Мы отправили ссылку для сброса пароля",
+ "authCheckEmailResendEmail": "Отправить письмо повторно",
+ "authCheckEmailBackTo": "Назад к",
+ "goBackTo": "Назад к",
+ "authCheckEmailDidntReceiveEmail": "Не получили письмо?",
+ "authCheckEmailClickToResend": "Нажмите, чтобы отправить повторно",
+ "authSetNewPasswordTitle": "Установите новый пароль",
+ "authSetNewPasswordDescription": "Ваш новый пароль должен отличаться от ранее использованных паролей.",
+ "authSetNewPasswordNewPassword": "Новый пароль",
+ "authSetNewPasswordConfirmPassword": "Подтвердите пароль",
+ "confirmPassword": "Введите пароль еще раз для подтверждения",
+ "confirmNewPasswordPlaceholder": "Подтвердите ваш новый пароль",
+ "authSetNewPasswordResetPassword": "Сбросить пароль",
+ "authSetNewPasswordBackTo": "Назад к",
+ "authPasswordMustBeAtLeast": "Должно быть как минимум",
+ "authPasswordCharactersLong": "длиной 8 символов",
+ "authPasswordMustContainAtLeast": "Должен содержать как минимум",
+ "authPasswordSpecialCharacter": "один специальный символ",
+ "authPasswordOneNumber": "одно число",
+ "authPasswordUpperCharacter": "один верхний символ",
+ "authPasswordLowerCharacter": "один нижний символ",
+ "authPasswordConfirmAndPassword": "Подтвердите пароль и пароль",
+ "authPasswordMustMatch": "Пароли должны совпадать",
+ "authRegisterCreateAccount": "Создайте свою учетную запись, чтобы начать",
+ "authRegisterCreateSuperAdminAccount": "Создайте учетную запись суперадминистратора, чтобы начать работу",
+ "authRegisterSignUpWithEmail": "Создать учетную запись суперадминистратора",
+ "authRegisterBySigningUp": "Создавая учетную запись, вы соглашаетесь с нашими Условиями использования и Политикой конфиденциальности .",
+ "authRegisterFirstName": "Имя",
+ "authRegisterLastName": "Фамилия",
+ "authRegisterEmail": "Эл. почта",
+ "authRegisterEmailRequired": "Чтобы продолжить, пожалуйста, введите ваш адрес электронной почты",
+ "authRegisterEmailInvalid": "Пожалуйста, введите действительный адрес электронной почты",
+ "bulkImport": {
+ "title": "Массовый импорт",
+ "selectFileTips": "Выберите CSV-файл для загрузки",
+ "selectFileDescription": "Вы можете скачать наш шаблон или пример ",
+ "selectFile": "Выбрать файл",
+ "parsingFailed": "Ошибка анализа",
+ "uploadSuccess": "Мониторы успешно созданы!",
+ "validationFailed": "Ошибка проверки",
+ "noFileSelected": "Файл не выбран",
+ "fallbackPage": "Импортируйте файл для загрузки списка серверов"
+ },
+ "distributedStatusHeaderText": "Охват реального времени и реального устройства",
+ "distributedStatusSubHeaderText": "Работает на миллионах устройств по всему миру, просматривайте производительность системы по глобальному региону, стране или городу",
+ "settingsGeneralSettings": "Общие настройки",
+ "settingsDisplayTimezone": "Отображать часовой пояс",
+ "settingsDisplayTimezoneDescription": "Выберите часовой пояс, используемый для отображения дат и времени в приложении.",
+ "settingsAppearance": "Внешний вид",
+ "settingsAppearanceDescription": "Переключение между светлым и темным режимом или изменение языка пользовательского интерфейса",
+ "settingsThemeMode": "Тема",
+ "settingsThemeModeLight": "Светлая",
+ "settingsThemeModeDark": "Тёмная",
+ "settingsLanguage": "Язык",
+ "settingsDistributedUptime": "Distributed uptime",
+ "settingsDistributedUptimeDescription": "Включить/выключить distributed uptime monitoring.",
+ "settingsEnabled": "Включено",
+ "settingsDisabled": "Выключено",
+ "settingsHistoryAndMonitoring": "История мониторинга",
+ "settingsHistoryAndMonitoringDescription": "Определите, как долго вы хотите хранить исторические данные. Вы также можете очистить все существующие данные.",
+ "settingsTTLLabel": "Дни, за которыми вы хотите следить.",
+ "settingsTTLOptionalLabel": "0 для бесконечности",
+ "settingsClearAllStats": "Очистить всю статистику. Это необратимо.",
+ "settingsClearAllStatsButton": "Очистить всю статистику",
+ "settingsClearAllStatsDialogTitle": "Хотите очистить всю статистику?",
+ "settingsClearAllStatsDialogDescription": "После удаления история мониторинга и статистика не могут быть восстановлены.",
+ "settingsClearAllStatsDialogConfirm": "Да, очистить всю статистику",
+ "settingsClearAllStatsDialogCancel": "Отмена",
+ "settingsDemoMonitors": "Демо мониторы",
+ "settingsDemoMonitorsDescription": "Добавьте примеры мониторов для демонстрации.",
+ "settingsAddDemoMonitors": "Добавление демонстрационных мониторов",
+ "settingsAddDemoMonitorsButton": "Добавьте демонстрационные мониторы",
+ "settingsSystemReset": "Сброс системы",
+ "settingsSystemResetDescription": "Удалить все мониторы из вашей системы.",
+ "settingsRemoveAllMonitors": "Удаление всех мониторов",
+ "settingsRemoveAllMonitorsButton": "Удалить все мониторы",
+ "settingsRemoveAllMonitorsDialogTitle": "Хотите удалить все мониторы?",
+ "settingsRemoveAllMonitorsDialogConfirm": "Да, удалить все мониторы",
+ "settingsWallet": "Кошелёк",
+ "settingsWalletDescription": "Подключите свой кошелек здесь. Это необходимо для того, чтобы монитор Distributed Uptime мог подключиться к нескольким узлам по всему миру.",
+ "settingsAbout": "О",
+ "settingsDevelopedBy": "Developed by Bluewave Labs.",
+ "settingsSave": "Сохранить",
+ "commonSave": "Сохранить",
+ "commonSaving": "Сохранение...",
+ "settingsSuccessSaved": "Настройки успешно сохранены",
+ "settingsFailedToSave": "Не удалось сохранить настройки",
+ "settingsStatsCleared": "Статистика успешно очищена",
+ "settingsFailedToClearStats": "Не удалось очистить статистику",
+ "FirstName": "Имя",
+ "LastName": "Фамилия",
+ "YourPhoto": "Фото профиля",
+ "PhotoDescriptionText": "Это фото будет отображаться на странице вашего профиля.",
+ "EmailDescriptionText": "Ваш текущий email—его нельзя изменить.",
+ "DeleteAccountTitle": "Удалить аккаунт",
+ "DeleteAccountButton": "Удалить аккаунт",
+ "DeleteDescriptionText": "Это удалит аккаунт и все связанные данные с сервера. Это необратимо.",
+ "DeleteAccountWarning": "Удаление аккаунта означает, что вы не сможете снова войти в систему, и все ваши данные будут удалены. Это необратимо.",
+ "DeleteWarningTitle": "Действительно удалить этот аккаунт?",
+ "settingsDemoMonitorsAdded": "Успешно добавлены демонстрационные мониторы",
+ "settingsFailedToAddDemoMonitors": "Не удалось добавить демонстрационные мониторы",
+ "settingsMonitorsDeleted": "Успешно удалены все мониторы",
+ "settingsFailedToDeleteMonitors": "Не удалось удалить все мониторы",
+ "backendUnreachable": "Ошибка подключения к серверу",
+ "backendUnreachableMessage": "Мы не можем подключиться к серверу. Пожалуйста, проверьте ваше интернет-соединение или проверьте конфигурацию развертывания, если проблема не устраняется.",
+ "backendUnreachableError": "Невозможно подключиться к серверу. Пожалуйста, повторите попытку позже.",
+ "retryConnection": "Повторить подключение",
+ "retryingConnection": "Подключение...",
+ "backendReconnected": "Успешно восстановлено подключение к серверу.",
+ "backendStillUnreachable": "Сервер по-прежнему недоступен. Пожалуйста, повторите попытку позже.",
+ "backendConnectionError": "Ошибка подключения к серверу. Пожалуйста, проверьте ваше сетевое подключение.",
+ "starPromptTitle": "Star Checkmate",
+ "starPromptDescription": "Ознакомьтесь с последними релизами и помогите развить сообщество на GitHub",
+ "https": "HTTPS",
+ "http": "HTTP",
+ "monitor": "монитор",
+ "aboutus": "О Нас",
+
+ "now": "Сейчас",
+ "delete": "Удалить",
+ "configure": "Настроить",
+ "networkError": "Ошибка сети",
+ "responseTime": "Время ответа",
+ "ms": "мс",
+ "bar": "Bar",
+ "area": "Area",
+ "country": "СТРАНА",
+ "city": "ГОРОД",
+ "response": "ОТВЕТ",
+ "checkConnection": "Пожалуйста, проверьте ваше соединение",
+ "passwordreset": "Сброс пароля",
+ "authRegisterStepOnePersonalDetails": "Введите свои личные данные",
+ "authCheckEmailOpenEmailButton": "Откройте приложение почты",
+ "authNewPasswordConfirmed": "Ваш пароль успешно сброшен. Нажмите ниже, чтобы войти в систему магическим образом.",
+ "monitorStatusUp": "Монитор {name} ({url}) теперь включен и отвечает",
+ "monitorStatusDown": "Монитор {name} ({url}) ОТКЛЮЧЕН и не отвечает",
+ "webhookSendSuccess": "Уведомление Webhook успешно отправлено",
+ "webhookSendError": "Ошибка отправки уведомления webhook на {platform}",
+ "webhookUnsupportedPlatform": "Неподдерживаемая платформа: {platform}",
+ "distributedRightCategoryTitle": "Монитор",
+ "distributedStatusServerMonitors": "Серверные мониторы",
+ "distributedStatusServerMonitorsDescription": "Мониторинг состояния связанных серверов",
+ "distributedUptimeCreateSelectURL": "Здесь вы можете выбрать URL-адрес хоста, а также тип монитора.",
+ "distributedUptimeCreateChecks": "Проверки, которые необходимо выполнить",
+ "distributedUptimeCreateChecksDescription": "Вы всегда можете добавить или удалить проверки после добавления своего сайта.",
+ "distributedUptimeCreateIncidentNotification": "Уведомления об инцидентах",
+ "distributedUptimeCreateIncidentDescription": "В случае возникновения инцидента сообщите об этом пользователям.",
+ "distributedUptimeCreateAdvancedSettings": "Расширенные настройки",
+ "distributedUptimeDetailsNoMonitorHistory": "Для этого монитора пока нет истории проверок.",
+ "distributedUptimeDetailsFooterHeading": "Made with ❤️ by UpRock & Bluewave Labs",
+ "distributedUptimeDetailsFooterBuilt": "Built on",
+ "distributedUptimeDetailsFooterSolana": "Solana",
+ "distributedUptimeDetailsMonitorHeader": "Distributed Uptime Monitoring powered by DePIN",
+ "distributedUptimeDetailsStatusHeaderUptime": "Аптайм:",
+ "distributedUptimeDetailsStatusHeaderLastUpdate": "Последнее обновление",
+ "notifications": {
+ "enableNotifications": "Включить уведомления {{platform}}",
+ "testNotification": "Тестовое уведомление",
+ "addOrEditNotifications": "Добавить или изменить уведомления",
+ "slack": {
+ "label": "Slack",
+ "description": "Чтобы включить уведомления Slack, создайте приложение Slack и включите входящие вебхуки. После этого просто укажите URL вебхука здесь.",
+ "webhookLabel": "URL вебхука",
+ "webhookPlaceholder": "https://hooks.slack.com/services/..."
+ },
+ "discord": {
+ "label": "Discord",
+ "description": "Чтобы отправить данные на канал Discord из Checkmate через уведомления Discord с использованием веб-хуков, вы можете использовать функцию входящих веб-хуков Discord.",
+ "webhookLabel": "Discord Webhook URL",
+ "webhookPlaceholder": "https://discord.com/api/webhooks/..."
+ },
+ "telegram": {
+ "label": "Telegram",
+ "description": "Чтобы включить уведомления Telegram, создайте бота Telegram с помощью BotFather, официального бота для создания и управления ботами Telegram. Затем получите токен API и идентификатор чата и запишите их здесь.",
+ "tokenLabel": "Ваш токен бота",
+ "tokenPlaceholder": "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11",
+ "chatIdLabel": "ID Вашего Чата",
+ "chatIdPlaceholder": "-1001234567890"
+ },
+ "webhook": {
+ "label": "Вебхуки",
+ "description": "Вы можете настроить пользовательский вебхук для получения уведомлений о возникновении инцидентов.",
+ "urlLabel": "URL вебхука",
+ "urlPlaceholder": "https://your-server.com/webhook"
+ },
+ "testNotificationDevelop": "Тестовое уведомление 2",
+ "integrationButton": ""
+ },
+ "testLocale": "testLocale",
+ "add": "Добавить",
+ "monitors": "мониторы",
+ "distributedUptimeStatusCreateStatusPage": "страница статуса",
+ "distributedUptimeStatusCreateStatusPageAccess": "Доступ",
+ "distributedUptimeStatusCreateStatusPageReady": "Если ваша страница статуса готова, вы можете отметить ее как опубликованную.",
+ "distributedUptimeStatusBasicInfoHeader": "Основная информация",
+ "distributedUptimeStatusBasicInfoDescription": "Определите название компании и поддомен, на который ссылается ваша страница статуса.",
+ "distributedUptimeStatusLogoHeader": "Логотип",
+ "distributedUptimeStatusLogoDescription": "Загрузите логотип для своей страницы статуса",
+ "distributedUptimeStatusLogoUploadButton": "Загрузить логотип",
+ "distributedUptimeStatusStandardMonitorsHeader": "Стандартные Мониторы",
+ "distributedUptimeStatusStandardMonitorsDescription": "Прикрепите стандартные мониторы к своей странице статуса.",
+ "distributedUptimeStatusCreateYour": "Создайте свой",
+ "distributedUptimeStatusEditYour": "Отредактируйте свой",
+ "distributedUptimeStatusPublishedLabel": "Опубликовано и доступно для общественности",
+ "distributedUptimeStatusCompanyNameLabel": "Название компании",
+ "distributedUptimeStatusPageAddressLabel": "Адрес вашей страницы статуса",
+ "distributedUptimeStatus30Days": "30 дней",
+ "distributedUptimeStatus60Days": "60 дней",
+ "distributedUptimeStatus90Days": "90 дней",
+ "distributedUptimeStatusPageNotSetUp": "Страница статуса не настроена.",
+ "distributedUptimeStatusContactAdmin": "Пожалуйста, свяжитесь с вашим администратором",
+ "distributedUptimeStatusPageNotPublic": "Эта страница статуса не является публичной.",
+ "distributedUptimeStatusPageDeleteDialog": "Вы хотите удалить эту страницу статуса?",
+ "distributedUptimeStatusPageDeleteConfirm": "Да, удалить страницу статуса",
+ "distributedUptimeStatusPageDeleteDescription": "После удаления ваша страница статуса не может быть восстановлена.",
+ "distributedUptimeStatusDevices": "Устройства",
+ "distributedUptimeStatusUpt": "UPT",
+ "distributedUptimeStatusUptBurned": "UPT Burned",
+ "distributedUptimeStatusUptLogo": "Upt Logo",
+ "incidentsTableNoIncidents": "Инцидентов не зафиксировано",
+ "incidentsTablePaginationLabel": "инциденты",
+ "incidentsTableMonitorName": "Имя Монитора",
+ "incidentsTableStatus": "Статус",
+ "incidentsTableDateTime": "Дата и Время",
+ "incidentsTableStatusCode": "Код Статуса",
+ "incidentsTableMessage": "Сообщение",
+ "incidentsOptionsHeader": "Инцидент для:",
+ "incidentsOptionsHeaderFilterBy": "Фильтровать по:",
+ "incidentsOptionsHeaderFilterAll": "Все",
+ "incidentsOptionsHeaderFilterDown": "Недоступно",
+ "incidentsOptionsHeaderFilterCannotResolve": "Невозможно решить",
+ "incidentsOptionsHeaderShow": "Показать:",
+ "incidentsOptionsHeaderLastHour": "Последний час",
+ "incidentsOptionsHeaderLastDay": "Последний день",
+ "incidentsOptionsHeaderLastWeek": "Последняя неделя",
+ "incidentsOptionsPlaceholderAllServers": "Все сервера",
+ "infrastructureCreateYour": "Создайте свой",
+ "infrastructureCreateGeneralSettingsDescription": "Здесь вы можете выбрать URL-адрес хоста, а также понятное имя и секретный ключ авторизации для подключения к агенту сервера.",
+ "infrastructureServerRequirement": "Сервер, который вы отслеживаете, должен быть запущен",
+ "infrastructureCustomizeAlerts": "Настройте оповещения",
+ "infrastructureAlertNotificationDescription": "Отправлять уведомления пользователям, когда пороговые значения превышают указанный процент.",
+ "infrastructureCreateMonitor": "Создать Монитор Инфраструктуры",
+ "infrastructureProtocol": "Протокол",
+ "infrastructureServerUrlLabel": "URL Сервера",
+ "infrastructureDisplayNameLabel": "Отображаемое имя",
+ "infrastructureAuthorizationSecretLabel": "Секрет авторизации",
+ "gb": "ГБ",
+ "mb": "МБ",
+ "mem": "Mem",
+ "memoryUsage": "Использование памяти",
+ "cpu": "CPU",
+ "cpuUsage": "Использование CPU",
+ "cpuTemperature": "Температура CPU",
+ "diskUsage": "Использование диска",
+ "used": "Использовал",
+ "total": "Всего",
+ "cores": "Ядра",
+ "frequency": "Частота",
+ "status": "Статус",
+ "cpuPhysical": "CPU (физический)",
+ "cpuLogical": "CPU (логический)",
+ "cpuFrequency": "Частота CPU",
+ "avgCpuTemperature": "Средняя температура CPU",
+ "memory": "Память",
+ "disk": "Диск",
+ "uptime": "Аптайм",
+ "os": "ОС",
+ "host": "Хост",
+ "actions": "Действия",
+ "integrations": "Интеграции",
+ "integrationsPrism": "Подключите Prism к вашему любимому сервису.",
+ "integrationsSlack": "Slack",
+ "integrationsSlackInfo": "Подключитесь к Slack и просматривайте инциденты в канале",
+ "integrationsDiscord": "Discord",
+ "integrationsDiscordInfo": "Подключитесь к Discord и просматривайте инциденты прямо в канале",
+ "integrationsZapier": "Zapier",
+ "integrationsZapierInfo": "Отправляйте все инциденты в Zapier, и тогда вы сможете видеть их везде",
+ "createYour": "",
+ "createMonitor": "",
+ "pause": "",
+ "resume": "",
+ "editing": "",
+ "url": "",
+ "access": "",
+ "timezone": "",
+ "features": "",
+ "administrator": "",
+ "loginHere": "",
+ "displayName": "",
+ "urlMonitor": "",
+ "portToMonitor": "",
+ "websiteMonitoring": "",
+ "websiteMonitoringDescription": "",
+ "pingMonitoring": "",
+ "pingMonitoringDescription": "",
+ "dockerContainerMonitoring": "",
+ "window": "",
+ "cancel": "",
+ "message": "",
+ "low": "",
+ "high": "",
+ "statusCode": "",
+ "date&Time": "",
+ "type": "",
+ "statusPageName": "",
+ "publicURL": "",
+ "repeat": "",
+ "edit": "",
+ "createA": "",
+ "remove": "",
+ "maintenanceWindowDescription": "",
+ "startTime": "",
+ "timeZoneInfo": "",
+ "monitorsToApply": "",
+ "nextWindow": "",
+ "notFoundButton": "",
+ "pageSpeedConfigureSettingsDescription": "",
+ "monitorDisplayName": "",
+ "whenNewIncident": "",
+ "notifySMS": "",
+ "notifyEmails": "",
+ "seperateEmails": "",
+ "checkFrequency": "",
+ "matchMethod": "",
+ "expectedValue": "",
+ "deleteDialogTitle": "",
+ "deleteDialogDescription": "",
+ "pageSpeedMonitor": "",
+ "shown": "",
+ "ago": "",
+ "companyName": "",
+ "pageSpeedDetailsPerformanceReport": "",
+ "pageSpeedDetailsPerformanceReportCalculator": "",
+ "checkingEvery": "",
+ "statusPageCreateSettings": "",
+ "basicInformation": "",
+ "statusPageCreateBasicInfoDescription": "",
+ "statusPageCreateSelectTimeZoneDescription": "",
+ "statusPageCreateAppearanceDescription": "",
+ "statusPageCreateSettingsCheckboxLabel": "",
+ "statusPageCreateBasicInfoStatusPageAddress": "",
+ "statusPageCreateTabsContent": "",
+ "statusPageCreateTabsContentDescription": "",
+ "statusPageCreateTabsContentFeaturesDescription": "",
+ "showCharts": "",
+ "showUptimePercentage": "",
+ "removeLogo": "",
+ "statusPageStatus": "",
+ "statusPageStatusContactAdmin": "",
+ "statusPageStatusNotPublic": "",
+ "statusPageStatusNoPage": "",
+ "statusPageStatusServiceStatus": "",
+ "deleteStatusPage": "",
+ "deleteStatusPageConfirm": "",
+ "deleteStatusPageDescription": "",
+ "uptimeCreate": "",
+ "uptimeCreateJsonPath": "",
+ "uptimeCreateJsonPathQuery": "",
+ "maintenanceTableActionMenuDialogTitle": "",
+ "incidentsPageTitle": "Инциденты",
+ "passwordPanel": {
+ "passwordChangedSuccess": "Ваш пароль был успешно изменен.",
+ "passwordInputIncorrect": "Ваш пароль введен неверно.",
+ "currentPassword": "Текущий пароль",
+ "enterCurrentPassword": "Введите ваш текущий пароль",
+ "newPassword": "Новый пароль",
+ "enterNewPassword": "Введите ваш новый пароль",
+ "confirmNewPassword": "Подтвердите новый пароль",
+ "passwordRequirements": "Новый пароль должен содержать не менее 8 символов и должен иметь как минимум одну заглавную букву, одну строчную букву, одну цифру и один специальный символ.",
+ "saving": "Сохранение..."
+ },
+ "pageSpeedWarning": "Предупреждение: Вы не добавили ключ API Google PageSpeed. Без него монитор PageSpeed не будет работать.",
+ "pageSpeedLearnMoreLink": "Нажмите здесь, чтобы узнать",
+ "pageSpeedAddApiKey": "как добавить ваш ключ API.",
+ "createNew": "Создать новый",
+ "greeting": {
+ "prepend": "Привет",
+ "append": "День прекрасен для новых достижений!",
+ "overview": "Вот обзор ваших мониторов {{type}}."
+ },
+ "monitorStatus": {
+ "up": "работает",
+ "down": "не работает",
+ "paused": "приостановлен"
+ },
+ "roles": {
+ "superAdmin": "Суперадминистратор",
+ "admin": "Администратор",
+ "teamMember": "Член команды",
+ "demoUser": "Демо-пользователь"
+ },
+ "teamPanel": {
+ "teamMembers": "Члены команды",
+ "filter": {
+ "all": "Все",
+ "member": "Член"
+ },
+ "inviteTeamMember": "Пригласить члена команды",
+ "inviteNewTeamMember": "Пригласить нового члена команды",
+ "inviteDescription": "Когда вы добавляете нового члена команды, он получит доступ ко всем мониторам.",
+ "email": "Эл. почта",
+ "selectRole": "Выберите роль",
+ "inviteLink": "Ссылка для приглашения",
+ "cancel": "Отмена",
+ "noMembers": "Нет членов команды с этой ролью",
+ "getToken": "Получить токен",
+ "emailToken": "Отправить токен по эл. почте",
+ "table": {
+ "name": "Имя",
+ "email": "Эл. почта",
+ "role": "Роль",
+ "created": "Создан"
+ }
+ },
+ "monitorState": {
+ "paused": "приостановлен",
+ "resumed": "возобновлен",
+ "active": "активный"
+ },
+ "menu": {
+ "uptime": "Аптайм",
+ "pagespeed": "Скорость страницы",
+ "infrastructure": "Инфраструктура",
+ "distributedUptime": "Распределенный Аптайм",
+ "incidents": "Инциденты",
+ "statusPages": "Страницы статуса",
+ "maintenance": "Обслуживание",
+ "integrations": "Интеграции",
+ "settings": "Настройки",
+ "support": "Поддержка",
+ "profile": "Профиль",
+ "password": "Пароль",
+ "team": "Команда",
+ "logOut": "Выйти",
+ "discussions": "Обсуждения",
+ "docs": "Документация",
+ "changelog": "История изменений"
+ },
+ "navControls": "Управление",
+ "statusBreadCrumbsStatusPages": "Страницы статуса",
+ "statusBreadCrumbsDetails": "Подробности",
+ "uptimeCreateSelectURL": "Введите URL или IP для мониторинга (например, https://example.com/ или 192.168.1.100) и добавьте понятное отображаемое имя, которое будет показано на панели управления."
+}
\ No newline at end of file
diff --git a/client/src/locales/tr.json b/client/src/locales/tr.json
new file mode 100644
index 000000000..5aee7cf51
--- /dev/null
+++ b/client/src/locales/tr.json
@@ -0,0 +1,516 @@
+{
+ "dontHaveAccount": "Hesabınız yok mu",
+ "doNotHaveAccount": "Hesabınız yok mu?",
+ "registerHere": "Buradan kayıt olun",
+ "email": "E-posta",
+ "forgotPassword": "Parolamı unuttum",
+ "password": "Parola",
+ "signUp": "Kayıt Ol",
+ "submit": "Gönder",
+ "title": "Başlık",
+ "continue": "Devam Et",
+ "enterEmail": "E-posta adresinizi girin",
+ "authLoginTitle": "Giriş Yap",
+ "authLoginEnterPassword": "Parolanızı girin",
+ "commonPassword": "Parola",
+ "commonBack": "Geri",
+ "authForgotPasswordTitle": "Parolanızı mı unuttunuz?",
+ "authForgotPasswordResetPassword": "Parola sıfırla",
+ "authForgotPasswordInstructions": "Endişelenmeyin, size sıfırlama talimatlarını göndereceğiz.",
+ "createPassword": "Parolanızı oluşturun",
+ "createAPassword": "Parola",
+ "authRegisterAlreadyHaveAccount": "Zaten hesabınız var mı?",
+ "authRegisterLoginLink": "Giriş Yap",
+ "commonAppName": "Checkmate",
+ "welcomeBack": "Tekrar hoş geldiniz! Başarıyla giriş yaptınız.",
+ "authLoginEnterEmail": "E-posta adresinizi girin",
+ "authRegisterTitle": "Hesap oluştur",
+ "authRegisterStepOneTitle": "Hesabınızı oluşturun",
+ "authRegisterStepOneDescription": "Başlamak için bilgilerinizi girin",
+ "authRegisterStepTwoTitle": "Profilinizi ayarlayın",
+ "authRegisterStepTwoDescription": "Kendiniz hakkında daha fazla bilgi verin",
+ "authRegisterStepThreeTitle": "Neredeyse bitti!",
+ "authRegisterStepThreeDescription": "Bilgilerinizi gözden geçirin",
+ "authForgotPasswordDescription": "Endişelenmeyin, size sıfırlama talimatlarını göndereceğiz.",
+ "authForgotPasswordSendInstructions": "Talimatları gönder",
+ "authForgotPasswordBackTo": "Geri dön",
+ "authCheckEmailTitle": "E-postanızı kontrol edin",
+ "authCheckEmailDescription": "{{email}} adresine şifre sıfırlama bağlantısı gönderdik",
+ "authCheckEmailResendEmail": "E-postayı yeniden gönder",
+ "authCheckEmailBackTo": "Geri dön",
+ "goBackTo": "Geri dön",
+ "authCheckEmailDidntReceiveEmail": "E-posta almadınız mı?",
+ "authCheckEmailClickToResend": "Yeniden göndermek için tıklayın",
+ "authSetNewPasswordTitle": "Yeni şifre belirle",
+ "authSetNewPasswordDescription": "Yeni şifreniz daha önce kullanılan şifrelerden farklı olmalıdır.",
+ "authSetNewPasswordNewPassword": "Yeni şifre",
+ "authSetNewPasswordConfirmPassword": "Parolayı onayla",
+ "confirmPassword": "Onaylamak için parolayı tekrar girin",
+ "confirmNewPasswordPlaceholder": "Yeni parolanızı onaylayın",
+ "authSetNewPasswordResetPassword": "Parola sıfırla",
+ "authSetNewPasswordBackTo": "Geri dön",
+ "authPasswordMustBeAtLeast": "En az",
+ "authPasswordCharactersLong": "8 karakter uzunluğunda olmalı",
+ "authPasswordMustContainAtLeast": "En az içermeli",
+ "authPasswordSpecialCharacter": "bir özel karakter",
+ "authPasswordOneNumber": "bir rakam",
+ "authPasswordUpperCharacter": "bir büyük harf",
+ "authPasswordLowerCharacter": "bir küçük harf",
+ "authPasswordConfirmAndPassword": "Onay şifresi ve şifre",
+ "authPasswordMustMatch": "Parolalar eşleşmelidir",
+ "authRegisterCreateAccount": "Hesap oluşturmak için devam et",
+ "authRegisterCreateSuperAdminAccount": "Super admin hesabınızı oluşturmak için devam edin",
+ "authRegisterSignUpWithEmail": "E-posta ile kayıt ol",
+ "authRegisterBySigningUp": "Kayıt olarak, aşağıdaki şartları kabul ediyorsunuz:",
+ "distributedStatusHeaderText": "Gerçek zamanlı, Gerçek cihazlar kapsamı",
+ "distributedStatusSubHeaderText": "Dünya çapında milyonlarca cihaz tarafından desteklenen sistem performansını küresel bölgeye, ülkeye veya şehre göre görüntüleyin",
+ "settingsGeneralSettings": "Genel ayarlar",
+ "settingsDisplayTimezone": "Görüntüleme saat dilimi",
+ "settingsDisplayTimezoneDescription": "Uygulama genelinde tarih ve saatlerin görüntülenmesi için kullanılacak saat dilimini seçin.",
+ "settingsAppearance": "Görünüm",
+ "settingsAppearanceDescription": "Açık ve koyu mod arasında geçiş yapın veya kullanıcı arayüzü dilini değiştirin",
+ "settingsThemeMode": "Tema",
+ "settingsThemeModeLight": "Açık",
+ "settingsThemeModeDark": "Koyu",
+ "settingsLanguage": "Dil",
+ "settingsDistributedUptime": "Dağıtılmış çalışma süresi",
+ "settingsDistributedUptimeDescription": "Dağıtılmış çalışma süresi izlemeyi etkinleştirin/devre dışı bırakın.",
+ "settingsEnabled": "Etkin",
+ "settingsDisabled": "Devre dışı",
+ "settingsHistoryAndMonitoring": "İzleme geçmişi",
+ "settingsHistoryAndMonitoringDescription": "Geçmiş verileri ne kadar süre saklamak istediğinizi tanımlayın. Ayrıca mevcut tüm verileri temizleyebilirsiniz.",
+ "settingsTTLLabel": "İzleme geçmişini saklamak istediğiniz gün sayısı.",
+ "settingsTTLOptionalLabel": "Sınırsız için 0",
+ "settingsClearAllStats": "Tüm istatistikleri temizle. Bu geri alınamaz.",
+ "settingsClearAllStatsButton": "Tüm istatistikleri temizle",
+ "settingsClearAllStatsDialogTitle": "Tüm istatistikleri temizlemek istiyor musunuz?",
+ "settingsClearAllStatsDialogDescription": "Kaldırıldıktan sonra, izleme geçmişi ve istatistikleri geri alınamaz.",
+ "settingsClearAllStatsDialogConfirm": "Evet, tüm istatistikleri temizle",
+ "settingsClearAllStatsDialogCancel": "İptal",
+ "settingsDemoMonitors": "Demo monitörler",
+ "settingsDemoMonitorsDescription": "Gösterim amaçlı örnek monitörler ekleyin.",
+ "settingsAddDemoMonitors": "Demo monitörler ekleniyor",
+ "settingsAddDemoMonitorsButton": "Demo monitörler ekle",
+ "settingsSystemReset": "Sistem sıfırlama",
+ "settingsSystemResetDescription": "Sisteminizden tüm monitörleri kaldırın.",
+ "settingsRemoveAllMonitors": "Tüm monitörler kaldırılıyor",
+ "settingsRemoveAllMonitorsButton": "Tüm monitörleri kaldır",
+ "settingsRemoveAllMonitorsDialogTitle": "Tüm monitörleri kaldırmak istiyor musunuz?",
+ "settingsRemoveAllMonitorsDialogConfirm": "Evet, tüm monitörleri kaldır",
+ "settingsWallet": "Cüzdan",
+ "settingsWalletDescription": "Cüzdanınızı buradan bağlayın. Bu, Dağıtılmış Çalışma Süresi monitörünün küresel olarak birden çok düğüme bağlanması için gereklidir.",
+ "settingsAbout": "Hakkında",
+ "settingsDevelopedBy": "Bluewave Labs tarafından geliştirilmiştir.",
+ "settingsSave": "Kaydet",
+ "settingsSuccessSaved": "Ayarlar başarıyla kaydedildi",
+ "settingsFailedToSave": "Ayarlar kaydedilemedi",
+ "settingsStatsCleared": "İstatistikler başarıyla temizlendi",
+ "settingsFailedToClearStats": "İstatistikler temizlenemedi",
+ "settingsDemoMonitorsAdded": "Demo monitörler başarıyla eklendi",
+ "settingsFailedToAddDemoMonitors": "Demo monitörler eklenemedi",
+ "settingsMonitorsDeleted": "Tüm monitörler başarıyla silindi",
+ "settingsFailedToDeleteMonitors": "Monitörler silinemedi",
+ "backendUnreachable": "Sunucu Bağlantı Hatası",
+ "backendUnreachableMessage": "Sunucuya bağlanamıyoruz. Lütfen internet bağlantınızı kontrol edin veya sorun devam ederse dağıtım yapılandırmanızı doğrulayın.",
+ "backendUnreachableError": "Sunucuya bağlanılamıyor. Lütfen daha sonra tekrar deneyin.",
+ "retryConnection": "Bağlantıyı Yeniden Dene",
+ "retryingConnection": "Bağlanıyor...",
+ "backendReconnected": "Sunucuya başarıyla yeniden bağlandı.",
+ "backendStillUnreachable": "Sunucu hala erişilemez durumda. Lütfen daha sonra tekrar deneyin.",
+ "backendConnectionError": "Sunucuya bağlanırken hata oluştu. Lütfen ağ bağlantınızı kontrol edin.",
+ "starPromptTitle": "Checkmate yıldızla değerlendirin",
+ "starPromptDescription": "En son sürümleri görün ve GitHub'daki topluluğun büyümesine yardımcı olun",
+ "https": "HTTPS",
+ "http": "HTTP",
+ "monitor": "monitör",
+ "aboutus": "Hakkımızda",
+
+ "now": "Şimdi",
+ "delete": "Sil",
+ "configure": "Yapılandır",
+ "networkError": "Ağ hatası",
+ "responseTime": "Yanıt süresi",
+ "ms": "ms",
+ "bar": "Çubuk",
+ "area": "Alan",
+ "country": "ÜLKE",
+ "city": "ŞEHİR",
+ "response": "YANIT",
+ "checkConnection": "Lütfen bağlantınızı kontrol edin",
+ "passwordreset": "Parola Sıfırlama",
+ "authRegisterStepOnePersonalDetails": "Kişisel bilgilerinizi girin",
+ "authCheckEmailOpenEmailButton": "Eposta uygulamasını aç",
+ "authNewPasswordConfirmed": "Parolanız başarıyla sıfırlandı. Otomatik olarak giriş yapmak için aşağıya tıklayın.",
+ "monitorStatusUp": "Monitör {name} ({url}) ayakta ve yanıt veriyor",
+ "monitorStatusDown": "Monitör {name} ({url}) yanıt vermiyor",
+ "webhookSendSuccess": "Web kanca bildirimi başarıyla gönderildi",
+ "webhookSendError": "Web kanca bildirimi bu platforma gönderilemedi: {platform}",
+ "webhookUnsupportedPlatform": "Desteklenmeyen platform: {platform}",
+ "distributedRightCategoryTitle": "Monitör",
+ "distributedStatusServerMonitors": "Sunucu monitörleri",
+ "distributedStatusServerMonitorsDescription": "İlgili sunucuların monitör durumları",
+ "distributedUptimeCreateSelectURL": "Burada sunucu adresini (URL) ve monitör türünü girebilirsiniz.",
+ "distributedUptimeCreateChecks": "Yapılacak kontroller",
+ "distributedUptimeCreateChecksDescription": "Adresi girdikten sonra kontrol ekleyebilir ya da çıkartabilirsiniz.",
+ "distributedUptimeCreateIncidentNotification": "Olay bildirimleri",
+ "distributedUptimeCreateIncidentDescription": "Bir olay olduğunda kullanıcıları bilgilendir.",
+ "distributedUptimeCreateAdvancedSettings": "Gelişmiş ayarlar",
+ "distributedUptimeDetailsNoMonitorHistory": "Bu monitör için henüz bir denetim günlüğü oluşturulmadı.",
+ "distributedUptimeDetailsFooterHeading": "UpRock & Bluewave Labs tarafından geliştirildi",
+ "distributedUptimeDetailsFooterBuilt": "Altyapı",
+ "distributedUptimeDetailsFooterSolana": "Solana",
+ "distributedUptimeDetailsMonitorHeader": "Depin Destekli Dağıtık Kesintisizlik İzleme",
+ "distributedUptimeDetailsStatusHeaderUptime": "Erişilebilirlik",
+ "distributedUptimeDetailsStatusHeaderLastUpdate": "Son güncelleme",
+ "notifications": {
+ "enableNotifications": "{{platform}} bildirimlerini etkinleştir",
+ "testNotification": "Bildirimi test et",
+ "addOrEditNotifications": "Bildirimleri ekle ya da düzenle",
+ "slack": {
+ "label": "Slack",
+ "description": "Slack bildirimlerini etkinleştirmek için bir Slack uygulaması oluşturun ve gelen web kancalarını etkinleştirin. Daha sonra, webhook URL’sini buraya girmeniz yeterlidir.\n\n\n\n\n\n",
+ "webhookLabel": "Web kanca URL:",
+ "webhookPlaceholder": "https://hooks.slack.com/services/...",
+ "webhookRequired": ""
+ },
+ "discord": {
+ "label": "Discord",
+ "description": "Checkmate’ten Discord bildirimleri aracılığıyla bir Discord kanalına veri göndermek için Discord’un gelen web kancaları özelliğini kullanabilirsiniz.\n\n\n\n\n\n\n\n",
+ "webhookLabel": "Discord web kanca URL",
+ "webhookPlaceholder": "https://discord.com/api/webhooks/...",
+ "webhookRequired": ""
+ },
+ "telegram": {
+ "label": "Telegram",
+ "description": "Telegram bildirimlerini etkinleştirmek için, Telegram botlarını oluşturup yönetmek için kullanılan resmi bot BotFather ile bir Telegram botu oluşturun. Daha sonra, API jetonunu (token) ve sohbet kimliğini (chat ID) alın ve buraya yazın.",
+ "tokenLabel": "Bot jetonu (token)",
+ "tokenPlaceholder": "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11",
+ "chatIdLabel": "Sohbet ID",
+ "chatIdPlaceholder": "-1001234567890",
+ "fieldsRequired": ""
+ },
+ "webhook": {
+ "label": "Web kancaları",
+ "description": "Olaylar meydana geldiğinde bildirim almak için özel bir web kancası ayarlayabilirsiniz.",
+ "urlLabel": "Web kanca URL:",
+ "urlPlaceholder": "https://sunucu-adresiniz.com/webhook",
+ "urlRequired": ""
+ },
+ "testNotificationDevelop": "Test bildirimi 2",
+ "integrationButton": "Bildirim Entegrasyonu",
+ "testSuccess": "",
+ "testFailed": "",
+ "unsupportedType": "",
+ "networkError": ""
+ },
+ "testLocale": "TEST13 UPLOAD",
+ "add": "Ekle",
+ "monitors": "Monitörler",
+ "distributedUptimeStatusCreateStatusPage": "durum sayfası",
+ "distributedUptimeStatusCreateStatusPageAccess": "Erişim",
+ "distributedUptimeStatusCreateStatusPageReady": "Durum sayfanız hazırsa yayınlayabilirsiniz.",
+ "distributedUptimeStatusBasicInfoHeader": "Temel bilgiler",
+ "distributedUptimeStatusBasicInfoDescription": "",
+ "distributedUptimeStatusLogoHeader": "Logo",
+ "distributedUptimeStatusLogoDescription": "Durum sayfanız için bir logo yükleyin",
+ "distributedUptimeStatusLogoUploadButton": "Logo yükle",
+ "distributedUptimeStatusStandardMonitorsHeader": "Standart monitörler",
+ "distributedUptimeStatusStandardMonitorsDescription": "Durum sayfanıza standart monitörleri ekleyin.",
+ "distributedUptimeStatusCreateYour": "",
+ "distributedUptimeStatusEditYour": "",
+ "distributedUptimeStatusPublishedLabel": "Yayında ve herkes tarafından görülebilir",
+ "distributedUptimeStatusCompanyNameLabel": "Şirket adı",
+ "distributedUptimeStatusPageAddressLabel": "Durum sayfası adresi",
+ "distributedUptimeStatus30Days": "30 gün",
+ "distributedUptimeStatus60Days": "60 gün",
+ "distributedUptimeStatus90Days": "90 gün",
+ "distributedUptimeStatusPageNotSetUp": "Henüz bir durum sayfası oluşturulmadı.",
+ "distributedUptimeStatusContactAdmin": "Lütfen yöneticiniz ile görüşün",
+ "distributedUptimeStatusPageNotPublic": "Bu durum sayfası herkese açık değil",
+ "distributedUptimeStatusPageDeleteDialog": "Bu durum sayfasını silmek istiyor musunuz? ",
+ "distributedUptimeStatusPageDeleteConfirm": "Evet, durum sayfasını sil",
+ "distributedUptimeStatusPageDeleteDescription": "Silindiği zaman durum sayfalarını geri getiremezsiniz.",
+ "distributedUptimeStatusDevices": "Cihazlar",
+ "distributedUptimeStatusUpt": "UPT",
+ "distributedUptimeStatusUptBurned": "Yakılan UPT",
+ "distributedUptimeStatusUptLogo": "Upt Logo",
+ "incidentsTableNoIncidents": "Hiç olay kaydedilmedi",
+ "incidentsTablePaginationLabel": "olaylar",
+ "incidentsTableMonitorName": "Monitör adı",
+ "incidentsTableStatus": "Durum",
+ "incidentsTableDateTime": "Tarih ve saat",
+ "incidentsTableStatusCode": "Durum kodu",
+ "incidentsTableMessage": "Mesaj",
+ "incidentsOptionsHeader": "Servisler:",
+ "incidentsOptionsHeaderFilterBy": "Filtrele:",
+ "incidentsOptionsHeaderFilterAll": "Tümü",
+ "incidentsOptionsHeaderFilterDown": "Erişilemiyor",
+ "incidentsOptionsHeaderFilterCannotResolve": "Çözümlenemiyor",
+ "incidentsOptionsHeaderShow": "Göster:",
+ "incidentsOptionsHeaderLastHour": "Son saat",
+ "incidentsOptionsHeaderLastDay": "Son gün",
+ "incidentsOptionsHeaderLastWeek": "Son hafta",
+ "incidentsOptionsPlaceholderAllServers": "Tüm sunucular",
+ "infrastructureCreateYour": "",
+ "infrastructureCreateGeneralSettingsDescription": "",
+ "infrastructureServerRequirement": "",
+ "infrastructureCustomizeAlerts": "Alarmları özelleştir",
+ "infrastructureAlertNotificationDescription": "",
+ "infrastructureCreateMonitor": "Altyapı Monitörü oluştur",
+ "infrastructureProtocol": "Protokol",
+ "infrastructureServerUrlLabel": "Sunucu adresi",
+ "infrastructureDisplayNameLabel": "Görünen adı",
+ "infrastructureAuthorizationSecretLabel": "Kimlik denetimi parolası",
+ "gb": "GB",
+ "mb": "MB",
+ "mem": "Bellek",
+ "memoryUsage": "Bellek kullanımı",
+ "cpu": "CPU",
+ "cpuUsage": "CPU kullanımı",
+ "cpuTemperature": "CPU sıcaklığı",
+ "diskUsage": "Disk kullanımı",
+ "used": "Kullanılan",
+ "total": "Toplam",
+ "cores": "Çekirdek",
+ "frequency": "Frekans",
+ "status": "Durum",
+ "cpuPhysical": "CPU (fiziksel)",
+ "cpuLogical": "CPU (Mantıksal)",
+ "cpuFrequency": "CPU Frekansı",
+ "avgCpuTemperature": "Ortalama CPU Isısı",
+ "memory": "Bellek",
+ "disk": "Disk",
+ "uptime": "",
+ "os": "İşletim sistemi",
+ "host": "Makine",
+ "actions": "İşlemler",
+ "integrations": "Entegrasyonlar",
+ "integrationsPrism": "Prism'i favori servisinize bağlayın.",
+ "integrationsSlack": "Slack",
+ "integrationsSlackInfo": "",
+ "integrationsDiscord": "Discord",
+ "integrationsDiscordInfo": "",
+ "integrationsZapier": "Zapier",
+ "integrationsZapierInfo": "",
+ "commonSave": "Kaydet",
+ "commonSaving": "Kaydediliyor...",
+ "createYour": "",
+ "createMonitor": "Monitör oluştur",
+ "pause": "Beklet",
+ "resume": "Yeniden başlat",
+ "editing": "Düzenleniyor...",
+ "url": "URL",
+ "access": "Erişim",
+ "timezone": "Zaman dilimi",
+ "features": "Özellikler",
+ "administrator": "Yönetici misin?",
+ "loginHere": "Buradan giriş yap",
+ "displayName": "Görüntülenecek isim",
+ "urlMonitor": "Monitör edilecek URL",
+ "portToMonitor": "Monitör edilecek port",
+ "websiteMonitoring": "Web sitesi monitörü",
+ "websiteMonitoringDescription": "",
+ "pingMonitoring": "Ping monitörü",
+ "pingMonitoringDescription": "Sitenizin ayakta olup olmadığını denetleyin.",
+ "dockerContainerMonitoring": "Docker konteyner monitörü",
+ "dockerContainerMonitoringDescription": "Docker konteynerinizin ayakta olup olmadığını denetleyin.",
+ "portMonitoring": "Port monitörü",
+ "portMonitoringDescription": "Portunuzun açık olup olmadığını denetleyin.",
+ "createMaintenanceWindow": "Bakım aralığı oluşturun",
+ "createMaintenance": "Bakım oluştur",
+ "editMaintenance": "Bakımı düzenle",
+ "maintenanceWindowName": "Bakım aralığı adı",
+ "friendlyNameInput": "Görünen ad",
+ "friendlyNamePlaceholder": "__:__ saatinde __ dakika boyunca bakım var",
+ "maintenanceRepeat": "Bakım Tekrarı",
+ "maintenance": "bakım",
+ "duration": "Süre",
+ "addMonitors": "Monitör ekle",
+ "window": "pencere",
+ "cancel": "İptal",
+ "message": "Mesaj",
+ "low": "düşük",
+ "high": "yüksek",
+ "statusCode": "Durum kodu",
+ "date&Time": "",
+ "type": "",
+ "statusPageName": "",
+ "publicURL": "",
+ "repeat": "",
+ "edit": "",
+ "createA": "",
+ "remove": "",
+ "maintenanceWindowDescription": "",
+ "startTime": "Başlangıç saati",
+ "timeZoneInfo": "",
+ "monitorsToApply": "",
+ "nextWindow": "Sonraki pencere",
+ "notFoundButton": "",
+ "pageSpeedConfigureSettingsDescription": "",
+ "monitorDisplayName": "",
+ "whenNewIncident": "Yeni bir olay oluştuğunda,",
+ "notifySMS": "",
+ "notifyEmails": "",
+ "seperateEmails": "",
+ "checkFrequency": "Frekansı denetle",
+ "matchMethod": "",
+ "expectedValue": "Beklenen değer",
+ "deleteDialogTitle": "Gerçekten bu monitörü silmek istiyor musunuz?",
+ "deleteDialogDescription": "Bir kez silindiği zaman tekrar getiremezsiniz.",
+ "pageSpeedMonitor": "Sayfa Hızı Monitörü",
+ "shown": "",
+ "ago": "",
+ "companyName": "Firma adı",
+ "pageSpeedDetailsPerformanceReport": "",
+ "pageSpeedDetailsPerformanceReportCalculator": "Hesap makinesini gör",
+ "checkingEvery": "Denetleme sıklığı",
+ "statusPageCreateSettings": "Eğer durum sayfanız hazırsa, herkese açık yayınlayabilirsiniz",
+ "basicInformation": "Temel Bilgiler",
+ "statusPageCreateBasicInfoDescription": "",
+ "statusPageCreateSelectTimeZoneDescription": "",
+ "statusPageCreateAppearanceDescription": "",
+ "statusPageCreateSettingsCheckboxLabel": "Yayınlandı ve herkese açık",
+ "statusPageCreateBasicInfoStatusPageAddress": "Durum sayfası adresiniz",
+ "statusPageCreateTabsContent": "Durum sayfası sunucuları",
+ "statusPageCreateTabsContentDescription": "",
+ "statusPageCreateTabsContentFeaturesDescription": "Durum sayfasında daha fazla bilgi göster",
+ "showCharts": "Çizelgeleri göster",
+ "showUptimePercentage": "",
+ "removeLogo": "Logoyu sil",
+ "statusPageStatus": "Herkese açık bir durum sayfası henüz oluşturulmadı.",
+ "statusPageStatusContactAdmin": "Lütfen yöneticinizle iletişime geçin.",
+ "statusPageStatusNotPublic": "Durum sayfası herkese açık değil.",
+ "statusPageStatusNoPage": "Burada bir durum sayfası bulunmuyor.",
+ "statusPageStatusServiceStatus": "Servis durumu",
+ "deleteStatusPage": "Gerçekten bu durum sayfasını silmek istiyor musunuz?",
+ "deleteStatusPageConfirm": "Evet, durum sayfasını sil",
+ "deleteStatusPageDescription": "Silindikten sonra durum sayfasını geri getiremezsiniz.",
+ "uptimeCreate": "",
+ "uptimeCreateJsonPath": "",
+ "uptimeCreateJsonPathQuery": "",
+ "maintenanceTableActionMenuDialogTitle": "Gerçekten bu bakım aralığını silmek istiyor musunuz?",
+ "infrastructureEditYour": "",
+ "infrastructureEditMonitor": "",
+ "infrastructureMonitorCreated": "",
+ "infrastructureMonitorUpdated": "",
+ "errorInvalidTypeId": "",
+ "pageSpeedWarning": "Uyarı: Google PageSpeed API anahtarı eklemediniz. Bu olmadan, PageSpeed monitörü çalışmayacaktır.",
+ "pageSpeedLearnMoreLink": "Daha fazla bilgi için tıklayın",
+ "pageSpeedAddApiKey": "API anahtarınızı nasıl ekleyeceğinizi öğrenin.",
+ "pageSpeedApiKeyFieldDescription": "Sayfa hızı izlemeyi etkinleştirmek için Google PageSpeed API anahtarınızı girin. Anahtarı güncellemek için Sıfırla'ya tıklayın.",
+ "pageSpeedApiKeyFieldResetLabel": "API anahtarı ayarlandı. Değiştirmek için Sıfırla'ya tıklayın.",
+ "reset": "Sıfırla",
+ "invalidFileFormat": "",
+ "invalidFileSize": "",
+ "ClickUpload": "",
+ "DragandDrop": "",
+ "MaxSize": "",
+ "SupportedFormats": "",
+ "FirstName": "Ad",
+ "LastName": "Soyad",
+ "EmailDescriptionText": "Mevcut e-postanız—değiştirilemez.",
+ "YourPhoto": "Profil fotoğrafı",
+ "PhotoDescriptionText": "Bu fotoğraf profil sayfanızda görüntülenecektir.",
+ "save": "",
+ "DeleteAccountTitle": "Hesabı kaldır",
+ "DeleteAccountButton": "Hesabı kaldır",
+ "DeleteDescriptionText": "Bu, hesabı ve tüm ilişkili verileri sunucudan kaldıracaktır. Bu geri alınamaz.",
+ "DeleteAccountWarning": "Hesabınızı kaldırmak, tekrar oturum açamayacağınız ve tüm verilerinizin kaldırılacağı anlamına gelir. Bu geri alınamaz.",
+ "DeleteWarningTitle": "Bu hesabı gerçekten kaldırmak istiyor musunuz?",
+ "authRegisterFirstName": "Ad",
+ "authRegisterLastName": "Soyad",
+ "authRegisterEmail": "E-posta",
+ "authRegisterEmailRequired": "Devam etmek için lütfen e-posta adresinizi girin",
+ "authRegisterEmailInvalid": "Lütfen geçerli bir e-posta adresi girin",
+ "bulkImport": {
+ "title": "Toplu İçe Aktar",
+ "selectFileTips": "Yüklemek için CSV dosyası seçin",
+ "selectFileDescription": "Şablonumuzu veya örneğimizi indirebilirsiniz",
+ "selectFile": "Dosya Seç",
+ "parsingFailed": "Ayrıştırma başarısız oldu",
+ "uploadSuccess": "Monitörler başarıyla oluşturuldu!",
+ "validationFailed": "Doğrulama başarısız oldu",
+ "noFileSelected": "Dosya seçilmedi",
+ "fallbackPage": "Sunucuların listesini toplu olarak yüklemek için bir dosya içe aktarın"
+ },
+ "createNew": "Yeni oluştur",
+ "greeting": {
+ "prepend": "Merhaba",
+ "append": "Öğleden sonra senin oyun alanın—hadi onu muhteşem yapalım!",
+ "overview": "İşte {{type}} monitörlerinizin genel görünümü."
+ },
+ "monitorStatus": {
+ "up": "aktif",
+ "down": "devre dışı",
+ "paused": "duraklatıldı"
+ },
+ "roles": {
+ "superAdmin": "Süper yönetici",
+ "admin": "Yönetici",
+ "teamMember": "Takım üyesi",
+ "demoUser": "Demo kullanıcı"
+ },
+ "teamPanel": {
+ "teamMembers": "Takım üyeleri",
+ "filter": {
+ "all": "Tümü",
+ "member": "Üye"
+ },
+ "inviteTeamMember": "Takım üyesi davet et",
+ "inviteNewTeamMember": "Yeni takım üyesi davet et",
+ "inviteDescription": "Yeni bir takım üyesi eklediğinizde, tüm monitörlere erişim hakkı alacaktır.",
+ "email": "E-posta",
+ "selectRole": "Rol seçin",
+ "inviteLink": "Davet bağlantısı",
+ "cancel": "İptal",
+ "noMembers": "Bu role sahip takım üyesi bulunmamaktadır",
+ "getToken": "Token al",
+ "emailToken": "Token e-posta ile gönder",
+ "table": {
+ "name": "Ad",
+ "email": "E-posta",
+ "role": "Rol",
+ "created": "Oluşturuldu"
+ }
+ },
+ "monitorState": {
+ "paused": "duraklatıldı",
+ "resumed": "devam ettirildi",
+ "active": "aktif"
+ },
+ "menu": {
+ "uptime": "Çalışma Süresi",
+ "pagespeed": "Sayfa Hızı",
+ "infrastructure": "Altyapı",
+ "distributedUptime": "Dağıtılmış Çalışma Süresi",
+ "incidents": "Olaylar",
+ "statusPages": "Durum Sayfaları",
+ "maintenance": "Bakım",
+ "integrations": "Entegrasyonlar",
+ "settings": "Ayarlar",
+ "support": "Destek",
+ "discussions": "Tartışmalar",
+ "docs": "Belgeler",
+ "changelog": "Değişiklik Günlüğü",
+ "profile": "Profil",
+ "password": "Şifre",
+ "team": "Takım",
+ "logOut": "Çıkış"
+ },
+ "navControls": "Kontroller",
+ "statusBreadCrumbsStatusPages": "Durum Sayfaları",
+ "statusBreadCrumbsDetails": "Detaylar",
+ "incidentsPageTitle": "Olaylar",
+ "passwordPanel": {
+ "passwordChangedSuccess": "Şifreniz başarıyla değiştirildi.",
+ "passwordInputIncorrect": "Şifre girişiniz yanlış.",
+ "currentPassword": "Mevcut şifre",
+ "enterCurrentPassword": "Mevcut şifrenizi girin",
+ "newPassword": "Yeni şifre",
+ "enterNewPassword": "Yeni şifrenizi girin",
+ "confirmNewPassword": "Yeni şifreyi onaylayın",
+ "passwordRequirements": "Yeni şifre en az 8 karakter içermeli ve en az bir büyük harf, bir küçük harf, bir rakam ve bir özel karakter içermelidir.",
+ "saving": "Kaydediliyor..."
+ },
+ "uptimeCreateSelectURL": "İzlenecek URL veya IP adresini girin (örn. https://example.com/ veya 192.168.1.100) ve kontrol panelinde görünecek net bir görüntü adı ekleyin."
+}
diff --git a/Client/src/main.jsx b/client/src/main.jsx
similarity index 96%
rename from Client/src/main.jsx
rename to client/src/main.jsx
index c07cad40b..4be45e6d7 100644
--- a/Client/src/main.jsx
+++ b/client/src/main.jsx
@@ -1,6 +1,7 @@
import ReactDOM from "react-dom/client";
import App from "./App.jsx";
import "./index.css";
+import "./Utils/i18n";
import { BrowserRouter as Router } from "react-router-dom";
import { Provider } from "react-redux";
import { persistor, store } from "./store";
diff --git a/Client/src/store.js b/client/src/store.js
similarity index 100%
rename from Client/src/store.js
rename to client/src/store.js
diff --git a/Client/vite.config.js b/client/vite.config.js
similarity index 100%
rename from Client/vite.config.js
rename to client/vite.config.js
diff --git a/Docker/.gitignore b/docker/.gitignore
old mode 100644
new mode 100755
similarity index 84%
rename from Docker/.gitignore
rename to docker/.gitignore
index 9b501e10d..1e35b3731
--- a/Docker/.gitignore
+++ b/docker/.gitignore
@@ -7,5 +7,6 @@ dist/mongo/data/*
dist/redis/data/*
prod/mongo/data/*
prod/redis/data/*
+dist/docker-compose-test.yaml
*.env
prod/certbot/*
\ No newline at end of file
diff --git a/Docker/dev/build_images.sh b/docker/coolify/build_images.sh
similarity index 57%
rename from Docker/dev/build_images.sh
rename to docker/coolify/build_images.sh
index f6171089c..179b50b5b 100755
--- a/Docker/dev/build_images.sh
+++ b/docker/coolify/build_images.sh
@@ -1,22 +1,21 @@
#!/bin/bash
-
# Change directory to root Server directory for correct Docker Context
cd "$(dirname "$0")"
-cd ../..
+cd ../../../
# Define an array of services and their Dockerfiles
declare -A services=(
- ["uptime_client"]="./Docker/dev/client.Dockerfile"
- ["uptime_database_mongo"]="./Docker/dev/mongoDB.Dockerfile"
- ["uptime_redis"]="./Docker/dev/redis.Dockerfile"
- ["uptime_server"]="./Docker/dev/server.Dockerfile"
+ ["bluewaveuptime/uptime_client"]="./server/docker/dist/client.Dockerfile"
+ ["bluewaveuptime/uptime_database_mongo"]="./server/docker/dist/mongoDB.Dockerfile"
+ ["bluewaveuptime/uptime_redis"]="./server/docker/dist/redis.Dockerfile"
+ ["bluewaveuptime/uptime_server"]="./server/docker/dist/server.Dockerfile"
)
# Loop through each service and build the corresponding image
for service in "${!services[@]}"; do
docker build -f "${services[$service]}" -t "$service" .
- ## Check if the build succeeded
+ # Check if the build succeeded
if [ $? -ne 0 ]; then
echo "Error building $service image. Exiting..."
exit 1
diff --git a/docker/coolify/client.Dockerfile b/docker/coolify/client.Dockerfile
new file mode 100755
index 000000000..1384bfa2c
--- /dev/null
+++ b/docker/coolify/client.Dockerfile
@@ -0,0 +1,31 @@
+FROM node:20-alpine AS build
+
+ENV NODE_OPTIONS="--max-old-space-size=4096"
+
+WORKDIR /app
+
+RUN apk add --no-cache \
+ python3 \
+ make g++ \
+ gcc \
+ libc-dev \
+ linux-headers \
+ libusb-dev \
+ eudev-dev
+
+COPY ./client/package*.json ./
+
+RUN npm install
+
+COPY ./client .
+
+RUN npm run build
+
+FROM nginx:1.27.1-alpine
+
+COPY ./server/docker/dist/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf
+COPY --from=build /app/dist /usr/share/nginx/html
+COPY --from=build /app/env.sh /docker-entrypoint.d/env.sh
+RUN chmod +x /docker-entrypoint.d/env.sh
+
+CMD ["nginx", "-g", "daemon off;"]
diff --git a/Docker/dev/mongoDB.Dockerfile b/docker/coolify/mongoDB.Dockerfile
old mode 100644
new mode 100755
similarity index 100%
rename from Docker/dev/mongoDB.Dockerfile
rename to docker/coolify/mongoDB.Dockerfile
diff --git a/Docker/dist/nginx/conf.d/default.conf b/docker/coolify/nginx/conf.d/default.conf
old mode 100644
new mode 100755
similarity index 100%
rename from Docker/dist/nginx/conf.d/default.conf
rename to docker/coolify/nginx/conf.d/default.conf
diff --git a/Docker/dev/redis.Dockerfile b/docker/coolify/redis.Dockerfile
old mode 100644
new mode 100755
similarity index 100%
rename from Docker/dev/redis.Dockerfile
rename to docker/coolify/redis.Dockerfile
diff --git a/Docker/test/prod/server.Dockerfile b/docker/coolify/server.Dockerfile
old mode 100644
new mode 100755
similarity index 65%
rename from Docker/test/prod/server.Dockerfile
rename to docker/coolify/server.Dockerfile
index 5d4ea7364..611a325a5
--- a/Docker/test/prod/server.Dockerfile
+++ b/docker/coolify/server.Dockerfile
@@ -2,11 +2,11 @@ FROM node:20-alpine
WORKDIR /app
-COPY ./Server/package*.json ./
+COPY ../../package*.json ./
RUN npm install
-COPY ./Server/ ./
+COPY ../../ ./
EXPOSE 5000
diff --git a/docker/dev/build_images.sh b/docker/dev/build_images.sh
new file mode 100755
index 000000000..e94be9fa5
--- /dev/null
+++ b/docker/dev/build_images.sh
@@ -0,0 +1,30 @@
+#!/bin/bash
+
+# Change directory to root Server directory for correct Docker Context
+cd "$(dirname "$0")"
+cd ../..
+
+# Define service names and their corresponding Dockerfiles in parallel arrays
+services=("uptime_client" "uptime_mongo" "uptime_redis" "uptime_server")
+dockerfiles=(
+ "./docker/dev/client.Dockerfile"
+ "./docker/dev/mongoDB.Dockerfile"
+ "./docker/dev/redis.Dockerfile"
+ "./docker/dev/server.Dockerfile"
+)
+
+# Loop through each service and build the corresponding image
+for i in "${!services[@]}"; do
+ service="${services[$i]}"
+ dockerfile="${dockerfiles[$i]}"
+
+ docker build -f "$dockerfile" -t "$service" .
+
+ # Check if the build succeeded
+ if [ $? -ne 0 ]; then
+ echo "Error building $service image. Exiting..."
+ exit 1
+ fi
+done
+
+echo "All images built successfully"
\ No newline at end of file
diff --git a/Docker/prod/client.Dockerfile b/docker/dev/client.Dockerfile
old mode 100644
new mode 100755
similarity index 56%
rename from Docker/prod/client.Dockerfile
rename to docker/dev/client.Dockerfile
index 1619b5e41..aa4d228fc
--- a/Docker/prod/client.Dockerfile
+++ b/docker/dev/client.Dockerfile
@@ -1,12 +1,24 @@
FROM node:20-alpine AS build
+ENV NODE_OPTIONS="--max-old-space-size=4096"
+
WORKDIR /app
-COPY ../../Client/package*.json ./
+RUN apk add --no-cache \
+ python3 \
+ make g++ \
+ gcc \
+ libc-dev \
+ linux-headers \
+ libusb-dev \
+ eudev-dev
+
+
+COPY ./client/package*.json ./
RUN npm install
-COPY ../../Client .
+COPY ./client ./
RUN npm run build
diff --git a/docker/dev/docker-compose.yaml b/docker/dev/docker-compose.yaml
new file mode 100755
index 000000000..292d0b1d5
--- /dev/null
+++ b/docker/dev/docker-compose.yaml
@@ -0,0 +1,47 @@
+services:
+ client:
+ image: uptime_client:latest
+ restart: always
+ ports:
+ - "80:80"
+ environment:
+ UPTIME_APP_API_BASE_URL: "http://localhost:52345/api/v1"
+ UPTIME_APP_CLIENT_HOST: "http://localhost"
+ volumes:
+ - ./nginx/conf.d:/etc/nginx/conf.d/
+ depends_on:
+ - server
+ server:
+ image: uptime_server:latest
+ restart: always
+ ports:
+ - "52345:52345"
+ env_file:
+ - server.env
+ depends_on:
+ - redis
+ - mongodb
+ redis:
+ image: uptime_redis:latest
+ restart: always
+ volumes:
+ - ./redis/data:/data
+ healthcheck:
+ test: ["CMD", "redis-cli", "ping"]
+ interval: 30s
+ timeout: 10s
+ retries: 5
+ start_period: 5s
+ mongodb:
+ image: uptime_mongo:latest
+ restart: always
+ command: ["mongod", "--quiet", "--replSet", "rs0", "--bind_ip_all"]
+ volumes:
+ - ./mongo/data:/data/db
+ healthcheck:
+ test: echo "try { rs.status() } catch (err) { rs.initiate({_id:'rs0',members:[{_id:0,host:'mongodb:27017'}]}) }" | mongosh --port 27017 --quiet
+ interval: 5s
+ timeout: 30s
+ start_period: 0s
+ start_interval: 1s
+ retries: 30
diff --git a/Docker/dist/mongoDB.Dockerfile b/docker/dev/mongoDB.Dockerfile
old mode 100644
new mode 100755
similarity index 100%
rename from Docker/dist/mongoDB.Dockerfile
rename to docker/dev/mongoDB.Dockerfile
diff --git a/docker/dev/nginx/conf.d/default.conf b/docker/dev/nginx/conf.d/default.conf
new file mode 100755
index 000000000..e2c2a7268
--- /dev/null
+++ b/docker/dev/nginx/conf.d/default.conf
@@ -0,0 +1,35 @@
+server {
+ listen 80 default_server;
+ listen [::]:80 default_server;
+
+ server_name localhost; # Set server name to localhost
+ server_tokens off;
+
+ location / {
+ root /usr/share/nginx/html;
+ index index.html index.htm;
+ try_files $uri $uri/ /index.html;
+ }
+
+ # location /api/ {
+ # proxy_pass http://server:52345/api/;
+ # proxy_http_version 1.1;
+ # proxy_set_header Host $host;
+ # proxy_set_header X-Real-IP $remote_addr;
+ # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ # proxy_set_header X-Forwarded-Proto $scheme;
+ # proxy_set_header Connection '';
+ # chunked_transfer_encoding off;
+ # proxy_buffering off;
+ # proxy_cache off;
+ # }
+
+ # location /api-docs/ {
+ # proxy_pass http://server:52345/api-docs/;
+ # proxy_http_version 1.1;
+ # proxy_set_header Host $host;
+ # proxy_set_header X-Real-IP $remote_addr;
+ # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ # proxy_set_header X-Forwarded-Proto $scheme;
+ # }
+}
\ No newline at end of file
diff --git a/Docker/dist/redis.Dockerfile b/docker/dev/redis.Dockerfile
old mode 100644
new mode 100755
similarity index 100%
rename from Docker/dist/redis.Dockerfile
rename to docker/dev/redis.Dockerfile
diff --git a/Docker/test/server.Dockerfile b/docker/dev/server.Dockerfile
old mode 100644
new mode 100755
similarity index 56%
rename from Docker/test/server.Dockerfile
rename to docker/dev/server.Dockerfile
index 5d4ea7364..d9d99a09d
--- a/Docker/test/server.Dockerfile
+++ b/docker/dev/server.Dockerfile
@@ -2,12 +2,12 @@ FROM node:20-alpine
WORKDIR /app
-COPY ./Server/package*.json ./
+COPY ./server/package*.json ./
RUN npm install
-COPY ./Server/ ./
+COPY ./server/ ./
-EXPOSE 5000
+EXPOSE 52345
CMD ["node", "index.js"]
\ No newline at end of file
diff --git a/Docker/dist/build_images.sh b/docker/dist/build_images.sh
similarity index 62%
rename from Docker/dist/build_images.sh
rename to docker/dist/build_images.sh
index 33af5efdf..e0d83a5d8 100755
--- a/Docker/dist/build_images.sh
+++ b/docker/dist/build_images.sh
@@ -1,15 +1,14 @@
#!/bin/bash
-
# Change directory to root Server directory for correct Docker Context
cd "$(dirname "$0")"
-cd ../..
+cd ../../
# Define an array of services and their Dockerfiles
declare -A services=(
- ["bluewaveuptime/uptime_client"]="./Docker/dist/client.Dockerfile"
- ["bluewaveuptime/uptime_database_mongo"]="./Docker/dist/mongoDB.Dockerfile"
- ["bluewaveuptime/uptime_redis"]="./Docker/dist/redis.Dockerfile"
- ["bluewaveuptime/uptime_server"]="./Docker/dist/server.Dockerfile"
+ ["bluewaveuptime/uptime_client"]="./docker/dist/client.Dockerfile"
+ ["bluewaveuptime/uptime_database_mongo"]="./docker/dist/mongoDB.Dockerfile"
+ ["bluewaveuptime/uptime_redis"]="./docker/dist/redis.Dockerfile"
+ ["bluewaveuptime/uptime_server"]="./docker/dist/server.Dockerfile"
)
# Loop through each service and build the corresponding image
@@ -23,4 +22,4 @@ for service in "${!services[@]}"; do
fi
done
-echo "All images built successfully"
\ No newline at end of file
+echo "All images built successfully"
diff --git a/docker/dist/client.Dockerfile b/docker/dist/client.Dockerfile
new file mode 100755
index 000000000..6491f4bbb
--- /dev/null
+++ b/docker/dist/client.Dockerfile
@@ -0,0 +1,31 @@
+FROM node:20-alpine AS build
+
+ENV NODE_OPTIONS="--max-old-space-size=4096"
+
+WORKDIR /app
+
+RUN apk add --no-cache \
+ python3 \
+ make g++ \
+ gcc \
+ libc-dev \
+ linux-headers \
+ libusb-dev \
+ eudev-dev
+
+COPY ./client/package*.json ./
+
+RUN npm install
+
+COPY ./client .
+
+RUN npm run build
+
+FROM nginx:1.27.1-alpine
+
+COPY ./docker/dist/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf
+COPY --from=build /app/dist /usr/share/nginx/html
+COPY --from=build /app/env.sh /docker-entrypoint.d/env.sh
+RUN chmod +x /docker-entrypoint.d/env.sh
+
+CMD ["nginx", "-g", "daemon off;"]
diff --git a/docker/dist/docker-compose.yaml b/docker/dist/docker-compose.yaml
new file mode 100755
index 000000000..a5da9d021
--- /dev/null
+++ b/docker/dist/docker-compose.yaml
@@ -0,0 +1,51 @@
+services:
+ client:
+ image: ghcr.io/bluewave-labs/checkmate:frontend-dist
+ restart: always
+ environment:
+ UPTIME_APP_API_BASE_URL: "http://localhost:52345/api/v1"
+ UPTIME_APP_CLIENT_HOST: "http://localhost"
+ ports:
+ - "80:80"
+ - "443:443"
+ depends_on:
+ - server
+ server:
+ image: ghcr.io/bluewave-labs/checkmate:backend-dist
+ restart: always
+ ports:
+ - "52345:52345"
+ depends_on:
+ - redis
+ - mongodb
+ environment:
+ - DB_CONNECTION_STRING=mongodb://mongodb:27017/uptime_db?replicaSet=rs0
+ - REDIS_URL=redis://redis:6379
+ - CLIENT_HOST=http://localhost
+ - JWT_SECRET=my_secret
+ # volumes:
+ # - /var/run/docker.sock:/var/run/docker.sock:ro
+ redis:
+ image: ghcr.io/bluewave-labs/checkmate:redis-dist
+ restart: always
+ volumes:
+ - ./redis/data:/data
+ healthcheck:
+ test: ["CMD", "redis-cli", "ping"]
+ interval: 30s
+ timeout: 10s
+ retries: 5
+ start_period: 5s
+ mongodb:
+ image: ghcr.io/bluewave-labs/checkmate:mongo-dist
+ restart: always
+ volumes:
+ - ./mongo/data:/data/db
+ command: ["mongod", "--quiet", "--replSet", "rs0", "--bind_ip_all"]
+ healthcheck:
+ test: echo "try { rs.status() } catch (err) { rs.initiate({_id:'rs0',members:[{_id:0,host:'mongodb:27017'}]}) }" | mongosh --port 27017 --quiet
+ interval: 5s
+ timeout: 30s
+ start_period: 0s
+ start_interval: 1s
+ retries: 30
diff --git a/docker/dist/mongoDB.Dockerfile b/docker/dist/mongoDB.Dockerfile
new file mode 100755
index 000000000..969a320c2
--- /dev/null
+++ b/docker/dist/mongoDB.Dockerfile
@@ -0,0 +1,3 @@
+FROM mongo
+EXPOSE 27017
+CMD ["mongod"]
diff --git a/docker/dist/nginx/conf.d/default.conf b/docker/dist/nginx/conf.d/default.conf
new file mode 100755
index 000000000..30e51c71c
--- /dev/null
+++ b/docker/dist/nginx/conf.d/default.conf
@@ -0,0 +1,35 @@
+server {
+ listen 80;
+ listen [::]:80;
+
+ server_name checkmate-demo.bluewavelabs.ca;
+ server_tokens off;
+
+ location /.well-known/acme-challenge/ {
+ root /var/www/certbot;
+ }
+
+ location / {
+ root /usr/share/nginx/html;
+ index index.html index.htm;
+ try_files $uri $uri/ /index.html;
+ }
+
+ # location /api/ {
+ # proxy_pass http://server:5000/api/;
+ # proxy_http_version 1.1;
+ # proxy_set_header Host $host;
+ # proxy_set_header X-Real-IP $remote_addr;
+ # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ # proxy_set_header X-Forwarded-Proto $scheme;
+ # }
+
+ location /api-docs/ {
+ proxy_pass http://server:5000/api-docs/;
+ proxy_http_version 1.1;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ }
+}
\ No newline at end of file
diff --git a/Docker/prod/redis.Dockerfile b/docker/dist/redis.Dockerfile
old mode 100644
new mode 100755
similarity index 100%
rename from Docker/prod/redis.Dockerfile
rename to docker/dist/redis.Dockerfile
diff --git a/Docker/dev/server.Dockerfile b/docker/dist/server.Dockerfile
old mode 100644
new mode 100755
similarity index 53%
rename from Docker/dev/server.Dockerfile
rename to docker/dist/server.Dockerfile
index 3a9ed5907..d9d99a09d
--- a/Docker/dev/server.Dockerfile
+++ b/docker/dist/server.Dockerfile
@@ -2,12 +2,12 @@ FROM node:20-alpine
WORKDIR /app
-COPY ../../Server/package*.json ./
+COPY ./server/package*.json ./
RUN npm install
-COPY ../../Server/ ./
+COPY ./server/ ./
-EXPOSE 5000
+EXPOSE 52345
CMD ["node", "index.js"]
\ No newline at end of file
diff --git a/Docker/prod/build_images.sh b/docker/prod/build_images.sh
similarity index 68%
rename from Docker/prod/build_images.sh
rename to docker/prod/build_images.sh
index c879190bc..23e91355c 100755
--- a/Docker/prod/build_images.sh
+++ b/docker/prod/build_images.sh
@@ -2,14 +2,14 @@
# Change directory to root directory for correct Docker Context
cd "$(dirname "$0")"
-cd ../..
+cd ../../
# Define an array of services and their Dockerfiles
declare -A services=(
- ["uptime_client"]="./Docker/prod/client.Dockerfile"
- ["uptime_database_mongo"]="./Docker/prod/mongoDB.Dockerfile"
- ["uptime_redis"]="./Docker/prod/redis.Dockerfile"
- ["uptime_server"]="./Docker/prod/server.Dockerfile"
+ ["uptime_client"]="./docker/prod/client.Dockerfile"
+ ["uptime_database_mongo"]="./docker/prod/mongoDB.Dockerfile"
+ ["uptime_redis"]="./docker/prod/redis.Dockerfile"
+ ["uptime_server"]="./docker/prod/server.Dockerfile"
)
# Loop through each service and build the corresponding image
diff --git a/Docker/test/cerbot-compose.yaml b/docker/prod/certbot-compose.yaml
old mode 100644
new mode 100755
similarity index 100%
rename from Docker/test/cerbot-compose.yaml
rename to docker/prod/certbot-compose.yaml
diff --git a/Docker/dist/client.Dockerfile b/docker/prod/client.Dockerfile
old mode 100644
new mode 100755
similarity index 56%
rename from Docker/dist/client.Dockerfile
rename to docker/prod/client.Dockerfile
index 3c4f577c0..e81a1af26
--- a/Docker/dist/client.Dockerfile
+++ b/docker/prod/client.Dockerfile
@@ -1,21 +1,29 @@
FROM node:20-alpine AS build
+ENV NODE_OPTIONS="--max-old-space-size=4096"
+
WORKDIR /app
-COPY ../../Client/package*.json ./
+RUN apk add --no-cache \
+ python3 \
+ make g++ \
+ gcc \
+ libc-dev \
+ linux-headers \
+ libusb-dev \
+ eudev-dev
+
+COPY ./client/package*.json ./
RUN npm install
-COPY ../../Client .
+COPY ./client .
RUN npm run build
-
FROM nginx:1.27.1-alpine
-COPY ./Docker/dist/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
COPY --from=build /app/env.sh /docker-entrypoint.d/env.sh
RUN chmod +x /docker-entrypoint.d/env.sh
-
CMD ["nginx", "-g", "daemon off;"]
\ No newline at end of file
diff --git a/Docker/prod/docker-compose.yaml b/docker/prod/docker-compose.yaml
old mode 100644
new mode 100755
similarity index 54%
rename from Docker/prod/docker-compose.yaml
rename to docker/prod/docker-compose.yaml
index 2f8907089..9cc4a82cb
--- a/Docker/prod/docker-compose.yaml
+++ b/docker/prod/docker-compose.yaml
@@ -1,9 +1,10 @@
services:
client:
- image: uptime_client:latest
+ image: ghcr.io/bluewave-labs/checkmate:frontend-demo
restart: always
environment:
UPTIME_APP_API_BASE_URL: "https://checkmate-demo.bluewavelabs.ca/api/v1"
+ UPTIME_APP_CLIENT_HOST: "https://checkmate-demo.bluewavelabs.ca"
ports:
- "80:80"
- "443:443"
@@ -21,20 +22,20 @@ services:
- ./certbot/www/:/var/www/certbot/:rw
- ./certbot/conf/:/etc/letsencrypt/:rw
server:
- image: uptime_server:latest
+ image: ghcr.io/bluewave-labs/checkmate:backend-demo
restart: always
ports:
- - "5000:5000"
+ - "52345:52345"
env_file:
- server.env
depends_on:
- redis
- mongodb
+ volumes:
+ - /var/run/docker.sock:/var/run/docker.sock:ro
redis:
- image: uptime_redis:latest
+ image: ghcr.io/bluewave-labs/checkmate:redis-demo
restart: always
- ports:
- - "6379:6379"
volumes:
- ./redis/data:/data
healthcheck:
@@ -44,13 +45,18 @@ services:
retries: 5
start_period: 5s
mongodb:
- image: uptime_database_mongo:latest
+ image: ghcr.io/bluewave-labs/checkmate:mongo-demo
restart: always
- command: ["mongod", "--quiet", "--auth"]
- ports:
- - "27017:27017"
+ command: ["mongod", "--quiet", "--replSet", "rs0", "--bind_ip_all"]
volumes:
- ./mongo/data:/data/db
- - ./mongo/init/create_users.js:/docker-entrypoint-initdb.d/create_users.js
+ # - ./mongo/init/init.js:/docker-entrypoint-initdb.d/init.js // No longer needed
env_file:
- mongo.env
+ healthcheck:
+ test: echo "try { rs.status() } catch (err) { rs.initiate({_id:'rs0',members:[{_id:0,host:'mongodb:27017'}]}) }" | mongosh --port 27017 --quiet
+ interval: 5s
+ timeout: 30s
+ start_period: 0s
+ start_interval: 1s
+ retries: 30
diff --git a/docker/prod/mongo/init/init.js b/docker/prod/mongo/init/init.js
new file mode 100644
index 000000000..34b90ced3
--- /dev/null
+++ b/docker/prod/mongo/init/init.js
@@ -0,0 +1,41 @@
+function initiateReplicaSet() {
+ try {
+ rs.initiate({
+ _id: "rs0",
+ members: [{ _id: 0, host: "localhost:27017" }],
+ });
+ } catch (e) {
+ print("Replica set already initiated or error occurred: " + e);
+ }
+}
+
+function waitForPrimary() {
+ while (true) {
+ const isMaster = db.isMaster();
+ if (isMaster.ismaster) {
+ print("This node is now PRIMARY.");
+ break;
+ }
+ print("Waiting to become PRIMARY...");
+ sleep(2000);
+ }
+}
+
+function createUser() {
+ db = db.getSiblingDB("uptime_db");
+
+ var username = process.env.USERNAME_ENV_VAR;
+ var password = process.env.PASSWORD_ENV_VAR;
+
+ db.createUser({
+ user: username,
+ pwd: password,
+ roles: [{ role: "readWrite", db: "uptime_db" }],
+ });
+
+ print("User '" + username + "' created successfully");
+}
+
+initiateReplicaSet();
+waitForPrimary();
+createUser();
diff --git a/docker/prod/mongoDB.Dockerfile b/docker/prod/mongoDB.Dockerfile
new file mode 100755
index 000000000..969a320c2
--- /dev/null
+++ b/docker/prod/mongoDB.Dockerfile
@@ -0,0 +1,3 @@
+FROM mongo
+EXPOSE 27017
+CMD ["mongod"]
diff --git a/Docker/prod/nginx/conf.d/cerbot b/docker/prod/nginx/conf.d/cerbot
old mode 100644
new mode 100755
similarity index 100%
rename from Docker/prod/nginx/conf.d/cerbot
rename to docker/prod/nginx/conf.d/cerbot
diff --git a/Docker/prod/nginx/conf.d/default.conf b/docker/prod/nginx/conf.d/default.conf
old mode 100644
new mode 100755
similarity index 90%
rename from Docker/prod/nginx/conf.d/default.conf
rename to docker/prod/nginx/conf.d/default.conf
index 98e1bd97d..8afeb93b7
--- a/Docker/prod/nginx/conf.d/default.conf
+++ b/docker/prod/nginx/conf.d/default.conf
@@ -16,7 +16,7 @@ server {
}
location /api/ {
- proxy_pass http://server:5000/api/;
+ proxy_pass http://server:52345/api/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
@@ -25,7 +25,7 @@ server {
}
location /api-docs/ {
- proxy_pass http://server:5000/api-docs/;
+ proxy_pass http://server:52345/api-docs/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
@@ -50,7 +50,7 @@ server {
}
location /api/ {
- proxy_pass http://server:5000/api/;
+ proxy_pass http://server:52345/api/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
@@ -59,7 +59,7 @@ server {
}
location /api-docs/ {
- proxy_pass http://server:5000/api-docs/;
+ proxy_pass http://server:52345/api-docs/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
diff --git a/Docker/test/prod/redis.Dockerfile b/docker/prod/redis.Dockerfile
old mode 100644
new mode 100755
similarity index 100%
rename from Docker/test/prod/redis.Dockerfile
rename to docker/prod/redis.Dockerfile
diff --git a/Docker/prod/server.Dockerfile b/docker/prod/server.Dockerfile
old mode 100644
new mode 100755
similarity index 67%
rename from Docker/prod/server.Dockerfile
rename to docker/prod/server.Dockerfile
index 707b774e7..c80f468f8
--- a/Docker/prod/server.Dockerfile
+++ b/docker/prod/server.Dockerfile
@@ -4,12 +4,12 @@ ENV NODE_OPTIONS="--max-old-space-size=2048"
WORKDIR /app
-COPY ./Server/package*.json ./
+COPY ./server/package*.json ./
RUN npm install
-COPY ./Server/ ./
+COPY ./server ./
-EXPOSE 5000
+EXPOSE 52345
CMD ["node", "index.js"]
\ No newline at end of file
diff --git a/Docker/test/prod/build_images.sh b/docker/staging/build_images.sh
similarity index 67%
rename from Docker/test/prod/build_images.sh
rename to docker/staging/build_images.sh
index c879190bc..ccfd451ba 100755
--- a/Docker/test/prod/build_images.sh
+++ b/docker/staging/build_images.sh
@@ -2,14 +2,14 @@
# Change directory to root directory for correct Docker Context
cd "$(dirname "$0")"
-cd ../..
+cd ../../
# Define an array of services and their Dockerfiles
declare -A services=(
- ["uptime_client"]="./Docker/prod/client.Dockerfile"
- ["uptime_database_mongo"]="./Docker/prod/mongoDB.Dockerfile"
- ["uptime_redis"]="./Docker/prod/redis.Dockerfile"
- ["uptime_server"]="./Docker/prod/server.Dockerfile"
+ ["uptime_client"]="./docker/staging/client.Dockerfile"
+ ["uptime_database_mongo"]="./docker/staging/mongoDB.Dockerfile"
+ ["uptime_redis"]="./docker/staging/redis.Dockerfile"
+ ["uptime_server"]="./docker/staging/server.Dockerfile"
)
# Loop through each service and build the corresponding image
diff --git a/Docker/prod/certbot-compose.yaml b/docker/staging/cerbot-compose.yaml
old mode 100644
new mode 100755
similarity index 96%
rename from Docker/prod/certbot-compose.yaml
rename to docker/staging/cerbot-compose.yaml
index 274f15b0c..9220d07a1
--- a/Docker/prod/certbot-compose.yaml
+++ b/docker/staging/cerbot-compose.yaml
@@ -1,4 +1,4 @@
-version: '3'
+version: "3"
services:
webserver:
diff --git a/Docker/test/client.Dockerfile b/docker/staging/client.Dockerfile
similarity index 56%
rename from Docker/test/client.Dockerfile
rename to docker/staging/client.Dockerfile
index 1619b5e41..aa4d228fc 100644
--- a/Docker/test/client.Dockerfile
+++ b/docker/staging/client.Dockerfile
@@ -1,12 +1,24 @@
FROM node:20-alpine AS build
+ENV NODE_OPTIONS="--max-old-space-size=4096"
+
WORKDIR /app
-COPY ../../Client/package*.json ./
+RUN apk add --no-cache \
+ python3 \
+ make g++ \
+ gcc \
+ libc-dev \
+ linux-headers \
+ libusb-dev \
+ eudev-dev
+
+
+COPY ./client/package*.json ./
RUN npm install
-COPY ../../Client .
+COPY ./client ./
RUN npm run build
diff --git a/Docker/test/docker-compose.yaml b/docker/staging/docker-compose.yaml
old mode 100644
new mode 100755
similarity index 51%
rename from Docker/test/docker-compose.yaml
rename to docker/staging/docker-compose.yaml
index 40890e1d9..b9ca52b6e
--- a/Docker/test/docker-compose.yaml
+++ b/docker/staging/docker-compose.yaml
@@ -1,9 +1,10 @@
services:
client:
- image: uptime_client:latest
+ image: ghcr.io/bluewave-labs/checkmate:frontend-staging
restart: always
environment:
UPTIME_APP_API_BASE_URL: "https://checkmate-test.bluewavelabs.ca/api/v1"
+ UPTIME_APP_CLIENT_HOST: "https://checkmate-test.bluewavelabs.ca"
ports:
- "80:80"
- "443:443"
@@ -20,18 +21,20 @@ services:
volumes:
- ./certbot/www/:/var/www/certbot/:rw
- ./certbot/conf/:/etc/letsencrypt/:rw
+ entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew --webroot -w /var/www/certbot; sleep 12h & wait $${!}; done;'"
+
server:
- image: uptime_server:latest
+ image: ghcr.io/bluewave-labs/checkmate:backend-staging
restart: always
ports:
- - "5000:5000"
+ - "52345:52345"
env_file:
- server.env
depends_on:
- redis
- mongodb
redis:
- image: uptime_redis:latest
+ image: ghcr.io/bluewave-labs/checkmate:redis-staging
restart: always
ports:
- "6379:6379"
@@ -44,12 +47,20 @@ services:
retries: 5
start_period: 5s
mongodb:
- image: uptime_database_mongo:latest
- command: ["mongod", "--quiet", "--auth"]
+ image: ghcr.io/bluewave-labs/checkmate:mongo-staging
+ restart: always
+ command: ["mongod", "--quiet", "--replSet", "rs0", "--bind_ip_all"]
ports:
- "27017:27017"
volumes:
- ./mongo/data:/data/db
- - ./mongo/init/create_users.js:/docker-entrypoint-initdb.d/create_users.js
+ # - ./mongo/init/02_create_users.js:/docker-entrypoint-initdb.d/02_create_users.js // No longer needed
env_file:
- mongo.env
+ healthcheck:
+ test: echo "try { rs.status() } catch (err) { rs.initiate({_id:'rs0',members:[{_id:0,host:'mongodb:27017'}]}) }" | mongosh --port 27017 --quiet
+ interval: 5s
+ timeout: 30s
+ start_period: 0s
+ start_interval: 1s
+ retries: 30
diff --git a/docker/staging/mongo/init/01_init_replica_set.js b/docker/staging/mongo/init/01_init_replica_set.js
new file mode 100644
index 000000000..878ce68a6
--- /dev/null
+++ b/docker/staging/mongo/init/01_init_replica_set.js
@@ -0,0 +1,15 @@
+try {
+ const status = rs.status();
+ printjson(status);
+} catch (e) {
+ if (e.codeName === "NotYetInitialized") {
+ print("Replica set not initialized. Initiating...");
+ rs.initiate({
+ _id: "rs0",
+ members: [{ _id: 0, host: "mongodb:27017" }],
+ });
+ } else {
+ print("Unexpected error during rs.status():");
+ printjson(e);
+ }
+}
diff --git a/Docker/prod/mongo/init/create_users.js b/docker/staging/mongo/init/02_create_users.js
old mode 100644
new mode 100755
similarity index 63%
rename from Docker/prod/mongo/init/create_users.js
rename to docker/staging/mongo/init/02_create_users.js
index 67a21f910..adb2bf078
--- a/Docker/prod/mongo/init/create_users.js
+++ b/docker/staging/mongo/init/02_create_users.js
@@ -4,13 +4,13 @@ var password = process.env.PASSWORD_ENV_VAR;
db = db.getSiblingDB("uptime_db");
db.createUser({
- user: username,
- pwd: password,
- roles: [
- {
- role: "readWrite",
- db: "uptime_db",
- },
- ],
+ user: username,
+ pwd: password,
+ roles: [
+ {
+ role: "readWrite",
+ db: "uptime_db",
+ },
+ ],
});
print("User uptime_user created successfully");
diff --git a/docker/staging/mongoDB.Dockerfile b/docker/staging/mongoDB.Dockerfile
new file mode 100755
index 000000000..969a320c2
--- /dev/null
+++ b/docker/staging/mongoDB.Dockerfile
@@ -0,0 +1,3 @@
+FROM mongo
+EXPOSE 27017
+CMD ["mongod"]
diff --git a/Docker/test/nginx/conf.d/certbot b/docker/staging/nginx/conf.d/certbot
old mode 100644
new mode 100755
similarity index 100%
rename from Docker/test/nginx/conf.d/certbot
rename to docker/staging/nginx/conf.d/certbot
diff --git a/Docker/test/nginx/conf.d/default.conf b/docker/staging/nginx/conf.d/default.conf
old mode 100644
new mode 100755
similarity index 80%
rename from Docker/test/nginx/conf.d/default.conf
rename to docker/staging/nginx/conf.d/default.conf
index 1533dd35e..c755ddef1
--- a/Docker/test/nginx/conf.d/default.conf
+++ b/docker/staging/nginx/conf.d/default.conf
@@ -16,16 +16,20 @@ server {
}
location /api/ {
- proxy_pass http://server:5000/api/;
+ proxy_pass http://server:52345/api/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header Connection '';
+ chunked_transfer_encoding off;
+ proxy_buffering off;
+ proxy_cache off;
}
location /api-docs/ {
- proxy_pass http://server:5000/api-docs/;
+ proxy_pass http://server:52345/api-docs/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
@@ -50,16 +54,20 @@ server {
}
location /api/ {
- proxy_pass http://server:5000/api/;
+ proxy_pass http://server:52345/api/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header Connection '';
+ chunked_transfer_encoding off;
+ proxy_buffering off;
+ proxy_cache off;
}
location /api-docs/ {
- proxy_pass http://server:5000/api-docs/;
+ proxy_pass http://server:52345/api-docs/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
diff --git a/Docker/test/redis.Dockerfile b/docker/staging/redis.Dockerfile
old mode 100644
new mode 100755
similarity index 100%
rename from Docker/test/redis.Dockerfile
rename to docker/staging/redis.Dockerfile
diff --git a/docker/staging/server.Dockerfile b/docker/staging/server.Dockerfile
new file mode 100755
index 000000000..c80f468f8
--- /dev/null
+++ b/docker/staging/server.Dockerfile
@@ -0,0 +1,15 @@
+FROM node:20-alpine
+
+ENV NODE_OPTIONS="--max-old-space-size=2048"
+
+WORKDIR /app
+
+COPY ./server/package*.json ./
+
+RUN npm install
+
+COPY ./server ./
+
+EXPOSE 52345
+
+CMD ["node", "index.js"]
\ No newline at end of file
diff --git a/docs/diagrams/Bluewave Uptime Auth Flow.pdf b/docs/diagrams/Bluewave Uptime Auth Flow.pdf
deleted file mode 100644
index d7c7b45ca..000000000
Binary files a/docs/diagrams/Bluewave Uptime Auth Flow.pdf and /dev/null differ
diff --git a/docs/diagrams/Bluewave Uptime Auth Flow.png b/docs/diagrams/Bluewave Uptime Auth Flow.png
deleted file mode 100644
index 32498b3b4..000000000
Binary files a/docs/diagrams/Bluewave Uptime Auth Flow.png and /dev/null differ
diff --git a/docs/diagrams/Bluewave Uptime High Level Overview.pdf b/docs/diagrams/Bluewave Uptime High Level Overview.pdf
deleted file mode 100644
index 1409d10fb..000000000
Binary files a/docs/diagrams/Bluewave Uptime High Level Overview.pdf and /dev/null differ
diff --git a/docs/diagrams/Bluewave Uptime High Level Overview.png b/docs/diagrams/Bluewave Uptime High Level Overview.png
deleted file mode 100644
index 65a2866b7..000000000
Binary files a/docs/diagrams/Bluewave Uptime High Level Overview.png and /dev/null differ
diff --git a/docs/diagrams/Bluewave Uptime JobQueue Flow.pdf b/docs/diagrams/Bluewave Uptime JobQueue Flow.pdf
deleted file mode 100644
index e39825f43..000000000
Binary files a/docs/diagrams/Bluewave Uptime JobQueue Flow.pdf and /dev/null differ
diff --git a/docs/diagrams/Bluewave Uptime JobQueue Flow.png b/docs/diagrams/Bluewave Uptime JobQueue Flow.png
deleted file mode 100644
index 8794017f0..000000000
Binary files a/docs/diagrams/Bluewave Uptime JobQueue Flow.png and /dev/null differ
diff --git a/docs/diagrams/Bluewave Uptime Monitor Flow.pdf b/docs/diagrams/Bluewave Uptime Monitor Flow.pdf
deleted file mode 100644
index 97d56d781..000000000
Binary files a/docs/diagrams/Bluewave Uptime Monitor Flow.pdf and /dev/null differ
diff --git a/docs/diagrams/Bluewave Uptime Monitor Flow.png b/docs/diagrams/Bluewave Uptime Monitor Flow.png
deleted file mode 100644
index 5cfc8bca8..000000000
Binary files a/docs/diagrams/Bluewave Uptime Monitor Flow.png and /dev/null differ
diff --git a/guides/.gitbook/assets/Screenshot 2024-10-10 at 10.37.36 PM.png b/guides/.gitbook/assets/Screenshot 2024-10-10 at 10.37.36 PM.png
deleted file mode 100644
index 31dbacbe0..000000000
Binary files a/guides/.gitbook/assets/Screenshot 2024-10-10 at 10.37.36 PM.png and /dev/null differ
diff --git a/guides/users-guide/maintenance-mode.md b/guides/users-guide/maintenance-mode.md
deleted file mode 100644
index 7881dbfd8..000000000
--- a/guides/users-guide/maintenance-mode.md
+++ /dev/null
@@ -1,35 +0,0 @@
----
-icon: clock-nine
----
-
-# Maintenance mode
-
-The Maintenance mode allows you to manage and schedule maintenance periods for monitored URLs. During a maintenance window, no pings or HTTP requests are sent to the specified URLs, preventing downtime alerts during scheduled maintenance activities.
-
-### Creating a new maintenance window
-
-When you click the **"Create Maintenance Window"** button, you will see a page similar to this:
-
-
-
-Here's how to set up a new maintenance window:
-
-**General settings:**
-
-* **Maintenance repeat**: Select how often the maintenance window should repeat (e.g., don't repeat, daily, weekly).
-* **Date**: Select the date the maintenance window should start.
-* **Start time**: Set the time of day the window begins.
-* **Duration**: Specify how long the maintenance window should last (in seconds, minutes, or hours).
-
-**Monitor related settings:**
-
-* **Friendly Name**: Provide a descriptive name for the maintenance window (e.g., "Maintenance at 10:37 PM for 30 minutes").
-* **Add Monitors**: Select the specific monitors (URLs) for which this maintenance window will apply by typing and selecting from the list.
-
-Once all fields are filled, click **Create maintenance** to save the new window.
-
-### Editing a maintenance window
-
-* To edit an existing window, click the gear icon under **Actions** in the table view.
-* Update the required fields and save your changes.
-
diff --git a/index.html b/index.html
deleted file mode 100644
index ee30de68d..000000000
--- a/index.html
+++ /dev/null
@@ -1 +0,0 @@
-Checkmate web page
diff --git a/package-lock.json b/package-lock.json
deleted file mode 100644
index f71a78c1f..000000000
--- a/package-lock.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "name": "bluewave-uptime",
- "lockfileVersion": 3,
- "requires": true,
- "packages": {}
-}
diff --git a/Server/.dockerignore b/server/.dockerignore
old mode 100644
new mode 100755
similarity index 100%
rename from Server/.dockerignore
rename to server/.dockerignore
diff --git a/server/.github/pull_request_template.md b/server/.github/pull_request_template.md
new file mode 100755
index 000000000..ed81cc04b
--- /dev/null
+++ b/server/.github/pull_request_template.md
@@ -0,0 +1,23 @@
+**(Please remove this line only before submitting your PR. Ensure that all relevant items are checked before submission.)**
+
+## Describe your changes
+
+Briefly describe the changes you made and their purpose.
+
+## Write your issue number after "Fixes "
+
+Fixes #123
+
+## Please ensure all items are checked off before requesting a review. "Checked off" means you need to add an "x" character between brackets so they turn into checkmarks.
+
+- [ ] (Do not skip this or your PR will be closed) I deployed the application locally.
+- [ ] (Do not skip this or your PR will be closed) I have performed a self-review and testing of my code.
+- [ ] I have included the issue # in the PR.
+- [ ] I have added i18n support to visible strings (instead of `Add `, use):
+```Javascript
+const { t } = useTranslation();
+{t('add')}
+```
+- [ ] The issue I am working on is assigned to me.
+- [ ] I didn't use any hardcoded values (otherwise it will not scale, and will make it difficult to maintain consistency across the application).
+- [ ] My PR is granular and targeted to one specific feature.
diff --git a/server/.github/workflows/staging-deploy.yml b/server/.github/workflows/staging-deploy.yml
new file mode 100755
index 000000000..8fadf12d4
--- /dev/null
+++ b/server/.github/workflows/staging-deploy.yml
@@ -0,0 +1,68 @@
+name: Staging deploy
+
+on:
+ push:
+ branches: ["develop"]
+
+jobs:
+ docker-build-and-push:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Build Server Docker image
+ run: |
+ docker build \
+ -t ghcr.io/bluewave-labs/checkmate-backend:staging \
+ -f ./docker/staging/server.Dockerfile \
+ --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate-backend \
+ .
+
+ - name: Push Server Docker image
+ run: docker push ghcr.io/bluewave-labs/checkmate-backend:staging
+
+ - name: Build Mongo Docker image
+ run: |
+ docker build \
+ -t ghcr.io/bluewave-labs/checkmate-mongo:staging \
+ -f ./docker/staging/mongoDB.Dockerfile \
+ --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate-backend \
+ .
+
+ - name: Push MongoDB Docker image
+ run: docker push ghcr.io/bluewave-labs/checkmate-mongo:staging
+
+ - name: Build Redis Docker image
+ run: |
+ docker build \
+ -t ghcr.io/bluewave-labs/checkmate-redis:staging \
+ -f ./docker/staging/redis.Dockerfile \
+ --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate-backend \
+ .
+
+ - name: Push Redis Docker image
+ run: docker push ghcr.io/bluewave-labs/checkmate-redis:staging
+
+ deploy-to-staging:
+ needs: docker-build-and-push
+ runs-on: ubuntu-latest
+ steps:
+ - name: SSH into server and restart container using Docker Compose
+ uses: appleboy/ssh-action@v1.0.0
+ with:
+ host: ${{ secrets.STAGING_SERVER_HOST }}
+ username: ${{ secrets.STAGING_SERVER_USER }}
+ key: ${{ secrets.STAGING_SERVER_SSH_KEY }}
+ script: |
+ cd checkmate/server/docker/staging
+ docker compose down
+ docker compose pull
+ docker compose up -d
diff --git a/Server/.gitignore b/server/.gitignore
old mode 100644
new mode 100755
similarity index 50%
rename from Server/.gitignore
rename to server/.gitignore
index 3f5217d23..bab6fb27c
--- a/Server/.gitignore
+++ b/server/.gitignore
@@ -3,4 +3,7 @@ node_modules
*.log
*.sh
.nyc_output
-coverage
\ No newline at end of file
+coverage
+.clinic
+node_modules
+.vscode/*
diff --git a/Server/.mocharc.cjs b/server/.mocharc.cjs
old mode 100644
new mode 100755
similarity index 100%
rename from Server/.mocharc.cjs
rename to server/.mocharc.cjs
diff --git a/Server/.nycrc b/server/.nycrc
old mode 100644
new mode 100755
similarity index 100%
rename from Server/.nycrc
rename to server/.nycrc
diff --git a/server/.prettierrc b/server/.prettierrc
new file mode 100755
index 000000000..5c345e37a
--- /dev/null
+++ b/server/.prettierrc
@@ -0,0 +1,16 @@
+{
+ "printWidth": 90,
+ "useTabs": true,
+ "tabWidth": 2,
+ "singleQuote": false,
+ "bracketSpacing": true,
+ "proseWrap": "preserve",
+ "bracketSameLine": false,
+ "singleAttributePerLine": true,
+ "semi": true,
+ "jsxSingleQuote": false,
+ "quoteProps": "as-needed",
+ "arrowParens": "always",
+ "trailingComma": "es5",
+ "htmlWhitespaceSensitivity": "css"
+}
diff --git a/server/LICENSE b/server/LICENSE
new file mode 100755
index 000000000..4a43a1939
--- /dev/null
+++ b/server/LICENSE
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C) 2025 BlueWave Labs
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published
+ by the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+ .
diff --git a/server/README.md b/server/README.md
new file mode 100755
index 000000000..03f1b1629
--- /dev/null
+++ b/server/README.md
@@ -0,0 +1,15 @@
+
+
+The backend service for Checkmate, an open source uptime and infrastructure monitoring application
+
+This directory contains the **backend** of Checkmate, which handles data processing, storage, and API services for the Checkmate monitoring tool. The backend is responsible for managing uptime checks, handling real-time alerts, and storing historical monitoring data.
+
+Checkmate's backend is designed to be lightweight and scalable, ensuring reliable performance even with a high number of active monitors.
+
+## Installation & documentation
+
+For setup instructions, configuration details, and deployment guidelines, please visit our official documentation at [docs.checkmate.so](https://docs.checkmate.so).
+
+## Related repositories
+
+- [Capture Agent](https://github.com/bluewave-labs/capture) (Optional, provides additional server insights)
diff --git a/server/controllers/announcementsController.js b/server/controllers/announcementsController.js
new file mode 100755
index 000000000..024ed95a5
--- /dev/null
+++ b/server/controllers/announcementsController.js
@@ -0,0 +1,79 @@
+import { createAnnouncementValidation } from "../validation/joi.js";
+import { handleError } from "./controllerUtils.js";
+
+const SERVICE_NAME = "announcementController";
+
+/**
+ * Controller for managing announcements in the system.
+ * This class handles the creation of new announcements.
+ *
+ * @class AnnouncementController
+ */
+
+class AnnouncementController {
+ constructor(db, stringService) {
+ this.db = db;
+ this.stringService = stringService;
+ this.createAnnouncement = this.createAnnouncement.bind(this);
+ this.getAnnouncement = this.getAnnouncement.bind(this);
+ }
+
+ /**
+ * Handles the creation of a new announcement.
+ *
+ * @async
+ * @param {Object} req - The request object, containing the announcement data in the body.
+ * @param {Object} res - The response object used to send the result back to the client.
+ * @param {Function} next - The next middleware function in the stack for error handling.
+ *
+ * @returns {Promise} A promise that resolves once the response is sent.
+ */
+ createAnnouncement = async (req, res, next) => {
+ try {
+ await createAnnouncementValidation.validateAsync(req.body);
+ } catch (error) {
+ return next(handleError(error, SERVICE_NAME)); // Handle Joi validation errors
+ }
+
+ const { title, message } = req.body;
+
+ try {
+ const announcementData = {
+ title: title.trim(),
+ message: message.trim(),
+ userId: req.user._id,
+ };
+
+ const newAnnouncement = await this.db.createAnnouncement(announcementData);
+ return res.success({
+ msg: this.stringService.createAnnouncement,
+ data: newAnnouncement,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "createAnnouncement"));
+ }
+ };
+
+ /**
+ * Handles retrieving announcements with pagination.
+ *
+ * @async
+ * @param {Object} res - The response object used to send the result back to the client.
+ * - `data`: The list of announcements to be sent back to the client.
+ * - `msg`: A message about the success of the request.
+ * @param {Function} next - The next middleware function in the stack for error handling.
+ */
+ getAnnouncement = async (req, res, next) => {
+ try {
+ const allAnnouncements = await this.db.getAnnouncements();
+ return res.success({
+ msg: this.stringService.getAnnouncement,
+ data: allAnnouncements,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "getAnnouncement"));
+ }
+ };
+}
+
+export default AnnouncementController;
diff --git a/Server/controllers/authController.js b/server/controllers/authController.js
old mode 100644
new mode 100755
similarity index 77%
rename from Server/controllers/authController.js
rename to server/controllers/authController.js
index 0ffa612f3..9d5fe0c20
--- a/Server/controllers/authController.js
+++ b/server/controllers/authController.js
@@ -8,41 +8,34 @@ import {
newPasswordValidation,
} from "../validation/joi.js";
import logger from "../utils/logger.js";
-import { errorMessages, successMessages } from "../utils/messages.js";
import jwt from "jsonwebtoken";
-import { getTokenFromHeaders, tokenType } from "../utils/utils.js";
+import { getTokenFromHeaders } from "../utils/utils.js";
import crypto from "crypto";
import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "authController";
class AuthController {
- constructor(db, settingsService, emailService, jobQueue) {
+ constructor(db, settingsService, emailService, jobQueue, stringService) {
this.db = db;
this.settingsService = settingsService;
this.emailService = emailService;
this.jobQueue = jobQueue;
+ this.stringService = stringService;
}
/**
* Creates and returns JWT token with an arbitrary payload
* @function
* @param {Object} payload
- * @param {tokenType} typeOfToken - Whether to generate refresh token with long TTL or access token with short TTL.
* @param {Object} appSettings
* @returns {String}
* @throws {Error}
*/
- issueToken = (payload, typeOfToken, appSettings) => {
+ issueToken = (payload, appSettings) => {
try {
- const tokenTTL =
- typeOfToken === tokenType.REFRESH_TOKEN
- ? (appSettings?.refreshTokenTTL ?? "7d")
- : (appSettings?.jwtTTL ?? "2h");
- const tokenSecret =
- typeOfToken === tokenType.REFRESH_TOKEN
- ? appSettings?.refreshTokenSecret
- : appSettings?.jwtSecret;
- const payloadData = typeOfToken === tokenType.REFRESH_TOKEN ? {} : payload;
+ const tokenTTL = appSettings?.jwtTTL ?? "2h";
+ const tokenSecret = appSettings?.jwtSecret;
+ const payloadData = payload;
return jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL });
} catch (error) {
@@ -64,6 +57,9 @@ class AuthController {
*/
registerUser = async (req, res, next) => {
try {
+ if (req.body?.email) {
+ req.body.email = req.body.email?.toLowerCase();
+ }
await registrationBodyValidation.validateAsync(req.body);
} catch (error) {
const validationError = handleValidationError(error, SERVICE_NAME);
@@ -72,11 +68,13 @@ class AuthController {
}
// Create a new user
try {
- const { inviteToken } = req.body;
+ const user = req.body;
// If superAdmin exists, a token should be attached to all further register requests
const superAdminExists = await this.db.checkSuperadmin(req, res);
if (superAdminExists) {
- await this.db.getInviteTokenAndDelete(inviteToken);
+ const invitedUser = await this.db.getInviteTokenAndDelete(user.inviteToken);
+ user.role = invitedUser.role;
+ user.teamId = invitedUser.teamId;
} else {
// This is the first account, create JWT secret to use if one is not supplied by env
const jwtSecret = crypto.randomBytes(64).toString("hex");
@@ -85,7 +83,7 @@ class AuthController {
const newUser = await this.db.insertUser({ ...req.body }, req.file);
logger.info({
- message: successMessages.AUTH_CREATE_USER,
+ message: this.stringService.authCreateUser,
service: SERVICE_NAME,
details: newUser._id,
});
@@ -96,8 +94,7 @@ class AuthController {
const appSettings = await this.settingsService.getSettings();
- const token = this.issueToken(userForToken, tokenType.ACCESS_TOKEN, appSettings);
- const refreshToken = this.issueToken({}, tokenType.REFRESH_TOKEN, appSettings);
+ const token = this.issueToken(userForToken, appSettings);
this.emailService
.buildAndSendEmail(
@@ -116,8 +113,8 @@ class AuthController {
});
res.success({
- msg: successMessages.AUTH_CREATE_USER,
- data: { user: newUser, token: token, refreshToken: refreshToken },
+ msg: this.stringService.authCreateUser,
+ data: { user: newUser, token: token },
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "registerController"));
@@ -138,6 +135,9 @@ class AuthController {
*/
loginUser = async (req, res, next) => {
try {
+ if (req.body?.email) {
+ req.body.email = req.body.email?.toLowerCase();
+ }
await loginValidation.validateAsync(req.body);
} catch (error) {
const validationError = handleValidationError(error, SERVICE_NAME);
@@ -153,7 +153,7 @@ class AuthController {
// Compare password
const match = await user.comparePassword(password);
if (match !== true) {
- const error = new Error(errorMessages.AUTH_INCORRECT_PASSWORD);
+ const error = new Error(this.stringService.authIncorrectPassword);
error.status = 401;
next(error);
return;
@@ -166,21 +166,15 @@ class AuthController {
// Happy path, return token
const appSettings = await this.settingsService.getSettings();
- const token = this.issueToken(
- userWithoutPassword,
- tokenType.ACCESS_TOKEN,
- appSettings
- );
- const refreshToken = this.issueToken({}, tokenType.REFRESH_TOKEN, appSettings);
+ const token = this.issueToken(userWithoutPassword, appSettings);
// reset avatar image
userWithoutPassword.avatarImage = user.avatarImage;
return res.success({
- msg: successMessages.AUTH_LOGIN_USER,
+ msg: this.stringService.authLoginUser,
data: {
user: userWithoutPassword,
token: token,
- refreshToken: refreshToken,
},
});
} catch (error) {
@@ -189,67 +183,6 @@ class AuthController {
}
};
- /**
- * Generates new auth token if the refresh token is valid
- * @async
- * @param {Express.Request} req - The Express request object.
- * @property {Object} req.headers - The parameter of the request.
- * @param {Express.Response} res - The Express response object.
- * @param {function} next - The next middleware function.
- * @returns {Object} The response object with a success status, a message indicating new auth token is generated.
- * @throws {Error} If there is an error during the process such as any of the token is not received
- */
- refreshAuthToken = async (req, res, next) => {
- try {
- // check for refreshToken
- const refreshToken = req.headers["x-refresh-token"];
-
- if (!refreshToken) {
- // No refresh token provided
- const error = new Error(errorMessages.NO_REFRESH_TOKEN);
- error.status = 401;
- error.service = SERVICE_NAME;
- error.method = "refreshAuthToken";
- return next(error);
- }
-
- // Verify refresh token
- const appSettings = await this.settingsService.getSettings();
- const { refreshTokenSecret } = appSettings;
- jwt.verify(refreshToken, refreshTokenSecret, async (refreshErr, refreshDecoded) => {
- if (refreshErr) {
- // Invalid or expired refresh token, trigger logout
- const errorMessage =
- refreshErr.name === "TokenExpiredError"
- ? errorMessages.EXPIRED_REFRESH_TOKEN
- : errorMessages.INVALID_REFRESH_TOKEN;
- const error = new Error(errorMessage);
- error.status = 401;
- error.service = SERVICE_NAME;
- return next(error);
- }
- });
- // Refresh token is valid and unexpired, generate new access token
- const oldAuthToken = getTokenFromHeaders(req.headers);
- const { jwtSecret } = await this.settingsService.getSettings();
- const payloadData = jwt.verify(oldAuthToken, jwtSecret, { ignoreExpiration: true });
- // delete old token related data
- delete payloadData.iat;
- delete payloadData.exp;
- const newAuthToken = this.issueToken(
- payloadData,
- tokenType.ACCESS_TOKEN,
- appSettings
- );
-
- return res.success({
- msg: successMessages.AUTH_TOKEN_REFRESHED,
- data: { user: payloadData, token: newAuthToken, refreshToken: refreshToken },
- });
- } catch (error) {
- next(handleError(error, SERVICE_NAME, "refreshAuthToken"));
- }
- };
/**
* Edits a user's information. If the user wants to change their password, the current password is checked before updating to the new password.
* @async
@@ -276,7 +209,7 @@ class AuthController {
// TODO is this neccessary any longer? Verify ownership middleware should handle this
if (req.params.userId !== req.user._id.toString()) {
- const error = new Error(errorMessages.AUTH_UNAUTHORIZED);
+ const error = new Error(this.stringService.unauthorized);
error.status = 401;
error.service = SERVICE_NAME;
next(error);
@@ -300,7 +233,7 @@ class AuthController {
// If not a match, throw a 403
// 403 instead of 401 to avoid triggering axios interceptor
if (!match) {
- const error = new Error(errorMessages.AUTH_INCORRECT_PASSWORD);
+ const error = new Error(this.stringService.authIncorrectPassword);
error.status = 403;
next(error);
return;
@@ -311,7 +244,7 @@ class AuthController {
const updatedUser = await this.db.updateUser(req, res);
res.success({
- msg: successMessages.AUTH_UPDATE_USER,
+ msg: this.stringService.authUpdateUser,
data: updatedUser,
});
} catch (error) {
@@ -333,7 +266,7 @@ class AuthController {
const superAdminExists = await this.db.checkSuperadmin(req, res);
return res.success({
- msg: successMessages.AUTH_ADMIN_EXISTS,
+ msg: this.stringService.authAdminExists,
data: superAdminExists,
});
} catch (error) {
@@ -379,7 +312,7 @@ class AuthController {
);
return res.success({
- msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN,
+ msg: this.stringService.authCreateRecoveryToken,
data: msgId,
});
} catch (error) {
@@ -410,7 +343,7 @@ class AuthController {
await this.db.validateRecoveryToken(req, res);
return res.success({
- msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN,
+ msg: this.stringService.authVerifyRecoveryToken,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "validateRecoveryTokenController"));
@@ -440,10 +373,10 @@ class AuthController {
try {
const user = await this.db.resetPassword(req, res);
const appSettings = await this.settingsService.getSettings();
- const token = this.issueToken(user._doc, tokenType.ACCESS_TOKEN, appSettings);
+ const token = this.issueToken(user._doc, appSettings);
return res.success({
- msg: successMessages.AUTH_RESET_PASSWORD,
+ msg: this.stringService.authResetPassword,
data: { user, token },
});
} catch (error) {
@@ -497,7 +430,7 @@ class AuthController {
await this.db.deleteUser(user._id);
return res.success({
- msg: successMessages.AUTH_DELETE_USER,
+ msg: this.stringService.authDeleteUser,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "deleteUserController"));
@@ -509,7 +442,7 @@ class AuthController {
const allUsers = await this.db.getAllUsers(req, res);
return res.success({
- msg: successMessages.AUTH_GET_ALL_USERS,
+ msg: this.stringService.authGetAllUsers,
data: allUsers,
});
} catch (error) {
diff --git a/Server/controllers/checkController.js b/server/controllers/checkController.js
old mode 100644
new mode 100755
similarity index 91%
rename from Server/controllers/checkController.js
rename to server/controllers/checkController.js
index ae6b96dbd..2addd7359
--- a/Server/controllers/checkController.js
+++ b/server/controllers/checkController.js
@@ -9,7 +9,6 @@ import {
deleteChecksByTeamIdParamValidation,
updateChecksTTLBodyValidation,
} from "../validation/joi.js";
-import { successMessages } from "../utils/messages.js";
import jwt from "jsonwebtoken";
import { getTokenFromHeaders } from "../utils/utils.js";
import { handleValidationError, handleError } from "./controllerUtils.js";
@@ -17,9 +16,10 @@ import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "checkController";
class CheckController {
- constructor(db, settingsService) {
+ constructor(db, settingsService, stringService) {
this.db = db;
this.settingsService = settingsService;
+ this.stringService = stringService;
}
createCheck = async (req, res, next) => {
@@ -36,7 +36,7 @@ class CheckController {
const check = await this.db.createCheck(checkData);
return res.success({
- msg: successMessages.CHECK_CREATE,
+ msg: this.stringService.checkCreate,
data: check,
});
} catch (error) {
@@ -57,7 +57,7 @@ class CheckController {
const result = await this.db.getChecksByMonitor(req);
return res.success({
- msg: successMessages.CHECK_GET,
+ msg: this.stringService.checkGet,
data: result,
});
} catch (error) {
@@ -77,7 +77,7 @@ class CheckController {
const checkData = await this.db.getChecksByTeam(req);
return res.success({
- msg: successMessages.CHECK_GET,
+ msg: this.stringService.checkGet,
data: checkData,
});
} catch (error) {
@@ -97,7 +97,7 @@ class CheckController {
const deletedCount = await this.db.deleteChecks(req.params.monitorId);
return res.success({
- msg: successMessages.CHECK_DELETE,
+ msg: this.stringService.checkDelete,
data: { deletedCount },
});
} catch (error) {
@@ -117,7 +117,7 @@ class CheckController {
const deletedCount = await this.db.deleteChecksByTeamId(req.params.teamId);
return res.success({
- msg: successMessages.CHECK_DELETE,
+ msg: this.stringService.checkDelete,
data: { deletedCount },
});
} catch (error) {
@@ -144,7 +144,7 @@ class CheckController {
await this.db.updateChecksTTL(teamId, ttl);
return res.success({
- msg: successMessages.CHECK_UPDATE_TTL,
+ msg: this.stringService.checkUpdateTTL,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "updateTTL"));
diff --git a/Server/controllers/controllerUtils.js b/server/controllers/controllerUtils.js
old mode 100644
new mode 100755
similarity index 100%
rename from Server/controllers/controllerUtils.js
rename to server/controllers/controllerUtils.js
diff --git a/server/controllers/diagnosticController.js b/server/controllers/diagnosticController.js
new file mode 100755
index 000000000..c46ac5ccb
--- /dev/null
+++ b/server/controllers/diagnosticController.js
@@ -0,0 +1,62 @@
+import { handleError } from "./controllerUtils.js";
+const SERVICE_NAME = "diagnosticController";
+
+class DiagnosticController {
+ constructor(db) {
+ this.db = db;
+ this.getDistributedUptimeDbExecutionStats =
+ this.getDistributedUptimeDbExecutionStats.bind(this);
+ this.getMonitorsByTeamIdExecutionStats =
+ this.getMonitorsByTeamIdExecutionStats.bind(this);
+ this.getDbStats = this.getDbStats.bind(this);
+ }
+
+ async getDistributedUptimeDbExecutionStats(req, res, next) {
+ try {
+ const data = await this.db.getDistributedUptimeDbExecutionStats(req);
+ return res.success({
+ msg: "OK",
+ data,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "getDbExecutionStats"));
+ }
+ }
+
+ async getMonitorsByTeamIdExecutionStats(req, res, next) {
+ try {
+ const data = await this.db.getMonitorsByTeamIdExecutionStats(req);
+ return res.success({
+ msg: "OK",
+ data,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "getMonitorsByTeamIdExecutionStats"));
+ }
+ }
+
+ async getDbStats(req, res, next) {
+ try {
+ const { methodName, args = [] } = req.body;
+ if (!methodName || !this.db[methodName]) {
+ return res.error({
+ msg: "Invalid method name or method doesn't exist",
+ status: 400,
+ });
+ }
+ const explainMethod = await this.db[methodName].apply(this.db, args);
+ const stats = {
+ methodName,
+ timestamp: new Date(),
+ explain: explainMethod,
+ };
+ return res.success({
+ msg: "OK",
+ data: stats,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "getDbStats"));
+ }
+ }
+}
+export default DiagnosticController;
diff --git a/server/controllers/distributedUptimeController.js b/server/controllers/distributedUptimeController.js
new file mode 100755
index 000000000..c036e97bc
--- /dev/null
+++ b/server/controllers/distributedUptimeController.js
@@ -0,0 +1,339 @@
+import { handleError } from "./controllerUtils.js";
+import Monitor from "../db/models/Monitor.js";
+import DistributedUptimeCheck from "../db/models/DistributedUptimeCheck.js";
+const SERVICE_NAME = "DistributedUptimeQueueController";
+
+class DistributedUptimeController {
+ constructor({ db, http, statusService, logger }) {
+ this.db = db;
+ this.http = http;
+ this.statusService = statusService;
+ this.logger = logger;
+ this.resultsCallback = this.resultsCallback.bind(this);
+ this.getDistributedUptimeMonitors = this.getDistributedUptimeMonitors.bind(this);
+ this.subscribeToDistributedUptimeMonitors =
+ this.subscribeToDistributedUptimeMonitors.bind(this);
+
+ this.subscribeToDistributedUptimeMonitorDetails =
+ this.subscribeToDistributedUptimeMonitorDetails.bind(this);
+ this.getDistributedUptimeMonitorDetails =
+ this.getDistributedUptimeMonitorDetails.bind(this);
+ }
+
+ async resultsCallback(req, res, next) {
+ try {
+ const { id, result } = req.body;
+ // Calculate response time
+ const {
+ first_byte_took,
+ body_read_took,
+ dns_took,
+ conn_took,
+ connect_took,
+ tls_took,
+ status_code,
+ error,
+ upt_burnt,
+ } = result;
+
+ // Calculate response time
+ const responseTime = first_byte_took / 1_000_000;
+ if (!isFinite(responseTime) || responseTime <= 0 || responseTime > 30000) {
+ this.logger.info({
+ message: `Unreasonable response time detected: ${responseTime}ms from first_byte_took: ${first_byte_took}ns`,
+ service: SERVICE_NAME,
+ method: "resultsCallback",
+ });
+ return;
+ }
+
+ // Calculate if server is up or down
+ const isErrorStatus = status_code >= 400;
+ const hasError = error !== "";
+
+ const status = isErrorStatus || hasError ? false : true;
+
+ // Build response
+ const distributedUptimeResponse = {
+ monitorId: id,
+ type: "distributed_http",
+ payload: result,
+ status,
+ code: status_code,
+ responseTime,
+ first_byte_took,
+ body_read_took,
+ dns_took,
+ conn_took,
+ connect_took,
+ tls_took,
+ upt_burnt,
+ };
+ if (error) {
+ const code = status_code || this.NETWORK_ERROR;
+ distributedUptimeResponse.code = code;
+ distributedUptimeResponse.message =
+ this.http.STATUS_CODES[code] || "Network Error";
+ } else {
+ distributedUptimeResponse.message = this.http.STATUS_CODES[status_code];
+ }
+
+ await this.statusService.updateStatus(distributedUptimeResponse);
+
+ res.status(200).json({ message: "OK" });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "resultsCallback"));
+ }
+ }
+
+ async getDistributedUptimeMonitors(req, res, next) {
+ try {
+ const monitors = await this.db.getMonitorsWithChecksByTeamId(req);
+ return res.success({
+ msg: "OK",
+ data: monitors,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "getDistributedUptimeMonitors"));
+ }
+ }
+
+ async subscribeToDistributedUptimeMonitors(req, res, next) {
+ try {
+ res.setHeader("Content-Type", "text/event-stream");
+ res.setHeader("Cache-Control", "no-cache");
+ res.setHeader("Connection", "keep-alive");
+ res.setHeader("Access-Control-Allow-Origin", "*");
+ // Disable compression
+ req.headers["accept-encoding"] = "identity";
+ res.removeHeader("Content-Encoding");
+ const BATCH_DELAY = 1000;
+ let batchTimeout = null;
+ let opInProgress = false;
+ let monitorStream = null;
+ let checksStream = null;
+
+ // Do things here
+ const notifyChange = async () => {
+ if (opInProgress) {
+ // Get data
+ const { count, monitors } = await this.db.getMonitorsWithChecksByTeamId(req);
+ res.write(`data: ${JSON.stringify({ count, monitors })}\n\n`);
+ opInProgress = false;
+ }
+ batchTimeout = null;
+ };
+
+ const handleChange = () => {
+ opInProgress = true;
+ if (batchTimeout) clearTimeout(batchTimeout);
+ batchTimeout = setTimeout(notifyChange, BATCH_DELAY);
+ };
+
+ const createMonitorStream = () => {
+ if (monitorStream) {
+ try {
+ monitorStream.close();
+ } catch (error) {
+ this.logger.error({
+ message: "Error closing monitor stream",
+ service: SERVICE_NAME,
+ method: "subscribeToDistributedUptimeMonitors",
+ stack: error.stack,
+ });
+ }
+ }
+ monitorStream = Monitor.watch(
+ [{ $match: { operationType: { $in: ["insert", "update", "delete"] } } }],
+ { fullDocument: "updateLookup" }
+ );
+
+ monitorStream.on("change", handleChange);
+ monitorStream.on("error", (error) => {
+ this.logger.error({
+ message: "Error in monitor stream",
+ service: SERVICE_NAME,
+ method: "subscribeToDistributedUptimeMonitors",
+ stack: error.stack,
+ });
+ createMonitorStream();
+ });
+ monitorStream.on("close", () => {
+ monitorStream = null;
+ });
+ };
+
+ const createChecksStream = () => {
+ if (checksStream) {
+ try {
+ checksStream.close();
+ } catch (error) {
+ this.logger.error({
+ message: "Error closing checks stream",
+ service: SERVICE_NAME,
+ method: "subscribeToDistributedUptimeMonitors",
+ details: error,
+ });
+ }
+ }
+ checksStream = DistributedUptimeCheck.watch(
+ [{ $match: { operationType: { $in: ["insert", "update", "delete"] } } }],
+ { fullDocument: "updateLookup" }
+ );
+ checksStream.on("change", handleChange);
+ checksStream.on("error", (error) => {
+ this.logger.error({
+ message: "Error in checks stream",
+ service: SERVICE_NAME,
+ method: "subscribeToDistributedUptimeMonitors",
+ stack: error.stack,
+ });
+ createChecksStream();
+ });
+ checksStream.on("close", () => {
+ checksStream = null;
+ });
+ };
+
+ createMonitorStream();
+ createChecksStream();
+
+ req.on("close", () => {
+ if (batchTimeout) {
+ clearTimeout(batchTimeout);
+ }
+ monitorStream.close();
+ checksStream.close();
+ clearInterval(keepAlive);
+ });
+
+ // Keep connection alive
+ const keepAlive = setInterval(() => {
+ res.write(": keepalive\n\n");
+ }, 10000);
+
+ // Clean up on close
+ req.on("close", () => {
+ clearInterval(keepAlive);
+ });
+ } catch (error) {
+ this.logger.error({
+ message: "Error in subscribeToDistributedUptimeMonitors",
+ service: SERVICE_NAME,
+ method: "subscribeToDistributedUptimeMonitors",
+ stack: error.stack,
+ });
+ next(handleError(error, SERVICE_NAME, "subscribeToDistributedUptimeMonitors"));
+ }
+ }
+
+ async getDistributedUptimeMonitorDetails(req, res, next) {
+ try {
+ const monitor = await this.db.getDistributedUptimeDetailsById(req);
+ return res.success({
+ msg: "OK",
+ data: monitor,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "getDistributedUptimeMonitorDetails"));
+ }
+ }
+
+ async subscribeToDistributedUptimeMonitorDetails(req, res, next) {
+ try {
+ res.setHeader("Content-Type", "text/event-stream");
+ res.setHeader("Cache-Control", "no-cache");
+ res.setHeader("Connection", "keep-alive");
+ res.setHeader("Access-Control-Allow-Origin", "*");
+
+ // disable compression
+ req.headers["accept-encoding"] = "identity";
+ res.removeHeader("Content-Encoding");
+
+ const BATCH_DELAY = 1000;
+ let batchTimeout = null;
+ let opInProgress = false;
+ let checksStream = null;
+ // Do things here
+ const notifyChange = async () => {
+ try {
+ if (opInProgress) {
+ // Get data
+ const monitor = await this.db.getDistributedUptimeDetailsById(req);
+ res.write(`data: ${JSON.stringify({ monitor })}\n\n`);
+ opInProgress = false;
+ }
+ batchTimeout = null;
+ } catch (error) {
+ opInProgress = false;
+ batchTimeout = null;
+ this.logger.error({
+ message: "Error in notifyChange",
+ service: SERVICE_NAME,
+ method: "subscribeToDistributedUptimeMonitorDetails",
+ stack: error.stack,
+ });
+ next(handleError(error, SERVICE_NAME, "getDistributedUptimeMonitorDetails"));
+ }
+ };
+
+ const handleChange = () => {
+ opInProgress = true;
+ if (batchTimeout) clearTimeout(batchTimeout);
+ batchTimeout = setTimeout(notifyChange, BATCH_DELAY);
+ };
+
+ const createCheckStream = () => {
+ if (checksStream) {
+ try {
+ checksStream.close();
+ } catch (error) {
+ this.logger.error({
+ message: "Error closing checks stream",
+ service: SERVICE_NAME,
+ method: "subscribeToDistributedUptimeMonitorDetails",
+ stack: error.stack,
+ });
+ }
+ }
+ checksStream = DistributedUptimeCheck.watch(
+ [{ $match: { operationType: { $in: ["insert", "update", "delete"] } } }],
+ { fullDocument: "updateLookup" }
+ );
+
+ checksStream.on("change", handleChange);
+ checksStream.on("error", (error) => {
+ this.logger.error({
+ message: "Error in checks stream",
+ service: SERVICE_NAME,
+ method: "subscribeToDistributedUptimeMonitorDetails",
+ stack: error.stack,
+ });
+ createCheckStream();
+ });
+ checksStream.on("close", () => {
+ checksStream = null;
+ });
+ };
+
+ createCheckStream();
+
+ // Handle client disconnect
+ req.on("close", () => {
+ if (batchTimeout) {
+ clearTimeout(batchTimeout);
+ }
+ checksStream.close();
+ clearInterval(keepAlive);
+ });
+
+ // Keep connection alive
+ const keepAlive = setInterval(() => {
+ res.write(": keepalive\n\n");
+ }, 10000);
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "getDistributedUptimeMonitorDetails"));
+ }
+ }
+}
+export default DistributedUptimeController;
diff --git a/Server/controllers/inviteController.js b/server/controllers/inviteController.js
old mode 100644
new mode 100755
similarity index 75%
rename from Server/controllers/inviteController.js
rename to server/controllers/inviteController.js
index a40f43a32..bce40dfa1
--- a/Server/controllers/inviteController.js
+++ b/server/controllers/inviteController.js
@@ -7,14 +7,15 @@ import logger from "../utils/logger.js";
import jwt from "jsonwebtoken";
import { handleError, handleValidationError } from "./controllerUtils.js";
import { getTokenFromHeaders } from "../utils/utils.js";
-import { successMessages } from "../utils/messages.js";
+
const SERVICE_NAME = "inviteController";
class InviteController {
- constructor(db, settingsService, emailService) {
+ constructor(db, settingsService, emailService, stringService) {
this.db = db;
this.settingsService = settingsService;
this.emailService = emailService;
+ this.stringService = stringService;
}
/**
@@ -30,7 +31,31 @@ class InviteController {
* @returns {Object} The response object with a success status, a message indicating the sending of the invitation, and the invitation token.
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/
- issueInvitation = async (req, res, next) => {
+ getInviteToken = async (req, res, next) => {
+ try {
+ // Only admins can invite
+ const token = getTokenFromHeaders(req.headers);
+ const { role, teamId } = jwt.decode(token);
+ req.body.teamId = teamId;
+ try {
+ await inviteRoleValidation.validateAsync({ roles: role });
+ await inviteBodyValidation.validateAsync(req.body);
+ } catch (error) {
+ next(handleValidationError(error, SERVICE_NAME));
+ return;
+ }
+
+ const inviteToken = await this.db.requestInviteToken({ ...req.body });
+ return res.success({
+ msg: this.stringService.inviteIssued,
+ data: inviteToken,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "inviteController"));
+ }
+ };
+
+ sendInviteEmail = async (req, res, next) => {
try {
// Only admins can invite
const token = getTokenFromHeaders(req.headers);
@@ -66,7 +91,7 @@ class InviteController {
});
return res.success({
- msg: successMessages.INVITE_ISSUED,
+ msg: this.stringService.inviteIssued,
data: inviteToken,
});
} catch (error) {
@@ -86,7 +111,7 @@ class InviteController {
const invite = await this.db.getInviteToken(req.body.token);
return res.success({
- msg: successMessages.INVITE_VERIFIED,
+ msg: this.stringService.inviteVerified,
data: invite,
});
} catch (error) {
diff --git a/Server/controllers/maintenanceWindowController.js b/server/controllers/maintenanceWindowController.js
old mode 100644
new mode 100755
similarity index 91%
rename from Server/controllers/maintenanceWindowController.js
rename to server/controllers/maintenanceWindowController.js
index b301ba94c..a11f957ed
--- a/Server/controllers/maintenanceWindowController.js
+++ b/server/controllers/maintenanceWindowController.js
@@ -9,14 +9,15 @@ import {
} from "../validation/joi.js";
import jwt from "jsonwebtoken";
import { getTokenFromHeaders } from "../utils/utils.js";
-import { successMessages } from "../utils/messages.js";
import { handleValidationError, handleError } from "./controllerUtils.js";
+
const SERVICE_NAME = "maintenanceWindowController";
class MaintenanceWindowController {
- constructor(db, settingsService) {
+ constructor(db, settingsService, stringService) {
this.db = db;
this.settingsService = settingsService;
+ this.stringService = stringService;
}
createMaintenanceWindows = async (req, res, next) => {
@@ -45,7 +46,7 @@ class MaintenanceWindowController {
await Promise.all(dbTransactions);
return res.success({
- msg: successMessages.MAINTENANCE_WINDOW_CREATE,
+ msg: this.stringService.maintenanceWindowCreate,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "createMaintenanceWindow"));
@@ -63,7 +64,7 @@ class MaintenanceWindowController {
const maintenanceWindow = await this.db.getMaintenanceWindowById(req.params.id);
return res.success({
- msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID,
+ msg: this.stringService.maintenanceWindowGetById,
data: maintenanceWindow,
});
} catch (error) {
@@ -89,7 +90,7 @@ class MaintenanceWindowController {
);
return res.success({
- msg: successMessages.MAINTENANCE_WINDOW_GET_BY_TEAM,
+ msg: this.stringService.maintenanceWindowGetByTeam,
data: maintenanceWindows,
});
} catch (error) {
@@ -111,7 +112,7 @@ class MaintenanceWindowController {
);
return res.success({
- msg: successMessages.MAINTENANCE_WINDOW_GET_BY_USER,
+ msg: this.stringService.maintenanceWindowGetByUser,
data: maintenanceWindows,
});
} catch (error) {
@@ -129,7 +130,7 @@ class MaintenanceWindowController {
try {
await this.db.deleteMaintenanceWindowById(req.params.id);
return res.success({
- msg: successMessages.MAINTENANCE_WINDOW_DELETE,
+ msg: this.stringService.maintenanceWindowDelete,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "deleteMaintenanceWindow"));
@@ -150,7 +151,7 @@ class MaintenanceWindowController {
req.body
);
return res.success({
- msg: successMessages.MAINTENANCE_WINDOW_EDIT,
+ msg: this.stringService.maintenanceWindowEdit,
data: editedMaintenanceWindow,
});
} catch (error) {
diff --git a/Server/controllers/monitorController.js b/server/controllers/monitorController.js
old mode 100644
new mode 100755
similarity index 64%
rename from Server/controllers/monitorController.js
rename to server/controllers/monitorController.js
index 86c0fb840..d537e8cee
--- a/Server/controllers/monitorController.js
+++ b/server/controllers/monitorController.js
@@ -1,9 +1,11 @@
+import Monitor from "../db/models/Monitor.js";
import {
getMonitorByIdParamValidation,
getMonitorByIdQueryValidation,
getMonitorsByTeamIdParamValidation,
getMonitorsByTeamIdQueryValidation,
createMonitorBodyValidation,
+ createMonitorsBodyValidation,
getMonitorURLByQueryValidation,
editMonitorBodyValidation,
pauseMonitorParamValidation,
@@ -14,20 +16,23 @@ import {
getHardwareDetailsByIdQueryValidation,
} from "../validation/joi.js";
import sslChecker from "ssl-checker";
-import { successMessages } from "../utils/messages.js";
import jwt from "jsonwebtoken";
import { getTokenFromHeaders } from "../utils/utils.js";
import logger from "../utils/logger.js";
import { handleError, handleValidationError } from "./controllerUtils.js";
import axios from "axios";
import seedDb from "../db/mongo/utils/seedDb.js";
+import { seedDistributedTest } from "../db/mongo/utils/seedDb.js";
const SERVICE_NAME = "monitorController";
+import pkg from "papaparse";
class MonitorController {
- constructor(db, settingsService, jobQueue) {
+ constructor(db, settingsService, jobQueue, stringService, emailService) {
this.db = db;
this.settingsService = settingsService;
this.jobQueue = jobQueue;
+ this.stringService = stringService;
+ this.emailService = emailService;
}
/**
@@ -43,7 +48,7 @@ class MonitorController {
try {
const monitors = await this.db.getAllMonitors();
return res.success({
- msg: successMessages.MONITOR_GET_ALL,
+ msg: this.stringService.monitorGetAll,
data: monitors,
});
} catch (error) {
@@ -64,7 +69,7 @@ class MonitorController {
try {
const monitors = await this.db.getAllMonitorsWithUptimeStats();
return res.success({
- msg: successMessages.MONITOR_GET_ALL,
+ msg: this.stringService.monitorGetAll,
data: monitors,
});
} catch (error) {
@@ -74,10 +79,10 @@ class MonitorController {
getUptimeDetailsById = async (req, res, next) => {
try {
- const monitor = await this.db.getUptimeDetailsById(req);
+ const data = await this.db.getUptimeDetailsById(req);
return res.success({
- msg: successMessages.MONITOR_GET_BY_ID,
- data: monitor,
+ msg: this.stringService.monitorGetByIdSuccess,
+ data,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "getMonitorDetailsById"));
@@ -105,7 +110,7 @@ class MonitorController {
try {
const monitorStats = await this.db.getMonitorStatsById(req);
return res.success({
- msg: successMessages.MONITOR_STATS_BY_ID,
+ msg: this.stringService.monitorStatsById,
data: monitorStats,
});
} catch (error) {
@@ -133,7 +138,7 @@ class MonitorController {
try {
const monitor = await this.db.getHardwareDetailsById(req);
return res.success({
- msg: successMessages.MONITOR_GET_BY_ID,
+ msg: this.stringService.monitorGetByIdSuccess,
data: monitor,
});
} catch (error) {
@@ -154,7 +159,7 @@ class MonitorController {
const certificate = await fetchMonitorCertificate(sslChecker, monitor);
return res.success({
- msg: successMessages.MONITOR_CERTIFICATE,
+ msg: this.stringService.monitorCertificate,
data: {
certificateDate: new Date(certificate.validTo),
},
@@ -187,7 +192,7 @@ class MonitorController {
try {
const monitor = await this.db.getMonitorById(req.params.monitorId);
return res.success({
- msg: successMessages.MONITOR_GET_BY_ID,
+ msg: this.stringService.monitorGetByIdSuccess,
data: monitor,
});
} catch (error) {
@@ -231,7 +236,7 @@ class MonitorController {
// Add monitor to job queue
this.jobQueue.addJob(monitor._id, monitor);
return res.success({
- msg: successMessages.MONITOR_CREATE,
+ msg: this.stringService.monitorCreate,
data: monitor,
});
} catch (error) {
@@ -239,6 +244,120 @@ class MonitorController {
}
};
+ /**
+ * Creates bulk monitors and adds them to the job queue after parsing CSV.
+ * @async
+ * @param {Object} req - The Express request object.
+ * @property {Object} req.file - The uploaded CSV file.
+ * @param {Object} res - The Express response object.
+ * @param {function} next - The next middleware function.
+ * @returns {Object} The response object with a success status and message.
+ * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
+ */
+ createBulkMonitors = async (req, res, next) => {
+ try {
+ const { parse } = pkg;
+
+ // validate the file
+ if (!req.file) {
+ throw new Error("No file uploaded");
+ }
+
+ // Check if the file is a CSV
+ if (!req.file.mimetype.includes("csv")) {
+ throw new Error("File is not a CSV");
+ }
+
+ // Validate if the file is empty
+ if (req.file.size === 0) {
+ throw new Error("File is empty");
+ }
+
+ const { userId, teamId } = req.body;
+
+ if (!userId || !teamId) {
+ throw new Error("Missing userId or teamId in form data");
+ }
+
+ // Get file buffer from memory and convert to string
+ const fileData = req.file.buffer.toString("utf-8");
+
+ // Parse the CSV data
+ parse(fileData, {
+ header: true,
+ skipEmptyLines: true,
+ transform: (value, header) => {
+ if (value === "") return undefined; // Empty fields become undefined
+
+ // Handle 'port' and 'interval' fields, check if they're valid numbers
+ if (["port", "interval"].includes(header)) {
+ const num = parseInt(value, 10);
+ if (isNaN(num)) {
+ throw new Error(`${header} should be a valid number, got: ${value}`);
+ }
+ return num;
+ }
+
+ return value;
+ },
+ complete: async ({ data, errors }) => {
+ try {
+ if (errors.length > 0) {
+ throw new Error("Error parsing CSV");
+ }
+
+ if (!data || data.length === 0) {
+ throw new Error("CSV file contains no data rows");
+ }
+
+ const enrichedData = data.map((monitor) => ({
+ userId,
+ teamId,
+ ...monitor,
+ description: monitor.description || monitor.name || monitor.url,
+ name: monitor.name || monitor.url,
+ type: monitor.type || "http",
+ }));
+
+ await createMonitorsBodyValidation.validateAsync(enrichedData);
+
+ try {
+ const monitors = await this.db.createBulkMonitors(enrichedData);
+
+ await Promise.all(
+ monitors.map(async (monitor, index) => {
+ const notifications = enrichedData[index].notifications;
+
+ if (notifications?.length) {
+ monitor.notifications = await Promise.all(
+ notifications.map(async (notification) => {
+ notification.monitorId = monitor._id;
+ return await this.db.createNotification(notification);
+ })
+ );
+ await monitor.save();
+ }
+
+ this.jobQueue.addJob(monitor._id, monitor);
+ })
+ );
+
+ return res.success({
+ msg: this.stringService.bulkMonitorsCreate,
+ data: monitors,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "createBulkMonitors"));
+ }
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "createBulkMonitors"));
+ }
+ },
+ });
+ } catch (error) {
+ return next(handleError(error, SERVICE_NAME, "createBulkMonitors"));
+ }
+ };
/**
* Checks if the endpoint can be resolved
* @async
@@ -295,12 +414,49 @@ class MonitorController {
try {
const monitor = await this.db.deleteMonitor(req, res, next);
// Delete associated checks,alerts,and notifications
+
try {
- await this.jobQueue.deleteJob(monitor);
- await this.db.deleteChecks(monitor._id);
- await this.db.deletePageSpeedChecksByMonitorId(monitor._id);
- await this.db.deleteNotificationsByMonitorId(monitor._id);
- await this.db.deleteHardwareChecksByMonitorId(monitor._id);
+ const operations = [
+ { name: "deleteJob", fn: () => this.jobQueue.deleteJob(monitor) },
+ { name: "deleteChecks", fn: () => this.db.deleteChecks(monitor._id) },
+ {
+ name: "deletePageSpeedChecks",
+ fn: () => this.db.deletePageSpeedChecksByMonitorId(monitor._id),
+ },
+ {
+ name: "deleteNotifications",
+ fn: () => this.db.deleteNotificationsByMonitorId(monitor._id),
+ },
+ {
+ name: "deleteHardwareChecks",
+ fn: () => this.db.deleteHardwareChecksByMonitorId(monitor._id),
+ },
+ {
+ name: "deleteDistributedUptimeChecks",
+ fn: () => this.db.deleteDistributedChecksByMonitorId(monitor._id),
+ },
+
+ // TODO We don't actually want to delete the status page if there are other monitors in it
+ // We actually just want to remove the monitor being deleted from the status page.
+ // Only delete he status page if there are no other monitors in it.
+ {
+ name: "deleteStatusPages",
+ fn: () => this.db.deleteStatusPagesByMonitorId(monitor._id),
+ },
+ ];
+ const results = await Promise.allSettled(operations.map((op) => op.fn()));
+
+ results.forEach((result, index) => {
+ if (result.status === "rejected") {
+ const operationName = operations[index].name;
+ logger.error({
+ message: `Failed to ${operationName} for monitor ${monitor._id}`,
+ service: SERVICE_NAME,
+ method: "deleteMonitor",
+ stack: result.reason.stack,
+ });
+ }
+ });
} catch (error) {
logger.error({
message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
@@ -309,7 +465,7 @@ class MonitorController {
stack: error.stack,
});
}
- return res.success({ msg: successMessages.MONITOR_DELETE });
+ return res.success({ msg: this.stringService.monitorDelete });
} catch (error) {
next(handleError(error, SERVICE_NAME, "deleteMonitor"));
}
@@ -382,18 +538,16 @@ class MonitorController {
const monitorBeforeEdit = await this.db.getMonitorById(monitorId);
// Get notifications from the request body
- const notifications = req.body.notifications;
-
+ const notifications = req.body.notifications ?? [];
const editedMonitor = await this.db.editMonitor(monitorId, req.body);
await this.db.deleteNotificationsByMonitorId(editedMonitor._id);
await Promise.all(
- notifications &&
- notifications.map(async (notification) => {
- notification.monitorId = editedMonitor._id;
- await this.db.createNotification(notification);
- })
+ notifications.map(async (notification) => {
+ notification.monitorId = editedMonitor._id;
+ await this.db.createNotification(notification);
+ })
);
// Delete the old job(editedMonitor has the same ID as the old monitor)
@@ -401,7 +555,7 @@ class MonitorController {
// Add the new job back to the queue
await this.jobQueue.addJob(editedMonitor._id, editedMonitor);
return res.success({
- msg: successMessages.MONITOR_EDIT,
+ msg: this.stringService.monitorEdit,
data: editedMonitor,
});
} catch (error) {
@@ -428,18 +582,26 @@ class MonitorController {
}
try {
- const monitor = await this.db.getMonitorById(req.params.monitorId);
+ const monitor = await Monitor.findOneAndUpdate(
+ { _id: req.params.monitorId },
+ [
+ {
+ $set: {
+ isActive: { $not: "$isActive" },
+ status: "$$REMOVE",
+ },
+ },
+ ],
+ { new: true }
+ );
monitor.isActive === true
? await this.jobQueue.deleteJob(monitor)
: await this.jobQueue.addJob(monitor._id, monitor);
- monitor.isActive = !monitor.isActive;
- monitor.status = undefined;
- monitor.save();
- return res.ssuccess({
+ return res.success({
msg: monitor.isActive
- ? successMessages.MONITOR_RESUME
- : successMessages.MONITOR_PAUSE,
+ ? this.stringService.monitorResume
+ : this.stringService.monitorPause,
data: monitor,
});
} catch (error) {
@@ -469,7 +631,7 @@ class MonitorController {
);
return res.success({
- msg: successMessages.MONITOR_DEMO_ADDED,
+ msg: this.stringService.monitorDemoAdded,
data: demoMonitors.length,
});
} catch (error) {
@@ -477,6 +639,49 @@ class MonitorController {
}
};
+ /**
+ * Sends a test email to verify email delivery functionality.
+ * @async
+ * @param {Object} req - The Express request object.
+ * @property {Object} req.body - The body of the request.
+ * @property {string} req.body.to - The email address to send the test email to.
+ * @param {Object} res - The Express response object.
+ * @param {function} next - The next middleware function.
+ * @returns {Object} The response object with a success status and the email delivery message ID.
+ * @throws {Error} If there is an error while sending the test email.
+ */
+ sendTestEmail = async (req, res, next) => {
+ try {
+ const { to } = req.body;
+ if (!to || typeof to !== "string") {
+ throw new Error(this.stringService.errorForValidEmailAddress);
+ }
+
+ const subject = this.stringService.testEmailSubject;
+ const context = { testName: "Monitoring System" };
+
+ const messageId = await this.emailService.buildAndSendEmail(
+ "testEmailTemplate",
+ context,
+ to,
+ subject
+ );
+
+ if (!messageId) {
+ return res.error({
+ msg: "Failed to send test email.",
+ });
+ }
+
+ return res.success({
+ msg: this.stringService.sendTestEmail,
+ data: { messageId },
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "sendTestEmail"));
+ }
+ };
+
getMonitorsByTeamId = async (req, res, next) => {
try {
await getMonitorsByTeamIdParamValidation.validateAsync(req.params);
@@ -488,7 +693,7 @@ class MonitorController {
try {
const monitors = await this.db.getMonitorsByTeamId(req);
return res.success({
- msg: successMessages.MONITOR_GET_BY_TEAM_ID,
+ msg: this.stringService.monitorGetByTeamId,
data: monitors,
});
} catch (error) {
@@ -496,12 +701,56 @@ class MonitorController {
}
};
+ getMonitorsAndSummaryByTeamId = async (req, res, next) => {
+ try {
+ await getMonitorsByTeamIdParamValidation.validateAsync(req.params);
+ await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
+ } catch (error) {
+ return next(handleValidationError(error, SERVICE_NAME));
+ }
+
+ try {
+ const result = await this.db.getMonitorsAndSummaryByTeamId(req);
+ return res.success({
+ msg: "OK", // TODO
+ data: result,
+ });
+ } catch (error) {
+ return next(handleError(error, SERVICE_NAME, "getMonitorsAndSummaryByTeamId"));
+ }
+ };
+
+ getMonitorsWithChecksByTeamId = async (req, res, next) => {
+ try {
+ await getMonitorsByTeamIdParamValidation.validateAsync(req.params);
+ await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
+ } catch (error) {
+ return next(handleValidationError(error, SERVICE_NAME));
+ }
+
+ try {
+ const result = await this.db.getMonitorsWithChecksByTeamId(req);
+ return res.success({
+ msg: "OK", // TODO
+ data: result,
+ });
+ } catch (error) {
+ return next(handleError(error, SERVICE_NAME, "getMonitorsWithChecksByTeamId"));
+ }
+ };
+
seedDb = async (req, res, next) => {
try {
+ const { type } = req.body;
const token = getTokenFromHeaders(req.headers);
const { jwtSecret } = this.settingsService.getSettings();
const { _id, teamId } = jwt.verify(token, jwtSecret);
- await seedDb(_id, teamId);
+ if (type === "distributed_test") {
+ await seedDistributedTest(_id, teamId);
+ } else {
+ await seedDb(_id, teamId);
+ }
+ res.success({ msg: "Database seeded" });
} catch (error) {
next(handleError(error, SERVICE_NAME, "seedDb"));
}
diff --git a/server/controllers/notificationController.js b/server/controllers/notificationController.js
new file mode 100755
index 000000000..3682821eb
--- /dev/null
+++ b/server/controllers/notificationController.js
@@ -0,0 +1,174 @@
+import { triggerNotificationBodyValidation } from "../validation/joi.js";
+import { handleError, handleValidationError } from "./controllerUtils.js";
+
+const SERVICE_NAME = "NotificationController";
+
+const NOTIFICATION_TYPES = {
+ WEBHOOK: 'webhook',
+ TELEGRAM: 'telegram'
+};
+
+const PLATFORMS = {
+ SLACK: 'slack',
+ DISCORD: 'discord',
+ TELEGRAM: 'telegram'
+};
+
+class NotificationController {
+ constructor(notificationService, stringService, statusService) {
+ this.notificationService = notificationService;
+ this.stringService = stringService;
+ this.statusService = statusService;
+ this.triggerNotification = this.triggerNotification.bind(this);
+ this.testWebhook = this.testWebhook.bind(this);
+ }
+
+ async triggerNotification(req, res, next) {
+ try {
+ await triggerNotificationBodyValidation.validateAsync(req.body, {
+ abortEarly: false,
+ stripUnknown: true,
+ });
+ } catch (error) {
+ next(handleValidationError(error, SERVICE_NAME));
+ return;
+ }
+
+ try {
+ const { monitorId, type, platform, config, status = false } = req.body;
+
+ // Create a simplified networkResponse similar to what would come from monitoring
+ const networkResponse = {
+ monitorId,
+ status
+ };
+
+ // Use the statusService to get monitor details and handle status change logic
+ // This returns { monitor, statusChanged, prevStatus } exactly like your job queue uses
+ const statusResult = await this.statusService.updateStatus(networkResponse);
+
+ if (type === NOTIFICATION_TYPES.WEBHOOK) {
+ const notification = {
+ type,
+ platform,
+ config,
+ };
+
+ await this.notificationService.sendWebhookNotification(
+ statusResult, // Contains monitor, statusChanged, and prevStatus
+ notification
+ );
+ }
+
+ return res.success({
+ msg: this.stringService.webhookSendSuccess,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "triggerNotification"));
+ }
+ }
+
+ createTestNetworkResponse() {
+ return {
+ monitor: {
+ _id: "test-monitor-id",
+ name: "Test Monitor",
+ url: "https://example.com"
+ },
+ status: true,
+ statusChanged: true,
+ prevStatus: false,
+ };
+ }
+
+ handleTelegramTest(botToken, chatId) {
+ if (!botToken || !chatId) {
+ return {
+ isValid: false,
+ error: {
+ msg: this.stringService.telegramRequiresBotTokenAndChatId,
+ status: 400
+ }
+ };
+ }
+
+ return {
+ isValid: true,
+ notification: {
+ type: NOTIFICATION_TYPES.WEBHOOK,
+ platform: PLATFORMS.TELEGRAM,
+ config: { botToken, chatId }
+ }
+ };
+ }
+
+ handleWebhookTest(webhookUrl, platform) {
+ if (webhookUrl === null) {
+ return {
+ isValid: false,
+ error: {
+ msg: this.stringService.webhookUrlRequired,
+ status: 400
+ }
+ };
+ }
+
+ return {
+ isValid: true,
+ notification: {
+ type: NOTIFICATION_TYPES.WEBHOOK,
+ platform: platform,
+ config: { webhookUrl }
+ }
+ };
+ }
+
+ async testWebhook(req, res, next) {
+ try {
+ const { webhookUrl, platform, botToken, chatId } = req.body;
+
+ if (platform === null) {
+ return res.error({
+ msg: this.stringService.platformRequired,
+ status: 400
+ });
+ }
+
+ // Platform-specific handling
+ const platformHandlers = {
+ [PLATFORMS.TELEGRAM]: () => this.handleTelegramTest(botToken, chatId),
+ // Default handler for webhook-based platforms (Slack, Discord, etc.)
+ default: () => this.handleWebhookTest(webhookUrl, platform)
+ };
+
+ const handler = platformHandlers[platform] || platformHandlers.default;
+ const handlerResult = handler();
+
+ if (!handlerResult.isValid) {
+ return res.error(handlerResult.error);
+ }
+
+ const networkResponse = this.createTestNetworkResponse();
+
+ const result = await this.notificationService.sendWebhookNotification(
+ networkResponse,
+ handlerResult.notification
+ );
+
+ if (result && result !== false) {
+ return res.success({
+ msg: this.stringService.webhookSendSuccess,
+ });
+ } else {
+ return res.error({
+ msg: this.stringService.testNotificationFailed,
+ status: 400
+ });
+ }
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "testWebhook"));
+ }
+ }
+}
+
+export default NotificationController;
\ No newline at end of file
diff --git a/Server/controllers/queueController.js b/server/controllers/queueController.js
old mode 100644
new mode 100755
similarity index 56%
rename from Server/controllers/queueController.js
rename to server/controllers/queueController.js
index f62b9fdeb..9d87a70f6
--- a/Server/controllers/queueController.js
+++ b/server/controllers/queueController.js
@@ -1,18 +1,18 @@
import { handleError } from "./controllerUtils.js";
-import { successMessages } from "../utils/messages.js";
const SERVICE_NAME = "JobQueueController";
class JobQueueController {
- constructor(jobQueue) {
+ constructor(jobQueue, stringService) {
this.jobQueue = jobQueue;
+ this.stringService = stringService;
}
getMetrics = async (req, res, next) => {
try {
const metrics = await this.jobQueue.getMetrics();
res.success({
- msg: successMessages.QUEUE_GET_METRICS,
+ msg: this.stringService.queueGetMetrics,
data: metrics,
});
} catch (error) {
@@ -25,7 +25,7 @@ class JobQueueController {
try {
const jobs = await this.jobQueue.getJobStats();
return res.success({
- msg: successMessages.QUEUE_GET_METRICS,
+ msg: this.stringService.queueGetMetrics,
data: jobs,
});
} catch (error) {
@@ -38,7 +38,7 @@ class JobQueueController {
try {
await this.jobQueue.addJob(Math.random().toString(36).substring(7));
return res.success({
- msg: successMessages.QUEUE_ADD_JOB,
+ msg: this.stringService.queueAddJob,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "addJob"));
@@ -50,12 +50,38 @@ class JobQueueController {
try {
await this.jobQueue.obliterate();
return res.success({
- msg: successMessages.QUEUE_OBLITERATE,
+ msg: this.stringService.queueObliterate,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "obliterateQueue"));
return;
}
};
+
+ flushQueue = async (req, res, next) => {
+ try {
+ const result = await this.jobQueue.flushQueue();
+ return res.success({
+ msg: this.stringService.jobQueueFlush,
+ data: result,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "flushQueue"));
+ return;
+ }
+ };
+
+ checkQueueHealth = async (req, res, next) => {
+ try {
+ const stuckQueues = await this.jobQueue.checkQueueHealth();
+ return res.success({
+ msg: this.stringService.queueHealthCheck,
+ data: stuckQueues,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "checkQueueHealth"));
+ return;
+ }
+ };
}
export default JobQueueController;
diff --git a/Server/controllers/settingsController.js b/server/controllers/settingsController.js
old mode 100644
new mode 100755
similarity index 53%
rename from Server/controllers/settingsController.js
rename to server/controllers/settingsController.js
index 496ed057a..b557e8dd6
--- a/Server/controllers/settingsController.js
+++ b/server/controllers/settingsController.js
@@ -1,25 +1,38 @@
-import { successMessages } from "../utils/messages.js";
import { updateAppSettingsBodyValidation } from "../validation/joi.js";
import { handleValidationError, handleError } from "./controllerUtils.js";
+
const SERVICE_NAME = "SettingsController";
class SettingsController {
- constructor(db, settingsService) {
+ constructor(db, settingsService, stringService) {
this.db = db;
this.settingsService = settingsService;
+ this.stringService = stringService;
}
getAppSettings = async (req, res, next) => {
- try {
- const settings = { ...(await this.settingsService.getSettings()) };
- delete settings.jwtSecret;
- return res.success({
- msg: successMessages.GET_APP_SETTINGS,
- data: settings,
- });
- } catch (error) {
- next(handleError(error, SERVICE_NAME, "getAppSettings"));
+ const dbSettings = await this.settingsService.getDBSettings();
+ const sanitizedSettings = { ...dbSettings };
+
+ const returnSettings = {
+ pagespeedKeySet: false,
+ emailPasswordSet: false,
+ };
+
+ if (typeof sanitizedSettings.pagespeedApiKey !== "undefined") {
+ returnSettings.pagespeedKeySet = true;
+ delete sanitizedSettings.pagespeedApiKey;
}
+ if (typeof sanitizedSettings.systemEmailPassword !== "undefined") {
+ returnSettings.emailPasswordSet = true;
+ delete sanitizedSettings.systemEmailPassword;
+ }
+
+ returnSettings.settings = sanitizedSettings;
+ return res.success({
+ msg: this.stringService.getAppSettings,
+ data: returnSettings,
+ });
};
updateAppSettings = async (req, res, next) => {
@@ -35,7 +48,7 @@ class SettingsController {
const updatedSettings = { ...(await this.settingsService.reloadSettings()) };
delete updatedSettings.jwtSecret;
return res.success({
- msg: successMessages.UPDATE_APP_SETTINGS,
+ msg: this.stringService.updateAppSettings,
data: updatedSettings,
});
} catch (error) {
diff --git a/server/controllers/statusPageController.js b/server/controllers/statusPageController.js
new file mode 100755
index 000000000..d0bdcf4b5
--- /dev/null
+++ b/server/controllers/statusPageController.js
@@ -0,0 +1,143 @@
+import { handleError, handleValidationError } from "./controllerUtils.js";
+import {
+ createStatusPageBodyValidation,
+ getStatusPageParamValidation,
+ getStatusPageQueryValidation,
+ imageValidation,
+} from "../validation/joi.js";
+
+const SERVICE_NAME = "statusPageController";
+
+class StatusPageController {
+ constructor(db, stringService) {
+ this.db = db;
+ this.stringService = stringService;
+ }
+
+ createStatusPage = async (req, res, next) => {
+ try {
+ await createStatusPageBodyValidation.validateAsync(req.body);
+ await imageValidation.validateAsync(req.file);
+ } catch (error) {
+ next(handleValidationError(error, SERVICE_NAME));
+ return;
+ }
+
+ try {
+ const statusPage = await this.db.createStatusPage(req.body, req.file);
+ return res.success({
+ msg: this.stringService.statusPageCreate,
+ data: statusPage,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "createStatusPage"));
+ }
+ };
+
+ updateStatusPage = async (req, res, next) => {
+ try {
+ await createStatusPageBodyValidation.validateAsync(req.body);
+ await imageValidation.validateAsync(req.file);
+ } catch (error) {
+ next(handleValidationError(error, SERVICE_NAME));
+ return;
+ }
+
+ try {
+ const statusPage = await this.db.updateStatusPage(req.body, req.file);
+ if (statusPage === null) {
+ const error = new Error(this.stringService.statusPageNotFound);
+ error.status = 404;
+ throw error;
+ }
+ return res.success({
+ msg: this.stringService.statusPageUpdate,
+ data: statusPage,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "updateStatusPage"));
+ }
+ };
+
+ getStatusPage = async (req, res, next) => {
+ try {
+ const statusPage = await this.db.getStatusPage();
+ return res.success({
+ msg: this.stringService.statusPageByUrl,
+ data: statusPage,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "getStatusPage"));
+ }
+ };
+
+ getDistributedStatusPageByUrl = async (req, res, next) => {
+ try {
+ await getStatusPageParamValidation.validateAsync(req.params);
+ await getStatusPageQueryValidation.validateAsync(req.query);
+ } catch (error) {
+ next(handleValidationError(error, SERVICE_NAME));
+ return;
+ }
+
+ try {
+ const statusPage = await this.db.getDistributedStatusPageByUrl({
+ url: req.params.url,
+ daysToShow: req.params.timeFrame,
+ });
+ return res.success({
+ msg: this.stringService.statusPageByUrl,
+ data: statusPage,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "getDistributedStatusPageByUrl"));
+ }
+ };
+
+ getStatusPageByUrl = async (req, res, next) => {
+ try {
+ await getStatusPageParamValidation.validateAsync(req.params);
+ await getStatusPageQueryValidation.validateAsync(req.query);
+ } catch (error) {
+ next(handleValidationError(error, SERVICE_NAME));
+ return;
+ }
+
+ try {
+ const statusPage = await this.db.getStatusPageByUrl(req.params.url, req.query.type);
+ return res.success({
+ msg: this.stringService.statusPageByUrl,
+ data: statusPage,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "getStatusPageByUrl"));
+ }
+ };
+
+ getStatusPagesByTeamId = async (req, res, next) => {
+ try {
+ const teamId = req.params.teamId;
+ const statusPages = await this.db.getStatusPagesByTeamId(teamId);
+
+ return res.success({
+ msg: this.stringService.statusPageByTeamId,
+ data: statusPages,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "getStatusPageByTeamId"));
+ }
+ };
+
+ deleteStatusPage = async (req, res, next) => {
+ try {
+ await this.db.deleteStatusPage(req.params.url);
+ return res.success({
+ msg: this.stringService.statusPageDelete,
+ });
+ } catch (error) {
+ next(handleError(error, SERVICE_NAME, "deleteStatusPage"));
+ }
+ };
+}
+
+export default StatusPageController;
diff --git a/server/db/models/AppSettings.js b/server/db/models/AppSettings.js
new file mode 100755
index 000000000..22e586131
--- /dev/null
+++ b/server/db/models/AppSettings.js
@@ -0,0 +1,47 @@
+import mongoose from "mongoose";
+
+const AppSettingsSchema = mongoose.Schema(
+ {
+ checkTTL: {
+ type: Number,
+ default: 30,
+ },
+ language: {
+ type: String,
+ default: "gb",
+ },
+ pagespeedApiKey: {
+ type: String,
+ },
+ systemEmailHost: {
+ type: String,
+ },
+ systemEmailPort: {
+ type: Number,
+ },
+ systemEmailAddress: {
+ type: String,
+ },
+ systemEmailPassword: {
+ type: String,
+ },
+ systemEmailUser: {
+ type: String,
+ },
+ singleton: {
+ type: Boolean,
+ required: true,
+ unique: true,
+ default: true,
+ },
+ version: {
+ type: Number,
+ default: 1,
+ },
+ },
+ {
+ timestamps: true,
+ }
+);
+
+export default mongoose.model("AppSettings", AppSettingsSchema);
diff --git a/Server/db/models/Check.js b/server/db/models/Check.js
old mode 100644
new mode 100755
similarity index 86%
rename from Server/db/models/Check.js
rename to server/db/models/Check.js
index 158749986..39c5281d2
--- a/Server/db/models/Check.js
+++ b/server/db/models/Check.js
@@ -73,11 +73,10 @@ const BaseCheckSchema = mongoose.Schema({
* about the status and response of a particular check event.
*/
const CheckSchema = mongoose.Schema({ ...BaseCheckSchema.obj }, { timestamps: true });
-CheckSchema.index({ createdAt: 1 });
-CheckSchema.index({ monitorId: 1, createdAt: 1 });
-CheckSchema.index({ monitorId: 1, createdAt: -1 });
-CheckSchema.index({ teamId: 1, createdAt: -1 });
-CheckSchema.index({ teamId: 1 });
+CheckSchema.index({ updatedAt: 1 });
+CheckSchema.index({ monitorId: 1, updatedAt: 1 });
+CheckSchema.index({ monitorId: 1, updatedAt: -1 });
+CheckSchema.index({ teamId: 1, updatedAt: -1 });
export default mongoose.model("Check", CheckSchema);
export { BaseCheckSchema };
diff --git a/server/db/models/DistributedUptimeCheck.js b/server/db/models/DistributedUptimeCheck.js
new file mode 100755
index 000000000..cb88e2c31
--- /dev/null
+++ b/server/db/models/DistributedUptimeCheck.js
@@ -0,0 +1,137 @@
+import mongoose from "mongoose";
+
+import { BaseCheckSchema } from "./Check.js";
+
+// {
+// "id": "12123",
+// "result": {
+// "task_arrived": "2025-01-13T19:21:37.463466602Z",
+// "dns_start": "2025-01-14T00:21:33.1801319+05:00",
+// "dns_end": "2025-01-14T00:21:33.4582552+05:00",
+// "conn_start": "2025-01-14T00:21:33.1801319+05:00",
+// "conn_end": "2025-01-14T00:21:33.7076318+05:00",
+// "connect_start": "2025-01-14T00:21:33.4582552+05:00",
+// "connect_end": "2025-01-14T00:21:33.541899+05:00",
+// "tls_hand_shake_start": "2025-01-14T00:21:33.541899+05:00",
+// "tls_hand_shake_end": "2025-01-14T00:21:33.7076318+05:00",
+// "body_read_start": "2025-01-14T00:21:34.1894707+05:00",
+// "body_read_end": "2025-01-14T00:21:34.1894707+05:00",
+// "wrote_request": "2025-01-14T00:21:33.7076318+05:00",
+// "got_first_response_byte": "2025-01-14T00:21:34.1327652+05:00",
+// "first_byte_took": 425133400,
+// "body_read_took": 56030000,
+// "dns_took": 278123300,
+// "conn_took": 527499900,
+// "connect_took": 83643800,
+// "tls_took": 165732800,
+// "sni_name": "uprock.com",
+// "status_code": 200,
+// "body_size": 19320,
+// "request_header_size": 95,
+// "response_header_size": 246,
+// "response_headers": "X-Vercel-Id: bom1::iad1::sm87v-1736796096856-aec270c01f23\nDate: Mon, 13 Jan 2025 19:21:37 GMT\nServer: Vercel\nStrict-Transport-Security: max-age=63072000\nVary: RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Url\nX-Matched-Path: /\nX-Powered-By: Next.js\nX-Vercel-Cache: MISS\nAge: 0\nCache-Control: private, no-cache, no-store, max-age=0, must-revalidate\nContent-Type: text/html; charset=utf-8",
+// "error": "",
+// "device_id": "d5f578e143a2cd603dd6bf5f846a86a538bde4a8fbe2ad1fca284ad9f033daf8",
+// "ip_address": "223.123.19.0",
+// "proof": "",
+// "created_at": "2025-01-13T19:21:37.463466912Z",
+// "continent": "AS",
+// "country_code": "PK",
+// "city": "Muzaffargarh",
+// "upt_burnt" : "0.01",
+// "location": {
+// "lat": 71.0968,
+// "lng": 30.0208
+// },
+// "payload": {
+// "callback": "https://webhook.site/2a15b0af-545a-4ac2-b913-153b97592d7a",
+// "x": "y"
+// }
+// }
+// }
+
+const LocationSchema = new mongoose.Schema(
+ {
+ lat: { type: Number, required: true },
+ lng: { type: Number, required: true },
+ },
+ { _id: false }
+);
+
+const DistributedUptimeCheckSchema = mongoose.Schema(
+ {
+ ...BaseCheckSchema.obj,
+ first_byte_took: {
+ type: Number,
+ required: false,
+ },
+ body_read_took: {
+ type: Number,
+ required: false,
+ },
+ dns_took: {
+ type: Number,
+ required: false,
+ },
+ conn_took: {
+ type: Number,
+ required: false,
+ },
+ connect_took: {
+ type: Number,
+ required: false,
+ },
+ tls_took: {
+ type: Number,
+ required: false,
+ },
+ location: {
+ type: LocationSchema,
+ required: false,
+ },
+ continent: {
+ type: String,
+ required: false,
+ },
+ countryCode: {
+ type: String,
+ required: false,
+ },
+ city: {
+ type: String,
+ required: false,
+ },
+ uptBurnt: {
+ type: mongoose.Schema.Types.Decimal128,
+ required: false,
+ },
+ count: {
+ type: Number,
+ required: false,
+ },
+ },
+ { timestamps: true }
+);
+
+DistributedUptimeCheckSchema.pre("save", function (next) {
+ if (this.isModified("uptBurnt") && typeof this.uptBurnt === "string") {
+ this.uptBurnt = mongoose.Types.Decimal128.fromString(this.uptBurnt);
+ }
+ next();
+});
+
+DistributedUptimeCheckSchema.index({ createdAt: 1 });
+DistributedUptimeCheckSchema.index({ monitorId: 1, updatedAt: 1 });
+DistributedUptimeCheckSchema.index({ monitorId: 1, updatedAt: -1 });
+DistributedUptimeCheckSchema.index(
+ {
+ monitorId: 1,
+ createdAt: -1,
+ city: 1,
+ "location.lat": 1,
+ "location.lng": 1,
+ responseTime: 1,
+ },
+ { background: true }
+);
+export default mongoose.model("DistributedUptimeCheck", DistributedUptimeCheckSchema);
diff --git a/Server/db/models/HardwareCheck.js b/server/db/models/HardwareCheck.js
old mode 100644
new mode 100755
similarity index 100%
rename from Server/db/models/HardwareCheck.js
rename to server/db/models/HardwareCheck.js
diff --git a/Server/db/models/InviteToken.js b/server/db/models/InviteToken.js
old mode 100644
new mode 100755
similarity index 96%
rename from Server/db/models/InviteToken.js
rename to server/db/models/InviteToken.js
index 0c2402b07..079600647
--- a/Server/db/models/InviteToken.js
+++ b/server/db/models/InviteToken.js
@@ -15,6 +15,7 @@ const InviteTokenSchema = mongoose.Schema(
role: {
type: Array,
required: true,
+ default: ["user"],
},
token: {
type: String,
diff --git a/Server/db/models/MaintenanceWindow.js b/server/db/models/MaintenanceWindow.js
old mode 100644
new mode 100755
similarity index 100%
rename from Server/db/models/MaintenanceWindow.js
rename to server/db/models/MaintenanceWindow.js
diff --git a/Server/db/models/Monitor.js b/server/db/models/Monitor.js
old mode 100644
new mode 100755
similarity index 79%
rename from Server/db/models/Monitor.js
rename to server/db/models/Monitor.js
index 90cbb1d62..508c1c655
--- a/Server/db/models/Monitor.js
+++ b/server/db/models/Monitor.js
@@ -36,8 +36,23 @@ const MonitorSchema = mongoose.Schema(
"docker",
"port",
"distributed_http",
+ "distributed_test",
],
},
+ ignoreTlsErrors: {
+ type: Boolean,
+ default: false,
+ },
+ jsonPath: {
+ type: String,
+ },
+ expectedValue: {
+ type: String,
+ },
+ matchMethod: {
+ type: String,
+ enum: ["equal", "include", "regex"],
+ },
url: {
type: String,
required: true,
@@ -63,6 +78,7 @@ const MonitorSchema = mongoose.Schema(
usage_cpu: { type: Number },
usage_memory: { type: Number },
usage_disk: { type: Number },
+ usage_temperature: { type: Number },
},
_id: false,
},
@@ -81,4 +97,6 @@ const MonitorSchema = mongoose.Schema(
}
);
+MonitorSchema.index({ teamId: 1, type: 1 });
+
export default mongoose.model("Monitor", MonitorSchema);
diff --git a/server/db/models/MonitorStats.js b/server/db/models/MonitorStats.js
new file mode 100755
index 000000000..c28811b33
--- /dev/null
+++ b/server/db/models/MonitorStats.js
@@ -0,0 +1,53 @@
+import mongoose from "mongoose";
+
+const MonitorStatsSchema = new mongoose.Schema(
+ {
+ monitorId: {
+ type: mongoose.Schema.Types.ObjectId,
+ ref: "Monitor",
+ immutable: true,
+ index: true,
+ },
+ avgResponseTime: {
+ type: Number,
+ default: 0,
+ },
+ totalChecks: {
+ type: Number,
+ default: 0,
+ },
+ totalUpChecks: {
+ type: Number,
+ default: 0,
+ },
+ totalDownChecks: {
+ type: Number,
+ default: 0,
+ },
+ uptimePercentage: {
+ type: Number,
+ default: 0,
+ },
+ lastCheckTimestamp: {
+ type: Number,
+ default: 0,
+ },
+ lastResponseTime: {
+ type: Number,
+ default: 0,
+ },
+ timeOfLastFailure: {
+ type: Number,
+ default: 0,
+ },
+ uptBurnt: {
+ type: mongoose.Schema.Types.Decimal128,
+ required: false,
+ },
+ },
+ { timestamps: true }
+);
+
+const MonitorStats = mongoose.model("MonitorStats", MonitorStatsSchema);
+
+export default MonitorStats;
diff --git a/Server/db/models/Notification.js b/server/db/models/Notification.js
old mode 100644
new mode 100755
similarity index 85%
rename from Server/db/models/Notification.js
rename to server/db/models/Notification.js
index 8767880c1..43eb73c93
--- a/Server/db/models/Notification.js
+++ b/server/db/models/Notification.js
@@ -1,4 +1,14 @@
import mongoose from "mongoose";
+
+const configSchema = mongoose.Schema(
+ {
+ webhookUrl: { type: String },
+ botToken: { type: String },
+ chatId: { type: String },
+ },
+ { _id: false }
+);
+
const NotificationSchema = mongoose.Schema(
{
monitorId: {
@@ -8,7 +18,14 @@ const NotificationSchema = mongoose.Schema(
},
type: {
type: String,
- enum: ["email", "sms"],
+ enum: ["email", "sms", "webhook"],
+ },
+ platform: {
+ type: String,
+ },
+ config: {
+ type: configSchema,
+ default: () => ({}),
},
address: {
type: String,
@@ -76,4 +93,5 @@ NotificationSchema.pre("findOneAndUpdate", function (next) {
}
next();
});
+
export default mongoose.model("Notification", NotificationSchema);
diff --git a/Server/db/models/PageSpeedCheck.js b/server/db/models/PageSpeedCheck.js
old mode 100644
new mode 100755
similarity index 74%
rename from Server/db/models/PageSpeedCheck.js
rename to server/db/models/PageSpeedCheck.js
index c04df0931..513dd3039
--- a/Server/db/models/PageSpeedCheck.js
+++ b/server/db/models/PageSpeedCheck.js
@@ -78,32 +78,6 @@ const PageSpeedCheck = mongoose.Schema(
* @typedef {mongoose.Model} LighthouseMetricsModel
*/
-PageSpeedCheck.pre("save", async function (next) {
- try {
- const monitor = await mongoose.model("Monitor").findById(this.monitorId);
- if (monitor && monitor.status !== this.status) {
- if (monitor.status === true && this.status === false) {
- logger.info({ message: "Monitor went down", monitorId: monitor._id });
- }
-
- if (monitor.status === false && this.status === true) {
- logger.info({ message: "Monitor went up", monitorId: monitor._id });
- }
- monitor.status = this.status;
- await monitor.save();
- }
- } catch (error) {
- logger.error({
- message: error.message,
- service: "PageSpeedCheck",
- method: "pre-save",
- stack: error.stack,
- });
- } finally {
- next();
- }
-});
-
PageSpeedCheck.index({ createdAt: 1 });
PageSpeedCheck.index({ monitorId: 1, createdAt: 1 });
PageSpeedCheck.index({ monitorId: 1, createdAt: -1 });
diff --git a/Server/db/models/RecoveryToken.js b/server/db/models/RecoveryToken.js
old mode 100644
new mode 100755
similarity index 100%
rename from Server/db/models/RecoveryToken.js
rename to server/db/models/RecoveryToken.js
diff --git a/server/db/models/StatusPage.js b/server/db/models/StatusPage.js
new file mode 100755
index 000000000..ab7be6955
--- /dev/null
+++ b/server/db/models/StatusPage.js
@@ -0,0 +1,77 @@
+import mongoose from "mongoose";
+
+const StatusPageSchema = mongoose.Schema(
+ {
+ userId: {
+ type: mongoose.Schema.Types.ObjectId,
+ ref: "User",
+ immutable: true,
+ required: true,
+ },
+ teamId: {
+ type: mongoose.Schema.Types.ObjectId,
+ ref: "Team",
+ immutable: true,
+ required: true,
+ },
+ type: {
+ type: String,
+ required: true,
+ default: "uptime",
+ enum: ["uptime", "distributed"],
+ },
+ companyName: {
+ type: String,
+ required: true,
+ default: "",
+ },
+ url: {
+ type: String,
+ unique: true,
+ required: true,
+ default: "",
+ },
+ timezone: {
+ type: String,
+ required: false,
+ },
+ color: {
+ type: String,
+ required: false,
+ default: "#4169E1",
+ },
+ monitors: [
+ {
+ type: mongoose.Schema.Types.ObjectId,
+ ref: "Monitor",
+ required: true,
+ },
+ ],
+ subMonitors: [
+ {
+ type: mongoose.Schema.Types.ObjectId,
+ ref: "Monitor",
+ required: true,
+ },
+ ],
+ logo: {
+ data: Buffer,
+ contentType: String,
+ },
+ isPublished: {
+ type: Boolean,
+ default: false,
+ },
+ showCharts: {
+ type: Boolean,
+ default: true,
+ },
+ showUptimePercentage: {
+ type: Boolean,
+ default: true,
+ },
+ },
+ { timestamps: true }
+);
+
+export default mongoose.model("StatusPage", StatusPageSchema);
diff --git a/Server/db/models/Team.js b/server/db/models/Team.js
old mode 100644
new mode 100755
similarity index 100%
rename from Server/db/models/Team.js
rename to server/db/models/Team.js
diff --git a/Server/db/models/User.js b/server/db/models/User.js
old mode 100644
new mode 100755
similarity index 68%
rename from Server/db/models/User.js
rename to server/db/models/User.js
index 3ddc5cee0..74ee1166e
--- a/Server/db/models/User.js
+++ b/server/db/models/User.js
@@ -1,5 +1,5 @@
import mongoose from "mongoose";
-import bcrypt from "bcrypt";
+import bcrypt from "bcryptjs";
import logger from "../../utils/logger.js";
const UserSchema = mongoose.Schema(
@@ -55,20 +55,20 @@ const UserSchema = mongoose.Schema(
}
);
-UserSchema.pre("save", async function (next) {
+UserSchema.pre("save", function (next) {
if (!this.isModified("password")) {
- next();
+ return next();
}
- const salt = await bcrypt.genSalt(10); //genSalt is asynchronous, need to wait
- this.password = await bcrypt.hash(this.password, salt); // hash is also async, need to eitehr await or use hashSync
+ const salt = bcrypt.genSaltSync(10);
+ this.password = bcrypt.hashSync(this.password, salt);
next();
});
-UserSchema.pre("findOneAndUpdate", async function (next) {
+UserSchema.pre("findOneAndUpdate", function (next) {
const update = this.getUpdate();
if ("password" in update) {
- const salt = await bcrypt.genSalt(10); //genSalt is asynchronous, need to wait
- update.password = await bcrypt.hash(update.password, salt); // hash is also async, need to eitehr await or use hashSync
+ const salt = bcrypt.genSaltSync(10);
+ update.password = bcrypt.hashSync(update.password, salt);
}
next();
@@ -89,4 +89,4 @@ User.init().then(() => {
});
});
-export default mongoose.model("User", UserSchema);
+export default User;
diff --git a/Server/db/mongo/MongoDB.js b/server/db/mongo/MongoDB.js
old mode 100644
new mode 100755
similarity index 83%
rename from Server/db/mongo/MongoDB.js
rename to server/db/mongo/MongoDB.js
index e62828a41..b657caec4
--- a/Server/db/mongo/MongoDB.js
+++ b/server/db/mongo/MongoDB.js
@@ -43,6 +43,11 @@ import * as hardwareCheckModule from "./modules/hardwareCheckModule.js";
import * as checkModule from "./modules/checkModule.js";
+//****************************************
+// Distributed Checks
+//****************************************
+import * as distributedCheckModule from "./modules/distributedCheckModule.js";
+
//****************************************
// Maintenance Window
//****************************************
@@ -63,10 +68,16 @@ import * as settingsModule from "./modules/settingsModule.js";
//****************************************
import * as statusPageModule from "./modules/statusPageModule.js";
+//****************************************
+// Diagnostic
+//****************************************
+import * as diagnosticModule from "./modules/diagnosticModule.js";
+
class MongoDB {
static SERVICE_NAME = "MongoDB";
- constructor() {
+ constructor({ appSettings }) {
+ this.appSettings = appSettings;
Object.assign(this, userModule);
Object.assign(this, inviteModule);
Object.assign(this, recoveryModule);
@@ -74,23 +85,28 @@ class MongoDB {
Object.assign(this, pageSpeedCheckModule);
Object.assign(this, hardwareCheckModule);
Object.assign(this, checkModule);
+ Object.assign(this, distributedCheckModule);
Object.assign(this, maintenanceWindowModule);
Object.assign(this, notificationModule);
Object.assign(this, settingsModule);
Object.assign(this, statusPageModule);
+ Object.assign(this, diagnosticModule);
}
connect = async () => {
try {
const connectionString =
- process.env.DB_CONNECTION_STRING || "mongodb://localhost:27017/uptime_db";
+ this.appSettings.dbConnectionString || "mongodb://localhost:27017/uptime_db";
await mongoose.connect(connectionString);
// If there are no AppSettings, create one
- let appSettings = await AppSettings.find();
- if (appSettings.length === 0) {
- appSettings = new AppSettings({});
- await appSettings.save();
- }
+ await AppSettings.findOneAndUpdate(
+ {}, // empty filter to match any document
+ {}, // empty update
+ {
+ new: true,
+ setDefaultsOnInsert: true,
+ }
+ );
// Sync indexes
const models = mongoose.modelNames();
for (const modelName of models) {
diff --git a/Server/db/mongo/modules/checkModule.js b/server/db/mongo/modules/checkModule.js
old mode 100644
new mode 100755
similarity index 73%
rename from Server/db/mongo/modules/checkModule.js
rename to server/db/mongo/modules/checkModule.js
index 7965e7c30..2b0eb33ba
--- a/Server/db/mongo/modules/checkModule.js
+++ b/server/db/mongo/modules/checkModule.js
@@ -1,11 +1,15 @@
import Check from "../../models/Check.js";
import Monitor from "../../models/Monitor.js";
+import HardwareCheck from "../../models/HardwareCheck.js";
+import PageSpeedCheck from "../../models/PageSpeedCheck.js";
+import DistributedUptimeCheck from "../../models/DistributedUptimeCheck.js";
import User from "../../models/User.js";
import logger from "../../../utils/logger.js";
import { ObjectId } from "mongodb";
const SERVICE_NAME = "checkModule";
const dateRangeLookup = {
+ recent: new Date(new Date().setDate(new Date().getDate() - 2)),
hour: new Date(new Date().setHours(new Date().getHours() - 1)),
day: new Date(new Date().setDate(new Date().getDate() - 1)),
week: new Date(new Date().setDate(new Date().getDate() - 7)),
@@ -28,30 +32,7 @@ const dateRangeLookup = {
const createCheck = async (checkData) => {
try {
- const { monitorId, status } = checkData;
- const n = (await Check.countDocuments({ monitorId })) + 1;
const check = await new Check({ ...checkData }).save();
- const monitor = await Monitor.findById(monitorId);
-
- if (!monitor) {
- logger.error({
- message: "Monitor not found",
- service: SERVICE_NAME,
- method: "createCheck",
- details: `monitor ID: ${monitorId}`,
- });
- return;
- }
-
- // Update uptime percentage
- if (monitor.uptimePercentage === undefined) {
- monitor.uptimePercentage = status === true ? 1 : 0;
- } else {
- monitor.uptimePercentage =
- (monitor.uptimePercentage * (n - 1) + (status === true ? 1 : 0)) / n;
- }
-
- await monitor.save();
return check;
} catch (error) {
error.service = SERVICE_NAME;
@@ -60,6 +41,16 @@ const createCheck = async (checkData) => {
}
};
+const createChecks = async (checks) => {
+ try {
+ await Check.insertMany(checks);
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "createCheck";
+ throw error;
+ }
+};
+
/**
* Get all checks for a monitor
* @async
@@ -70,13 +61,14 @@ const createCheck = async (checkData) => {
const getChecksByMonitor = async (req) => {
try {
const { monitorId } = req.params;
- let { sortOrder, dateRange, filter, page, rowsPerPage } = req.query;
+ let { type, sortOrder, dateRange, filter, page, rowsPerPage, status } = req.query;
+ status = typeof status !== "undefined" ? false : undefined;
page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage);
// Match
const matchStage = {
monitorId: ObjectId.createFromHexString(monitorId),
- status: false,
+ ...(typeof status !== "undefined" && { status }),
...(dateRangeLookup[dateRange] && {
createdAt: {
$gte: dateRangeLookup[dateRange],
@@ -112,7 +104,20 @@ const getChecksByMonitor = async (req) => {
skip = page * rowsPerPage;
}
- const checks = await Check.aggregate([
+ const checkModels = {
+ http: Check,
+ ping: Check,
+ docker: Check,
+ port: Check,
+ pagespeed: PageSpeedCheck,
+ hardware: HardwareCheck,
+ distributed_http: DistributedUptimeCheck,
+ distributed_test: DistributedUptimeCheck,
+ };
+
+ const Model = checkModels[type];
+
+ const checks = await Model.aggregate([
{ $match: matchStage },
{ $sort: { createdAt: sortOrder } },
{
@@ -123,12 +128,15 @@ const getChecksByMonitor = async (req) => {
},
{
$project: {
- checksCount: { $arrayElemAt: ["$summary.checksCount", 0] },
- checks: "$checks",
+ checksCount: {
+ $ifNull: [{ $arrayElemAt: ["$summary.checksCount", 0] }, 0],
+ },
+ checks: {
+ $ifNull: ["$checks", []],
+ },
},
},
]);
-
return checks[0];
} catch (error) {
error.service = SERVICE_NAME;
@@ -180,10 +188,27 @@ const getChecksByTeam = async (req) => {
skip = page * rowsPerPage;
}
- const checks = await Check.aggregate([
+ const aggregatePipeline = [
{ $match: matchStage },
+ {
+ $unionWith: {
+ coll: "hardwarechecks",
+ pipeline: [{ $match: matchStage }],
+ },
+ },
+ {
+ $unionWith: {
+ coll: "pagespeedchecks",
+ pipeline: [{ $match: matchStage }],
+ },
+ },
+ {
+ $unionWith: {
+ coll: "distributeduptimechecks",
+ pipeline: [{ $match: matchStage }],
+ },
+ },
{ $sort: { createdAt: sortOrder } },
-
{
$facet: {
summary: [{ $count: "checksCount" }],
@@ -196,8 +221,9 @@ const getChecksByTeam = async (req) => {
checks: "$checks",
},
},
- ]);
+ ];
+ const checks = await Check.aggregate(aggregatePipeline);
return checks[0];
} catch (error) {
error.service = SERVICE_NAME;
@@ -235,19 +261,14 @@ const deleteChecks = async (monitorId) => {
const deleteChecksByTeamId = async (teamId) => {
try {
- const teamMonitors = await Monitor.find({ teamId: teamId });
- let totalDeletedCount = 0;
+ // Find all monitor IDs for this team (only get _id field for efficiency)
+ const teamMonitors = await Monitor.find({ teamId }, { _id: 1 });
+ const monitorIds = teamMonitors.map((monitor) => monitor._id);
- await Promise.all(
- teamMonitors.map(async (monitor) => {
- const result = await Check.deleteMany({ monitorId: monitor._id });
- totalDeletedCount += result.deletedCount;
- monitor.status = true;
- await monitor.save();
- })
- );
+ // Delete all checks for these monitors in one operation
+ const deleteResult = await Check.deleteMany({ monitorId: { $in: monitorIds } });
- return totalDeletedCount;
+ return deleteResult.deletedCount;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteChecksByTeamId";
@@ -289,6 +310,7 @@ const updateChecksTTL = async (teamId, ttl) => {
export {
createCheck,
+ createChecks,
getChecksByMonitor,
getChecksByTeam,
deleteChecks,
diff --git a/server/db/mongo/modules/diagnosticModule.js b/server/db/mongo/modules/diagnosticModule.js
new file mode 100755
index 000000000..2fd8acc71
--- /dev/null
+++ b/server/db/mongo/modules/diagnosticModule.js
@@ -0,0 +1,107 @@
+import DistributedUptimeCheck from "../../models/DistributedUptimeCheck.js";
+import Monitor from "../../models/Monitor.js";
+import { ObjectId } from "mongodb";
+
+const SERVICE_NAME = "diagnosticModule";
+import {
+ buildMonitorSummaryByTeamIdPipeline,
+ buildMonitorsByTeamIdPipeline,
+ buildFilteredMonitorsByTeamIdPipeline,
+ buildDePINDetailsByDateRange,
+ buildDePINLatestChecks,
+} from "./monitorModuleQueries.js";
+import { getDateRange } from "./monitorModule.js";
+
+const getDistributedUptimeDbExecutionStats = async (req) => {
+ try {
+ const { monitorId } = req?.params ?? {};
+ if (typeof monitorId === "undefined") {
+ throw new Error();
+ }
+ const monitor = await Monitor.findById(monitorId);
+ if (monitor === null || monitor === undefined) {
+ throw new Error(this.stringService.dbFindMonitorById(monitorId));
+ }
+
+ const { dateRange } = req.query;
+ const dates = getDateRange(dateRange);
+ const formatLookup = {
+ recent: "%Y-%m-%dT%H:%M:00Z",
+ day: {
+ $concat: [
+ { $dateToString: { format: "%Y-%m-%dT%H:", date: "$createdAt" } },
+ {
+ $cond: [{ $lt: [{ $minute: "$createdAt" }, 30] }, "00:00Z", "30:00Z"],
+ },
+ ],
+ },
+ week: "%Y-%m-%dT%H:00:00Z",
+ month: "%Y-%m-%dT00:00:00Z",
+ };
+
+ const dateString = formatLookup[dateRange];
+
+ const dePINDetailsByDateRangeStats = await DistributedUptimeCheck.aggregate(
+ buildDePINDetailsByDateRange(monitor, dates, dateString)
+ ).explain("executionStats");
+ const latestChecksStats = await DistributedUptimeCheck.aggregate(
+ buildDePINLatestChecks(monitor)
+ ).explain("executionStats");
+
+ return {
+ dePINDetailsByDateRangeStats,
+ latestChecksStats,
+ };
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "getAllMonitorsWithUptimeStats";
+ throw error;
+ }
+};
+
+const getMonitorsByTeamIdExecutionStats = async (req) => {
+ try {
+ let { limit, type, page, rowsPerPage, filter, field, order } = req.query;
+ limit = parseInt(limit);
+ page = parseInt(page);
+ rowsPerPage = parseInt(rowsPerPage);
+ if (field === undefined) {
+ field = "name";
+ order = "asc";
+ }
+ // Build match stage
+ const matchStage = { teamId: ObjectId.createFromHexString(req.params.teamId) };
+ if (type !== undefined) {
+ matchStage.type = Array.isArray(type) ? { $in: type } : type;
+ }
+
+ const summary = await Monitor.aggregate(
+ buildMonitorSummaryByTeamIdPipeline({ matchStage })
+ ).explain("executionStats");
+
+ const monitors = await Monitor.aggregate(
+ buildMonitorsByTeamIdPipeline({ matchStage, field, order })
+ ).explain("executionStats");
+
+ const filteredMonitors = await Monitor.aggregate(
+ buildFilteredMonitorsByTeamIdPipeline({
+ matchStage,
+ filter,
+ page,
+ rowsPerPage,
+ field,
+ order,
+ limit,
+ type,
+ })
+ ).explain("executionStats");
+
+ return { summary, monitors, filteredMonitors };
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "getMonitorSummaryByTeamIdExecutionStats";
+ throw error;
+ }
+};
+
+export { getDistributedUptimeDbExecutionStats, getMonitorsByTeamIdExecutionStats };
diff --git a/server/db/mongo/modules/distributedCheckModule.js b/server/db/mongo/modules/distributedCheckModule.js
new file mode 100755
index 000000000..10fc577b2
--- /dev/null
+++ b/server/db/mongo/modules/distributedCheckModule.js
@@ -0,0 +1,157 @@
+import DistributedUptimeCheck from "../../models/DistributedUptimeCheck.js";
+import { ObjectId } from "mongodb";
+
+const SERVICE_NAME = "distributedCheckModule";
+
+const createDistributedCheck = async (checkData) => {
+ try {
+ if (typeof checkData.monitorId === "string") {
+ checkData.monitorId = ObjectId.createFromHexString(checkData.monitorId);
+ }
+ const check = await DistributedUptimeCheck.findOneAndUpdate(
+ {
+ monitorId: checkData.monitorId,
+ city: checkData.city,
+ },
+ [
+ {
+ $set: {
+ ...checkData,
+
+ responseTime: {
+ $cond: {
+ if: { $ifNull: ["$count", false] },
+ then: {
+ $cond: {
+ // Check if the new value is an outlier (3x the current average)
+ if: {
+ $and: [
+ { $gt: ["$responseTime", 0] },
+ {
+ $gt: [
+ checkData.responseTime,
+ { $multiply: ["$responseTime", 3] },
+ ],
+ },
+ ],
+ },
+ then: "$responseTime", // Keep the current value if it's an outlier
+ else: {
+ // Normal case - calculate new average
+ $round: [
+ {
+ $divide: [
+ {
+ $add: [
+ { $multiply: ["$responseTime", "$count"] },
+ checkData.responseTime,
+ ],
+ },
+ { $add: ["$count", 1] },
+ ],
+ },
+ 2,
+ ],
+ },
+ },
+ },
+ else: checkData.responseTime,
+ },
+ },
+ count: { $add: [{ $ifNull: ["$count", 0] }, 1] },
+ },
+ },
+ ],
+ {
+ upsert: true,
+ new: true,
+ runValidators: true,
+ }
+ );
+ return check;
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "createCheck";
+ throw error;
+ }
+};
+
+const createDistributedChecks = async (checksData) => {
+ try {
+ if (!Array.isArray(checksData) || checksData.length === 0) {
+ return;
+ }
+
+ const bulkOps = checksData.map((checkData) => {
+ if (typeof checkData.monitorId === "string") {
+ checkData.monitorId = ObjectId.createFromHexString(checkData.monitorId);
+ }
+
+ return {
+ updateOne: {
+ filter: {
+ monitorId: checkData.monitorId,
+ city: checkData.city,
+ },
+ update: [
+ {
+ $set: {
+ ...checkData,
+ responseTime: {
+ $cond: {
+ if: { $ifNull: ["$count", false] },
+ then: {
+ $round: [
+ {
+ $divide: [
+ {
+ $add: [
+ { $multiply: ["$responseTime", "$count"] },
+ checkData.responseTime,
+ ],
+ },
+ { $add: ["$count", 1] },
+ ],
+ },
+ 2,
+ ],
+ },
+ else: checkData.responseTime,
+ },
+ },
+ count: { $add: [{ $ifNull: ["$count", 0] }, 1] },
+ },
+ },
+ ],
+ upsert: true,
+ },
+ };
+ });
+
+ // Execute bulk operation
+ await DistributedUptimeCheck.bulkWrite(bulkOps, {
+ ordered: false, // Allow parallel processing
+ });
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "createDistributedChecks";
+ throw error;
+ }
+};
+
+const deleteDistributedChecksByMonitorId = async (monitorId) => {
+ try {
+ const result = await DistributedUptimeCheck.deleteMany({ monitorId });
+ return result.deletedCount;
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "deleteDistributedChecksByMonitorId";
+ throw error;
+ }
+};
+
+export {
+ createDistributedCheck,
+ createDistributedChecks,
+ deleteDistributedChecksByMonitorId,
+};
diff --git a/Server/db/mongo/modules/hardwareCheckModule.js b/server/db/mongo/modules/hardwareCheckModule.js
old mode 100644
new mode 100755
similarity index 75%
rename from Server/db/mongo/modules/hardwareCheckModule.js
rename to server/db/mongo/modules/hardwareCheckModule.js
index 25f14bae1..738412c60
--- a/Server/db/mongo/modules/hardwareCheckModule.js
+++ b/server/db/mongo/modules/hardwareCheckModule.js
@@ -37,13 +37,29 @@ const createHardwareCheck = async (hardwareCheckData) => {
}).save();
return hardwareCheck;
} catch (error) {
- console.log("error creating hardware check", error);
+ logger.error({
+ message: "Error creating hardware check",
+ service: SERVICE_NAME,
+ method: "createHardwareCheck",
+ stack: error.stack,
+ });
error.service = SERVICE_NAME;
error.method = "createHardwareCheck";
throw error;
}
};
+const createHardwareChecks = async (hardwareChecks) => {
+ try {
+ await HardwareCheck.insertMany(hardwareChecks);
+ return true;
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "createHardwareChecks";
+ throw error;
+ }
+};
+
const deleteHardwareChecksByMonitorId = async (monitorId) => {
try {
const result = await HardwareCheck.deleteMany({ monitorId });
@@ -55,4 +71,4 @@ const deleteHardwareChecksByMonitorId = async (monitorId) => {
}
};
-export { createHardwareCheck, deleteHardwareChecksByMonitorId };
+export { createHardwareCheck, createHardwareChecks, deleteHardwareChecksByMonitorId };
diff --git a/Server/db/mongo/modules/inviteModule.js b/server/db/mongo/modules/inviteModule.js
old mode 100644
new mode 100755
similarity index 86%
rename from Server/db/mongo/modules/inviteModule.js
rename to server/db/mongo/modules/inviteModule.js
index 0cbf0ab04..f5c960697
--- a/Server/db/mongo/modules/inviteModule.js
+++ b/server/db/mongo/modules/inviteModule.js
@@ -1,6 +1,7 @@
import InviteToken from "../../models/InviteToken.js";
import crypto from "crypto";
-import { errorMessages } from "../../../utils/messages.js";
+import ServiceRegistry from "../../../service/serviceRegistry.js";
+import StringService from "../../../service/stringService.js";
const SERVICE_NAME = "inviteModule";
/**
@@ -42,12 +43,13 @@ const requestInviteToken = async (userData) => {
* @throws {Error} If the invite token is not found or there is another error.
*/
const getInviteToken = async (token) => {
+ const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
const invite = await InviteToken.findOne({
token,
});
if (invite === null) {
- throw new Error(errorMessages.AUTH_INVITE_NOT_FOUND);
+ throw new Error(stringService.authInviteNotFound);
}
return invite;
} catch (error) {
@@ -68,12 +70,13 @@ const getInviteToken = async (token) => {
* @throws {Error} If the invite token is not found or there is another error.
*/
const getInviteTokenAndDelete = async (token) => {
+ const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
const invite = await InviteToken.findOneAndDelete({
token,
});
if (invite === null) {
- throw new Error(errorMessages.AUTH_INVITE_NOT_FOUND);
+ throw new Error(stringService.authInviteNotFound);
}
return invite;
} catch (error) {
diff --git a/Server/db/mongo/modules/maintenanceWindowModule.js b/server/db/mongo/modules/maintenanceWindowModule.js
old mode 100644
new mode 100755
similarity index 86%
rename from Server/db/mongo/modules/maintenanceWindowModule.js
rename to server/db/mongo/modules/maintenanceWindowModule.js
index 072f83c3d..959f3f961
--- a/Server/db/mongo/modules/maintenanceWindowModule.js
+++ b/server/db/mongo/modules/maintenanceWindowModule.js
@@ -14,17 +14,6 @@ const SERVICE_NAME = "maintenanceWindowModule";
* @param {Date} maintenanceWindowData.end - The end date and time of the maintenance window.
* @returns {Promise} The saved MaintenanceWindow document.
* @throws {Error} If there is an error saving the document.
- * @example
- * const maintenanceWindowData = {
- * monitorId: 'yourMonitorId',
- * active: true,
- * oneTime: true,
- * start: new Date(),
- * end: new Date(),
- * };
- * createMaintenanceWindow(maintenanceWindowData)
- * .then(maintenanceWindow => console.log(maintenanceWindow))
- * .catch(error => console.error(error));
*/
const createMaintenanceWindow = async (maintenanceWindowData) => {
try {
@@ -66,10 +55,6 @@ const getMaintenanceWindowById = async (maintenanceWindowId) => {
* @param {Object} query - The request body.
* @returns {Promise>} An array of MaintenanceWindow documents.
* @throws {Error} If there is an error retrieving the documents.
- * @example
- * getMaintenanceWindowByUserId(teamId)
- * .then(maintenanceWindows => console.log(maintenanceWindows))
- * .catch(error => console.error(error));
*/
const getMaintenanceWindowsByTeamId = async (teamId, query) => {
try {
@@ -113,10 +98,6 @@ const getMaintenanceWindowsByTeamId = async (teamId, query) => {
* @param {mongoose.Schema.Types.ObjectId} monitorId - The ID of the monitor.
* @returns {Promise>} An array of MaintenanceWindow documents.
* @throws {Error} If there is an error retrieving the documents.
- * @example
- * getMaintenanceWindowsByMonitorId('monitorId')
- * .then(maintenanceWindows => console.log(maintenanceWindows))
- * .catch(error => console.error(error));
*/
const getMaintenanceWindowsByMonitorId = async (monitorId) => {
try {
@@ -138,10 +119,6 @@ const getMaintenanceWindowsByMonitorId = async (monitorId) => {
* @param {mongoose.Schema.Types.ObjectId} maintenanceWindowId - The ID of the MaintenanceWindow document to delete.
* @returns {Promise} The deleted MaintenanceWindow document.
* @throws {Error} If there is an error deleting the document.
- * @example
- * deleteMaintenanceWindowById('maintenanceWindowId')
- * .then(maintenanceWindow => console.log(maintenanceWindow))
- * .catch(error => console.error(error));
*/
const deleteMaintenanceWindowById = async (maintenanceWindowId) => {
try {
@@ -163,9 +140,6 @@ const deleteMaintenanceWindowById = async (maintenanceWindowId) => {
* @returns {Promise} The result of the delete operation. This object contains information about the operation, such as the number of documents deleted.
* @throws {Error} If there is an error deleting the documents.
* @example
- * deleteMaintenanceWindowByMonitorId('monitorId')
- * .then(result => console.log(result))
- * .catch(error => console.error(error));
*/
const deleteMaintenanceWindowByMonitorId = async (monitorId) => {
try {
@@ -186,9 +160,6 @@ const deleteMaintenanceWindowByMonitorId = async (monitorId) => {
* @returns {Promise} The result of the delete operation. This object contains information about the operation, such as the number of documents deleted.
* @throws {Error} If there is an error deleting the documents.
* @example
- * deleteMaintenanceWindowByUserId('userId')
- * .then(result => console.log(result))
- * .catch(error => console.error(error));
*/
const deleteMaintenanceWindowByUserId = async (userId) => {
try {
diff --git a/Server/db/mongo/modules/monitorModule.js b/server/db/mongo/modules/monitorModule.js
old mode 100644
new mode 100755
similarity index 71%
rename from Server/db/mongo/modules/monitorModule.js
rename to server/db/mongo/modules/monitorModule.js
index 4c60e0f22..fe8e3c2fc
--- a/Server/db/mongo/modules/monitorModule.js
+++ b/server/db/mongo/modules/monitorModule.js
@@ -1,18 +1,30 @@
import Monitor from "../../models/Monitor.js";
+import MonitorStats from "../../models/MonitorStats.js";
import Check from "../../models/Check.js";
import PageSpeedCheck from "../../models/PageSpeedCheck.js";
import HardwareCheck from "../../models/HardwareCheck.js";
-import { errorMessages } from "../../../utils/messages.js";
+import DistributedUptimeCheck from "../../models/DistributedUptimeCheck.js";
import Notification from "../../models/Notification.js";
import { NormalizeData, NormalizeDataUptimeDetails } from "../../../utils/dataUtils.js";
+import ServiceRegistry from "../../../service/serviceRegistry.js";
+import StringService from "../../../service/stringService.js";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
+import { ObjectId } from "mongodb";
+
import {
buildUptimeDetailsPipeline,
buildHardwareDetailsPipeline,
+ buildMonitorStatsPipeline,
+ buildMonitorSummaryByTeamIdPipeline,
+ buildMonitorsByTeamIdPipeline,
+ buildMonitorsAndSummaryByTeamIdPipeline,
+ buildMonitorsWithChecksByTeamIdPipeline,
+ buildFilteredMonitorsByTeamIdPipeline,
+ buildDePINDetailsByDateRange,
+ buildDePINLatestChecks,
} from "./monitorModuleQueries.js";
-import { ObjectId } from "mongodb";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
@@ -208,6 +220,7 @@ const getIncidents = (checks) => {
*/
const getDateRange = (dateRange) => {
const startDates = {
+ recent: new Date(new Date().setHours(new Date().getHours() - 2)),
day: new Date(new Date().setDate(new Date().getDate() - 1)),
week: new Date(new Date().setDate(new Date().getDate() - 7)),
month: new Date(new Date().setMonth(new Date().getMonth() - 1)),
@@ -324,40 +337,47 @@ const calculateGroupStats = (group) => {
* @throws {Error}
*/
const getUptimeDetailsById = async (req) => {
+ const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
const { monitorId } = req.params;
- const monitor = await Monitor.findById(monitorId);
- if (monitor === null || monitor === undefined) {
- throw new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId));
- }
-
const { dateRange, normalize } = req.query;
const dates = getDateRange(dateRange);
const formatLookup = {
+ recent: "%Y-%m-%dT%H:%M:00Z",
day: "%Y-%m-%dT%H:00:00Z",
week: "%Y-%m-%dT%H:00:00Z",
month: "%Y-%m-%dT00:00:00Z",
};
const dateString = formatLookup[dateRange];
+
const results = await Check.aggregate(
- buildUptimeDetailsPipeline(monitor, dates, dateString)
+ buildUptimeDetailsPipeline(monitorId, dates, dateString)
);
const monitorData = results[0];
+
+ monitorData.groupedUpChecks = NormalizeDataUptimeDetails(
+ monitorData.groupedUpChecks,
+ 10,
+ 100
+ );
+
+ monitorData.groupedDownChecks = NormalizeDataUptimeDetails(
+ monitorData.groupedDownChecks,
+ 10,
+ 100
+ );
+
const normalizedGroupChecks = NormalizeDataUptimeDetails(
monitorData.groupedChecks,
10,
100
);
- const monitorStats = {
- ...monitor.toObject(),
- ...monitorData,
- groupedChecks: normalizedGroupChecks,
- };
-
- return monitorStats;
+ monitorData.groupedChecks = normalizedGroupChecks;
+ const monitorStats = await MonitorStats.findOne({ monitorId });
+ return { monitorData, monitorStats };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getUptimeDetailsById";
@@ -365,6 +385,72 @@ const getUptimeDetailsById = async (req) => {
}
};
+const getDistributedUptimeDetailsById = async (req) => {
+ try {
+ const { monitorId } = req?.params ?? {};
+ if (typeof monitorId === "undefined") {
+ throw new Error();
+ }
+ const monitor = await Monitor.findById(monitorId);
+ if (monitor === null || monitor === undefined) {
+ throw new Error(this.stringService.dbFindMonitorById(monitorId));
+ }
+
+ const { dateRange, normalize } = req.query;
+ const dates = getDateRange(dateRange);
+ const formatLookup = {
+ recent: "%Y-%m-%dT%H:%M:00Z",
+ day: {
+ $concat: [
+ { $dateToString: { format: "%Y-%m-%dT%H:", date: "$updatedAt" } },
+ {
+ $cond: [{ $lt: [{ $minute: "$updatedAt" }, 30] }, "00:00Z", "30:00Z"],
+ },
+ ],
+ },
+ week: "%Y-%m-%dT%H:00:00Z",
+ month: "%Y-%m-%dT00:00:00Z",
+ };
+
+ const dateString = formatLookup[dateRange];
+
+ const monitorStatsResult = await MonitorStats.aggregate(
+ buildMonitorStatsPipeline(monitor)
+ );
+ const monitorStats = monitorStatsResult[0];
+ const dePINDetailsByDateRange = await DistributedUptimeCheck.aggregate(
+ buildDePINDetailsByDateRange(monitor, dates, dateString)
+ );
+ const latestChecks = await DistributedUptimeCheck.aggregate(
+ buildDePINLatestChecks(monitor)
+ );
+
+ const checkData = dePINDetailsByDateRange[0];
+ const normalizedGroupChecks = NormalizeDataUptimeDetails(
+ checkData.groupedChecks,
+ 10,
+ 100
+ );
+ const data = {
+ ...monitor.toObject(),
+ latestChecks,
+ totalChecks: monitorStats?.totalChecks,
+ avgResponseTime: monitorStats?.avgResponseTime,
+ uptimePercentage: monitorStats?.uptimePercentage,
+ timeSinceLastCheck: monitorStats?.timeSinceLastCheck,
+ uptBurnt: monitorStats?.uptBurnt,
+ groupedChecks: normalizedGroupChecks,
+ groupedMapChecks: checkData.groupedMapChecks,
+ };
+
+ return data;
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "getDistributedUptimeDetailsById";
+ throw error;
+ }
+};
+
/**
* Get stats by monitor ID
* @async
@@ -374,13 +460,14 @@ const getUptimeDetailsById = async (req) => {
* @throws {Error}
*/
const getMonitorStatsById = async (req) => {
+ const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
const { monitorId } = req.params;
// Get monitor, if we can't find it, abort with error
const monitor = await Monitor.findById(monitorId);
if (monitor === null || monitor === undefined) {
- throw new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId));
+ throw new Error(stringService.getDbFindMonitorById(monitorId));
}
// Get query params
@@ -441,6 +528,7 @@ const getHardwareDetailsById = async (req) => {
const monitor = await Monitor.findById(monitorId);
const dates = getDateRange(dateRange);
const formatLookup = {
+ recent: "%Y-%m-%dT%H:%M:00Z",
day: "%Y-%m-%dT%H:00:00Z",
week: "%Y-%m-%dT%H:00:00Z",
month: "%Y-%m-%dT00:00:00Z",
@@ -471,10 +559,11 @@ const getHardwareDetailsById = async (req) => {
* @throws {Error}
*/
const getMonitorById = async (monitorId) => {
+ const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
const monitor = await Monitor.findById(monitorId);
if (monitor === null || monitor === undefined) {
- const error = new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId));
+ const error = new Error(stringService.getDbFindMonitorById(monitorId));
error.status = 404;
throw error;
}
@@ -497,7 +586,6 @@ const getMonitorById = async (monitorId) => {
const getMonitorsByTeamId = async (req) => {
let { limit, type, page, rowsPerPage, filter, field, order } = req.query;
-
limit = parseInt(limit);
page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage);
@@ -505,184 +593,131 @@ const getMonitorsByTeamId = async (req) => {
field = "name";
order = "asc";
}
- // Build the match stage
+ // Build match stage
const matchStage = { teamId: ObjectId.createFromHexString(req.params.teamId) };
if (type !== undefined) {
matchStage.type = Array.isArray(type) ? { $in: type } : type;
}
- const skip = page && rowsPerPage ? page * rowsPerPage : 0;
+ const summaryResult = await Monitor.aggregate(
+ buildMonitorSummaryByTeamIdPipeline({ matchStage })
+ );
+ const summary = summaryResult[0];
- const sort = { [field]: order === "asc" ? 1 : -1 };
- const results = await Monitor.aggregate([
- { $match: matchStage },
- {
- $facet: {
- summary: [
- {
- $group: {
- _id: null,
- totalMonitors: { $sum: 1 },
- upMonitors: {
- $sum: {
- $cond: [{ $eq: ["$status", true] }, 1, 0],
- },
- },
- downMonitors: {
- $sum: {
- $cond: [{ $eq: ["$status", false] }, 1, 0],
- },
- },
- pausedMonitors: {
- $sum: {
- $cond: [{ $eq: ["$isActive", false] }, 1, 0],
- },
- },
- },
- },
- {
- $project: {
- _id: 0,
- },
- },
- ],
- monitors: [
- { $sort: sort },
- {
- $project: {
- _id: 1,
- name: 1,
- },
- },
- ],
- filteredMonitors: [
- ...(filter !== undefined
- ? [
- {
- $match: {
- $or: [
- { name: { $regex: filter, $options: "i" } },
- { url: { $regex: filter, $options: "i" } },
- ],
- },
- },
- ]
- : []),
- { $sort: sort },
- { $skip: skip },
- ...(rowsPerPage ? [{ $limit: rowsPerPage }] : []),
- ...(limit
- ? [
- {
- $lookup: {
- from: "checks",
- let: { monitorId: "$_id" },
- pipeline: [
- {
- $match: {
- $expr: { $eq: ["$monitorId", "$$monitorId"] },
- },
- },
- { $sort: { createdAt: -1 } },
- ...(limit ? [{ $limit: limit }] : []),
- ],
- as: "standardchecks",
- },
- },
- ]
- : []),
- ...(limit
- ? [
- {
- $lookup: {
- from: "pagespeedchecks",
- let: { monitorId: "$_id" },
- pipeline: [
- {
- $match: {
- $expr: { $eq: ["$monitorId", "$$monitorId"] },
- },
- },
- { $sort: { createdAt: -1 } },
- ...(limit ? [{ $limit: limit }] : []),
- ],
- as: "pagespeedchecks",
- },
- },
- ]
- : []),
- ...(limit
- ? [
- {
- $lookup: {
- from: "hardwarechecks",
- let: { monitorId: "$_id" },
- pipeline: [
- {
- $match: {
- $expr: { $eq: ["$monitorId", "$$monitorId"] },
- },
- },
- { $sort: { createdAt: -1 } },
- ...(limit ? [{ $limit: limit }] : []),
- ],
- as: "hardwarechecks",
- },
- },
- ]
- : []),
+ const monitors = await Monitor.aggregate(
+ buildMonitorsByTeamIdPipeline({ matchStage, field, order })
+ );
- {
- $addFields: {
- checks: {
- $switch: {
- branches: [
- {
- case: { $in: ["$type", ["http", "ping", "docker", "port"]] },
- then: "$standardchecks",
- },
- {
- case: { $eq: ["$type", "pagespeed"] },
- then: "$pagespeedchecks",
- },
- {
- case: { $eq: ["$type", "hardware"] },
- then: "$hardwarechecks",
- },
- ],
- default: [],
- },
- },
- },
- },
- {
- $project: {
- standardchecks: 0,
- pagespeedchecks: 0,
- hardwarechecks: 0,
- },
- },
- ],
- },
- },
- {
- $project: {
- summary: { $arrayElemAt: ["$summary", 0] },
- filteredMonitors: 1,
- monitors: 1,
- },
- },
- ]);
+ const filteredMonitors = await Monitor.aggregate(
+ buildFilteredMonitorsByTeamIdPipeline({
+ matchStage,
+ filter,
+ page,
+ rowsPerPage,
+ field,
+ order,
+ limit,
+ type,
+ })
+ );
- let { monitors, filteredMonitors, summary } = results[0];
- filteredMonitors = filteredMonitors.map((monitor) => {
+ const normalizedFilteredMonitors = filteredMonitors.map((monitor) => {
if (!monitor.checks) {
return monitor;
}
monitor.checks = NormalizeData(monitor.checks, 10, 100);
return monitor;
});
- return { monitors, filteredMonitors, summary };
+
+ return { summary, monitors, filteredMonitors: normalizedFilteredMonitors };
+};
+
+const getMonitorsAndSummaryByTeamId = async (req) => {
+ try {
+ const { type } = req.query;
+ const teamId = ObjectId.createFromHexString(req.params.teamId);
+ const matchStage = { teamId };
+ if (type !== undefined) {
+ matchStage.type = Array.isArray(type) ? { $in: type } : type;
+ }
+
+ if (req.explain === true) {
+ return Monitor.aggregate(
+ buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })
+ ).explain("executionStats");
+ }
+
+ const queryResult = await Monitor.aggregate(
+ buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })
+ );
+ const { monitors, summary } = queryResult?.[0] ?? {};
+ return { monitors, summary };
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "getMonitorsAndSummaryByTeamId";
+ throw error;
+ }
+};
+
+const getMonitorsWithChecksByTeamId = async (req) => {
+ try {
+ let { limit, type, page, rowsPerPage, filter, field, order } = req.query;
+ limit = parseInt(limit);
+ page = parseInt(page);
+ rowsPerPage = parseInt(rowsPerPage);
+ if (field === undefined) {
+ field = "name";
+ order = "asc";
+ }
+ const teamId = ObjectId.createFromHexString(req.params.teamId);
+ // Build match stage
+ const matchStage = { teamId };
+ if (type !== undefined) {
+ matchStage.type = Array.isArray(type) ? { $in: type } : type;
+ }
+
+ if (req.explain === true) {
+ return Monitor.aggregate(
+ buildMonitorsWithChecksByTeamIdPipeline({
+ matchStage,
+ filter,
+ page,
+ rowsPerPage,
+ field,
+ order,
+ limit,
+ type,
+ })
+ ).explain("executionStats");
+ }
+
+ const queryResult = await Monitor.aggregate(
+ buildMonitorsWithChecksByTeamIdPipeline({
+ matchStage,
+ filter,
+ page,
+ rowsPerPage,
+ field,
+ order,
+ limit,
+ type,
+ })
+ );
+ const monitors = queryResult[0]?.monitors;
+ const count = queryResult[0]?.count;
+ const normalizedFilteredMonitors = monitors.map((monitor) => {
+ if (!monitor.checks) {
+ return monitor;
+ }
+ monitor.checks = NormalizeData(monitor.checks, 10, 100);
+ return monitor;
+ });
+ return { count, monitors: normalizedFilteredMonitors };
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "getMonitorsWithChecksByTeamId";
+ throw error;
+ }
};
/**
@@ -707,6 +742,27 @@ const createMonitor = async (req, res) => {
}
};
+/**
+ * Create bulk monitors
+ * @async
+ * @param {Express.Request} req
+ * @returns {Promise}
+ * @throws {Error}
+ */
+const createBulkMonitors = async (req) => {
+ try {
+ const monitors = req.map(
+ (item) => new Monitor({ ...item, notifications: undefined })
+ );
+ await Monitor.bulkSave(monitors);
+ return monitors;
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "createBulkMonitors";
+ throw error;
+ }
+};
+
/**
* Delete a monitor by ID
* @async
@@ -716,11 +772,13 @@ const createMonitor = async (req, res) => {
* @throws {Error}
*/
const deleteMonitor = async (req, res) => {
+ const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
+
const monitorId = req.params.monitorId;
try {
const monitor = await Monitor.findByIdAndDelete(monitorId);
if (!monitor) {
- throw new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId));
+ throw new Error(stringService.getDbFindMonitorById(monitorId));
}
return monitor;
} catch (error) {
@@ -815,8 +873,12 @@ export {
getMonitorStatsById,
getMonitorById,
getMonitorsByTeamId,
+ getMonitorsAndSummaryByTeamId,
+ getMonitorsWithChecksByTeamId,
getUptimeDetailsById,
+ getDistributedUptimeDetailsById,
createMonitor,
+ createBulkMonitors,
deleteMonitor,
deleteAllMonitors,
deleteMonitorsByUserId,
@@ -839,3 +901,22 @@ export {
groupChecksByTime,
calculateGroupStats,
};
+
+// limit 25
+// page 1
+// rowsPerPage 25
+// filter undefined
+// field name
+// order asc
+// skip 25
+// sort { name: 1 }
+// filteredMonitors []
+
+// limit 25
+// page NaN
+// rowsPerPage 25
+// filter undefined
+// field name
+// order asc
+// skip 0
+// sort { name: 1 }
diff --git a/server/db/mongo/modules/monitorModuleQueries.js b/server/db/mongo/modules/monitorModuleQueries.js
new file mode 100755
index 000000000..0ffaaf6f1
--- /dev/null
+++ b/server/db/mongo/modules/monitorModuleQueries.js
@@ -0,0 +1,1043 @@
+import { ObjectId } from "mongodb";
+
+const buildUptimeDetailsPipeline = (monitorId, dates, dateString) => {
+ return [
+ {
+ $match: {
+ monitorId: ObjectId.createFromHexString(monitorId),
+ createdAt: { $gte: dates.start, $lte: dates.end },
+ },
+ },
+ {
+ $sort: {
+ createdAt: 1,
+ },
+ },
+ {
+ $facet: {
+ // For the response time chart, should return checks for date window
+ // Grouped by: {day: hour}, {week: day}, {month: day}
+ uptimePercentage: [
+ {
+ $group: {
+ _id: null,
+ upChecks: {
+ $sum: { $cond: [{ $eq: ["$status", true] }, 1, 0] },
+ },
+ totalChecks: { $sum: 1 },
+ },
+ },
+ {
+ $project: {
+ _id: 0,
+ percentage: {
+ $cond: [
+ { $eq: ["$totalChecks", 0] },
+ 0,
+ { $divide: ["$upChecks", "$totalChecks"] },
+ ],
+ },
+ },
+ },
+ ],
+ groupedAvgResponseTime: [
+ {
+ $group: {
+ _id: null,
+ avgResponseTime: {
+ $avg: "$responseTime",
+ },
+ },
+ },
+ ],
+ groupedChecks: [
+ {
+ $group: {
+ _id: {
+ $dateToString: {
+ format: dateString,
+ date: "$createdAt",
+ },
+ },
+ avgResponseTime: {
+ $avg: "$responseTime",
+ },
+ totalChecks: {
+ $sum: 1,
+ },
+ },
+ },
+ {
+ $sort: {
+ _id: 1,
+ },
+ },
+ ],
+ // Up checks grouped by: {day: hour}, {week: day}, {month: day}
+ groupedUpChecks: [
+ {
+ $match: {
+ status: true,
+ },
+ },
+ {
+ $group: {
+ _id: {
+ $dateToString: {
+ format: dateString,
+ date: "$createdAt",
+ },
+ },
+ totalChecks: {
+ $sum: 1,
+ },
+ avgResponseTime: {
+ $avg: "$responseTime",
+ },
+ },
+ },
+ {
+ $sort: { _id: 1 },
+ },
+ ],
+ // Down checks grouped by: {day: hour}, {week: day}, {month: day} for the date window
+ groupedDownChecks: [
+ {
+ $match: {
+ status: false,
+ },
+ },
+ {
+ $group: {
+ _id: {
+ $dateToString: {
+ format: dateString,
+ date: "$createdAt",
+ },
+ },
+ totalChecks: {
+ $sum: 1,
+ },
+ avgResponseTime: {
+ $avg: "$responseTime",
+ },
+ },
+ },
+ {
+ $sort: { _id: 1 },
+ },
+ ],
+ },
+ },
+ {
+ $lookup: {
+ from: "monitors",
+ let: { monitor_id: { $toObjectId: monitorId } },
+ pipeline: [
+ {
+ $match: {
+ $expr: { $eq: ["$_id", "$$monitor_id"] },
+ },
+ },
+ {
+ $project: {
+ _id: 1,
+ name: 1,
+ status: 1,
+ interval: 1,
+ type: 1,
+ url: 1,
+ isActive: 1,
+ },
+ },
+ ],
+ as: "monitor",
+ },
+ },
+ {
+ $project: {
+ groupedAvgResponseTime: {
+ $arrayElemAt: ["$groupedAvgResponseTime.avgResponseTime", 0],
+ },
+
+ groupedChecks: "$groupedChecks",
+ groupedUpChecks: "$groupedUpChecks",
+ groupedDownChecks: "$groupedDownChecks",
+ groupedUptimePercentage: { $arrayElemAt: ["$uptimePercentage.percentage", 0] },
+ monitor: { $arrayElemAt: ["$monitor", 0] },
+ },
+ },
+ ];
+};
+
+const buildHardwareDetailsPipeline = (monitor, dates, dateString) => {
+ return [
+ {
+ $match: {
+ monitorId: monitor._id,
+ createdAt: { $gte: dates.start, $lte: dates.end },
+ },
+ },
+ {
+ $sort: {
+ createdAt: 1,
+ },
+ },
+ {
+ $facet: {
+ aggregateData: [
+ {
+ $group: {
+ _id: null,
+ latestCheck: {
+ $last: "$$ROOT",
+ },
+ totalChecks: {
+ $sum: 1,
+ },
+ },
+ },
+ ],
+ upChecks: [
+ {
+ $match: {
+ status: true,
+ },
+ },
+ {
+ $group: {
+ _id: null,
+ totalChecks: {
+ $sum: 1,
+ },
+ },
+ },
+ ],
+ checks: [
+ {
+ $limit: 1,
+ },
+ {
+ $project: {
+ diskCount: {
+ $size: "$disk",
+ },
+ },
+ },
+ {
+ $lookup: {
+ from: "hardwarechecks",
+ let: {
+ diskCount: "$diskCount",
+ },
+ pipeline: [
+ {
+ $match: {
+ $expr: {
+ $and: [
+ { $eq: ["$monitorId", monitor._id] },
+ { $gte: ["$createdAt", dates.start] },
+ { $lte: ["$createdAt", dates.end] },
+ ],
+ },
+ },
+ },
+ {
+ $group: {
+ _id: {
+ $dateToString: {
+ format: dateString,
+ date: "$createdAt",
+ },
+ },
+ avgCpuUsage: {
+ $avg: "$cpu.usage_percent",
+ },
+ avgMemoryUsage: {
+ $avg: "$memory.usage_percent",
+ },
+ avgTemperatures: {
+ $push: {
+ $ifNull: ["$cpu.temperature", [0]],
+ },
+ },
+ disks: {
+ $push: "$disk",
+ },
+ },
+ },
+ {
+ $project: {
+ _id: 1,
+ avgCpuUsage: 1,
+ avgMemoryUsage: 1,
+ avgTemperature: {
+ $map: {
+ input: {
+ $range: [
+ 0,
+ {
+ $size: {
+ // Handle null temperatures array
+ $ifNull: [
+ { $arrayElemAt: ["$avgTemperatures", 0] },
+ [0], // Default to single-element array if null
+ ],
+ },
+ },
+ ],
+ },
+ as: "index",
+ in: {
+ $avg: {
+ $map: {
+ input: "$avgTemperatures",
+ as: "tempArray",
+ in: {
+ $ifNull: [
+ { $arrayElemAt: ["$$tempArray", "$$index"] },
+ 0, // Default to 0 if element is null
+ ],
+ },
+ },
+ },
+ },
+ },
+ },
+ disks: {
+ $map: {
+ input: {
+ $range: [0, "$$diskCount"],
+ },
+ as: "diskIndex",
+ in: {
+ name: {
+ $concat: [
+ "disk",
+ {
+ $toString: "$$diskIndex",
+ },
+ ],
+ },
+ readSpeed: {
+ $avg: {
+ $map: {
+ input: "$disks",
+ as: "diskArray",
+ in: {
+ $arrayElemAt: [
+ "$$diskArray.read_speed_bytes",
+ "$$diskIndex",
+ ],
+ },
+ },
+ },
+ },
+ writeSpeed: {
+ $avg: {
+ $map: {
+ input: "$disks",
+ as: "diskArray",
+ in: {
+ $arrayElemAt: [
+ "$$diskArray.write_speed_bytes",
+ "$$diskIndex",
+ ],
+ },
+ },
+ },
+ },
+ totalBytes: {
+ $avg: {
+ $map: {
+ input: "$disks",
+ as: "diskArray",
+ in: {
+ $arrayElemAt: [
+ "$$diskArray.total_bytes",
+ "$$diskIndex",
+ ],
+ },
+ },
+ },
+ },
+ freeBytes: {
+ $avg: {
+ $map: {
+ input: "$disks",
+ as: "diskArray",
+ in: {
+ $arrayElemAt: ["$$diskArray.free_bytes", "$$diskIndex"],
+ },
+ },
+ },
+ },
+ usagePercent: {
+ $avg: {
+ $map: {
+ input: "$disks",
+ as: "diskArray",
+ in: {
+ $arrayElemAt: [
+ "$$diskArray.usage_percent",
+ "$$diskIndex",
+ ],
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ ],
+ as: "hourlyStats",
+ },
+ },
+ {
+ $unwind: "$hourlyStats",
+ },
+ {
+ $replaceRoot: {
+ newRoot: "$hourlyStats",
+ },
+ },
+ ],
+ },
+ },
+ {
+ $project: {
+ aggregateData: {
+ $arrayElemAt: ["$aggregateData", 0],
+ },
+ upChecks: {
+ $arrayElemAt: ["$upChecks", 0],
+ },
+ checks: {
+ $sortArray: {
+ input: "$checks",
+ sortBy: { _id: 1 },
+ },
+ },
+ },
+ },
+ ];
+};
+
+const buildMonitorStatsPipeline = (monitor) => {
+ return [
+ {
+ $match: {
+ monitorId: monitor._id,
+ },
+ },
+ {
+ $project: {
+ avgResponseTime: 1,
+ uptimePercentage: 1,
+ totalChecks: 1,
+ timeSinceLastCheck: {
+ $subtract: [Date.now(), "$lastCheckTimestamp"],
+ },
+ lastCheckTimestamp: 1,
+ uptBurnt: { $toString: "$uptBurnt" },
+ },
+ },
+ ];
+};
+
+const buildMonitorSummaryByTeamIdPipeline = ({ matchStage }) => {
+ return [
+ { $match: matchStage },
+ {
+ $group: {
+ _id: null,
+ totalMonitors: { $sum: 1 },
+ upMonitors: {
+ $sum: {
+ $cond: [{ $eq: ["$status", true] }, 1, 0],
+ },
+ },
+ downMonitors: {
+ $sum: {
+ $cond: [{ $eq: ["$status", false] }, 1, 0],
+ },
+ },
+ pausedMonitors: {
+ $sum: {
+ $cond: [{ $eq: ["$isActive", false] }, 1, 0],
+ },
+ },
+ },
+ },
+ {
+ $project: {
+ _id: 0,
+ },
+ },
+ ];
+};
+
+const buildMonitorsByTeamIdPipeline = ({ matchStage, field, order }) => {
+ const sort = { [field]: order === "asc" ? 1 : -1 };
+
+ return [
+ { $match: matchStage },
+ { $sort: sort },
+ {
+ $project: {
+ _id: 1,
+ name: 1,
+ type: 1,
+ },
+ },
+ ];
+};
+
+const buildMonitorsAndSummaryByTeamIdPipeline = ({ matchStage }) => {
+ return [
+ { $match: matchStage },
+ {
+ $facet: {
+ summary: [
+ {
+ $group: {
+ _id: null,
+ totalMonitors: { $sum: 1 },
+ upMonitors: {
+ $sum: {
+ $cond: [{ $eq: ["$status", true] }, 1, 0],
+ },
+ },
+ downMonitors: {
+ $sum: {
+ $cond: [{ $eq: ["$status", false] }, 1, 0],
+ },
+ },
+ pausedMonitors: {
+ $sum: {
+ $cond: [{ $eq: ["$isActive", false] }, 1, 0],
+ },
+ },
+ },
+ },
+ {
+ $project: {
+ _id: 0,
+ },
+ },
+ ],
+ monitors: [
+ { $sort: { name: 1 } },
+ {
+ $project: {
+ _id: 1,
+ name: 1,
+ type: 1,
+ },
+ },
+ ],
+ },
+ },
+ {
+ $project: {
+ summary: { $arrayElemAt: ["$summary", 0] },
+ monitors: 1,
+ },
+ },
+ ];
+};
+
+const buildMonitorsWithChecksByTeamIdPipeline = ({
+ matchStage,
+ filter,
+ page,
+ rowsPerPage,
+ field,
+ order,
+ limit,
+ type,
+}) => {
+ const skip = page && rowsPerPage ? page * rowsPerPage : 0;
+ const sort = { [field]: order === "asc" ? 1 : -1 };
+ const limitStage = rowsPerPage ? [{ $limit: rowsPerPage }] : [];
+
+ // Match name
+ if (typeof filter !== "undefined" && field === "name") {
+ matchStage.$or = [
+ { name: { $regex: filter, $options: "i" } },
+ { url: { $regex: filter, $options: "i" } },
+ ];
+ }
+
+ // Match isActive
+ if (typeof filter !== "undefined" && field === "isActive") {
+ matchStage.isActive = filter === "true" ? true : false;
+ }
+
+ if (typeof filter !== "undefined" && field === "status") {
+ matchStage.status = filter === "true" ? true : false;
+ }
+
+ // Match type
+ if (typeof filter !== "undefined" && field === "type") {
+ matchStage.type = filter;
+ }
+
+ const monitorsPipeline = [
+ { $sort: sort },
+ { $skip: skip },
+ ...limitStage,
+ {
+ $project: {
+ _id: 1,
+ name: 1,
+ description: 1,
+ type: 1,
+ url: 1,
+ isActive: 1,
+ createdAt: 1,
+ updatedAt: 1,
+ uptimePercentage: 1,
+ status: 1,
+ },
+ },
+ ];
+
+ // Add checks
+ if (limit) {
+ let checksCollection = "checks";
+ if (type === "pagespeed") {
+ checksCollection = "pagespeedchecks";
+ } else if (type === "hardware") {
+ checksCollection = "hardwarechecks";
+ } else if (type === "distributed_http" || type === "distributed_test") {
+ checksCollection = "distributeduptimechecks";
+ }
+ monitorsPipeline.push({
+ $lookup: {
+ from: checksCollection,
+ let: { monitorId: "$_id" },
+ pipeline: [
+ {
+ $match: {
+ $expr: { $eq: ["$monitorId", "$$monitorId"] },
+ },
+ },
+ { $sort: { updatedAt: -1 } },
+ { $limit: limit },
+ {
+ $project: {
+ _id: 1,
+ status: 1,
+ responseTime: 1,
+ statusCode: 1,
+ createdAt: 1,
+ updatedAt: 1,
+ originalResponseTime: 1,
+ },
+ },
+ ],
+ as: "checks",
+ },
+ });
+ }
+
+ const pipeline = [
+ { $match: matchStage },
+ {
+ $facet: {
+ count: [{ $count: "monitorsCount" }],
+ monitors: monitorsPipeline,
+ },
+ },
+ {
+ $project: {
+ count: { $arrayElemAt: ["$count", 0] },
+ monitors: 1,
+ },
+ },
+ ];
+ return pipeline;
+};
+
+const buildFilteredMonitorsByTeamIdPipeline = ({
+ matchStage,
+ filter,
+ page,
+ rowsPerPage,
+ field,
+ order,
+ limit,
+ type,
+}) => {
+ const skip = page && rowsPerPage ? page * rowsPerPage : 0;
+ const sort = { [field]: order === "asc" ? 1 : -1 };
+ const limitStage = rowsPerPage ? [{ $limit: rowsPerPage }] : [];
+
+ if (typeof filter !== "undefined" && field === "name") {
+ matchStage.$or = [
+ { name: { $regex: filter, $options: "i" } },
+ { url: { $regex: filter, $options: "i" } },
+ ];
+ }
+
+ if (typeof filter !== "undefined" && field === "status") {
+ matchStage.status = filter === "true";
+ }
+
+ const pipeline = [
+ { $match: matchStage },
+ { $sort: sort },
+ { $skip: skip },
+ ...limitStage,
+ ];
+
+ // Add checks
+ if (limit) {
+ let checksCollection = "checks";
+ if (type === "pagespeed") {
+ checksCollection = "pagespeedchecks";
+ } else if (type === "hardware") {
+ checksCollection = "hardwarechecks";
+ } else if (type === "distributed_http" || type === "distributed_test") {
+ checksCollection = "distributeduptimechecks";
+ }
+ pipeline.push({
+ $lookup: {
+ from: checksCollection,
+ let: { monitorId: "$_id" },
+ pipeline: [
+ {
+ $match: {
+ $expr: { $eq: ["$monitorId", "$$monitorId"] },
+ },
+ },
+ { $sort: { createdAt: -1 } },
+ { $limit: limit },
+ ],
+ as: "checks",
+ },
+ });
+ }
+
+ return pipeline;
+};
+
+const buildGetMonitorsByTeamIdPipeline = (req) => {
+ let { limit, type, page, rowsPerPage, filter, field, order } = req.query;
+
+ limit = parseInt(limit);
+ page = parseInt(page);
+ rowsPerPage = parseInt(rowsPerPage);
+ if (field === undefined) {
+ field = "name";
+ order = "asc";
+ }
+ // Build the match stage
+ const matchStage = { teamId: ObjectId.createFromHexString(req.params.teamId) };
+ if (type !== undefined) {
+ matchStage.type = Array.isArray(type) ? { $in: type } : type;
+ }
+
+ const skip = page && rowsPerPage ? page * rowsPerPage : 0;
+ const sort = { [field]: order === "asc" ? 1 : -1 };
+ return [
+ { $match: matchStage },
+ {
+ $facet: {
+ summary: [
+ {
+ $group: {
+ _id: null,
+ totalMonitors: { $sum: 1 },
+ upMonitors: {
+ $sum: {
+ $cond: [{ $eq: ["$status", true] }, 1, 0],
+ },
+ },
+ downMonitors: {
+ $sum: {
+ $cond: [{ $eq: ["$status", false] }, 1, 0],
+ },
+ },
+ pausedMonitors: {
+ $sum: {
+ $cond: [{ $eq: ["$isActive", false] }, 1, 0],
+ },
+ },
+ },
+ },
+ {
+ $project: {
+ _id: 0,
+ },
+ },
+ ],
+ monitors: [
+ { $sort: sort },
+ {
+ $project: {
+ _id: 1,
+ name: 1,
+ },
+ },
+ ],
+ filteredMonitors: [
+ ...(filter !== undefined
+ ? [
+ {
+ $match: {
+ $or: [
+ { name: { $regex: filter, $options: "i" } },
+ { url: { $regex: filter, $options: "i" } },
+ ],
+ },
+ },
+ ]
+ : []),
+ { $sort: sort },
+ { $skip: skip },
+ ...(rowsPerPage ? [{ $limit: rowsPerPage }] : []),
+ ...(limit
+ ? [
+ {
+ $lookup: {
+ from: "checks",
+ let: { monitorId: "$_id" },
+ pipeline: [
+ {
+ $match: {
+ $expr: { $eq: ["$monitorId", "$$monitorId"] },
+ },
+ },
+ { $sort: { createdAt: -1 } },
+ ...(limit ? [{ $limit: limit }] : []),
+ ],
+ as: "standardchecks",
+ },
+ },
+ ]
+ : []),
+ ...(limit
+ ? [
+ {
+ $lookup: {
+ from: "pagespeedchecks",
+ let: { monitorId: "$_id" },
+ pipeline: [
+ {
+ $match: {
+ $expr: { $eq: ["$monitorId", "$$monitorId"] },
+ },
+ },
+ { $sort: { createdAt: -1 } },
+ ...(limit ? [{ $limit: limit }] : []),
+ ],
+ as: "pagespeedchecks",
+ },
+ },
+ ]
+ : []),
+ ...(limit
+ ? [
+ {
+ $lookup: {
+ from: "hardwarechecks",
+ let: { monitorId: "$_id" },
+ pipeline: [
+ {
+ $match: {
+ $expr: { $eq: ["$monitorId", "$$monitorId"] },
+ },
+ },
+ { $sort: { createdAt: -1 } },
+ ...(limit ? [{ $limit: limit }] : []),
+ ],
+ as: "hardwarechecks",
+ },
+ },
+ ]
+ : []),
+ ...(limit
+ ? [
+ {
+ $lookup: {
+ from: "distributeduptimechecks",
+ let: { monitorId: "$_id" },
+ pipeline: [
+ {
+ $match: {
+ $expr: { $eq: ["$monitorId", "$$monitorId"] },
+ },
+ },
+ { $sort: { createdAt: -1 } },
+ ...(limit ? [{ $limit: limit }] : []),
+ ],
+ as: "distributeduptimechecks",
+ },
+ },
+ ]
+ : []),
+
+ {
+ $addFields: {
+ checks: {
+ $switch: {
+ branches: [
+ {
+ case: { $in: ["$type", ["http", "ping", "docker", "port"]] },
+ then: "$standardchecks",
+ },
+ {
+ case: { $eq: ["$type", "pagespeed"] },
+ then: "$pagespeedchecks",
+ },
+ {
+ case: { $eq: ["$type", "hardware"] },
+ then: "$hardwarechecks",
+ },
+ {
+ case: { $eq: ["$type", "distributed_http"] },
+ then: "$distributeduptimechecks",
+ },
+ {
+ case: { $eq: ["$type", "distributed_test"] },
+ then: "$distributeduptimechecks",
+ },
+ ],
+ default: [],
+ },
+ },
+ },
+ },
+ {
+ $project: {
+ standardchecks: 0,
+ pagespeedchecks: 0,
+ hardwarechecks: 0,
+ },
+ },
+ ],
+ },
+ },
+ {
+ $project: {
+ summary: { $arrayElemAt: ["$summary", 0] },
+ filteredMonitors: 1,
+ monitors: 1,
+ },
+ },
+ ];
+};
+
+const buildDePINDetailsByDateRange = (monitor, dates, dateString) => {
+ return [
+ {
+ $match: {
+ monitorId: monitor._id,
+ updatedAt: { $gte: dates.start, $lte: dates.end },
+ },
+ },
+ {
+ $project: {
+ _id: 0,
+ city: 1,
+ updatedAt: 1,
+ "location.lat": 1,
+ "location.lng": 1,
+ responseTime: 1,
+ },
+ },
+ {
+ $facet: {
+ groupedMapChecks: [
+ {
+ $group: {
+ _id: {
+ city: "$city",
+ lat: "$location.lat",
+ lng: "$location.lng",
+ },
+
+ avgResponseTime: {
+ $avg: "$responseTime",
+ },
+ },
+ },
+ ],
+ groupedChecks: [
+ {
+ $group: {
+ _id: {
+ date: {
+ $dateToString: {
+ format: dateString,
+ date: "$updatedAt",
+ },
+ },
+ },
+ avgResponseTime: {
+ $avg: "$responseTime",
+ },
+ },
+ },
+ {
+ $sort: {
+ "_id.date": 1,
+ },
+ },
+ ],
+ },
+ },
+ {
+ $project: {
+ groupedMapChecks: "$groupedMapChecks",
+ groupedChecks: "$groupedChecks",
+ },
+ },
+ ];
+};
+
+const buildDePINLatestChecks = (monitor) => {
+ return [
+ {
+ $match: {
+ monitorId: monitor._id,
+ },
+ },
+ {
+ $sort: { updatedAt: -1 },
+ },
+ {
+ $limit: 5,
+ },
+ {
+ $project: {
+ responseTime: 1,
+ city: 1,
+ countryCode: 1,
+ uptBurnt: {
+ $toString: {
+ $ifNull: ["$uptBurnt", 0],
+ },
+ },
+ },
+ },
+ ];
+};
+
+export {
+ buildUptimeDetailsPipeline,
+ buildHardwareDetailsPipeline,
+ buildMonitorStatsPipeline,
+ buildGetMonitorsByTeamIdPipeline,
+ buildMonitorSummaryByTeamIdPipeline,
+ buildMonitorsByTeamIdPipeline,
+ buildMonitorsAndSummaryByTeamIdPipeline,
+ buildMonitorsWithChecksByTeamIdPipeline,
+ buildFilteredMonitorsByTeamIdPipeline,
+ buildDePINDetailsByDateRange,
+ buildDePINLatestChecks,
+};
diff --git a/Server/db/mongo/modules/notificationModule.js b/server/db/mongo/modules/notificationModule.js
old mode 100644
new mode 100755
similarity index 100%
rename from Server/db/mongo/modules/notificationModule.js
rename to server/db/mongo/modules/notificationModule.js
diff --git a/Server/db/mongo/modules/pageSpeedCheckModule.js b/server/db/mongo/modules/pageSpeedCheckModule.js
old mode 100644
new mode 100755
similarity index 78%
rename from Server/db/mongo/modules/pageSpeedCheckModule.js
rename to server/db/mongo/modules/pageSpeedCheckModule.js
index 427893a96..f634fae27
--- a/Server/db/mongo/modules/pageSpeedCheckModule.js
+++ b/server/db/mongo/modules/pageSpeedCheckModule.js
@@ -24,6 +24,16 @@ const createPageSpeedCheck = async (pageSpeedCheckData) => {
throw error;
}
};
+const createPageSpeedChecks = async (pageSpeedChecks) => {
+ try {
+ await PageSpeedCheck.insertMany(pageSpeedChecks);
+ return true;
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "createPageSpeedCheck";
+ throw error;
+ }
+};
/**
* Delete all PageSpeed checks for a monitor
@@ -44,4 +54,4 @@ const deletePageSpeedChecksByMonitorId = async (monitorId) => {
}
};
-export { createPageSpeedCheck, deletePageSpeedChecksByMonitorId };
+export { createPageSpeedCheck, createPageSpeedChecks, deletePageSpeedChecksByMonitorId };
diff --git a/Server/db/mongo/modules/recoveryModule.js b/server/db/mongo/modules/recoveryModule.js
old mode 100644
new mode 100755
similarity index 82%
rename from Server/db/mongo/modules/recoveryModule.js
rename to server/db/mongo/modules/recoveryModule.js
index 40dd66c56..3b39e847c
--- a/Server/db/mongo/modules/recoveryModule.js
+++ b/server/db/mongo/modules/recoveryModule.js
@@ -1,7 +1,8 @@
import UserModel from "../../models/User.js";
import RecoveryToken from "../../models/RecoveryToken.js";
import crypto from "crypto";
-import { errorMessages } from "../../../utils/messages.js";
+import serviceRegistry from "../../../service/serviceRegistry.js";
+import StringService from "../../../service/stringService.js";
const SERVICE_NAME = "recoveryModule";
@@ -31,6 +32,7 @@ const requestRecoveryToken = async (req, res) => {
};
const validateRecoveryToken = async (req, res) => {
+ const stringService = serviceRegistry.get(StringService.SERVICE_NAME);
try {
const candidateToken = req.body.recoveryToken;
const recoveryToken = await RecoveryToken.findOne({
@@ -39,7 +41,7 @@ const validateRecoveryToken = async (req, res) => {
if (recoveryToken !== null) {
return recoveryToken;
} else {
- throw new Error(errorMessages.DB_TOKEN_NOT_FOUND);
+ throw new Error(stringService.dbTokenNotFound);
}
} catch (error) {
error.service = SERVICE_NAME;
@@ -49,6 +51,7 @@ const validateRecoveryToken = async (req, res) => {
};
const resetPassword = async (req, res) => {
+ const stringService = serviceRegistry.get(StringService.SERVICE_NAME);
try {
const newPassword = req.body.password;
@@ -57,12 +60,12 @@ const resetPassword = async (req, res) => {
const user = await UserModel.findOne({ email: recoveryToken.email });
if (user === null) {
- throw new Error(errorMessages.DB_USER_NOT_FOUND);
+ throw new Error(stringService.dbUserNotFound);
}
const match = await user.comparePassword(newPassword);
if (match === true) {
- throw new Error(errorMessages.DB_RESET_PASSWORD_BAD_MATCH);
+ throw new Error(stringService.dbResetPasswordBadMatch);
}
user.password = newPassword;
diff --git a/Server/db/mongo/modules/settingsModule.js b/server/db/mongo/modules/settingsModule.js
old mode 100644
new mode 100755
similarity index 55%
rename from Server/db/mongo/modules/settingsModule.js
rename to server/db/mongo/modules/settingsModule.js
index 3b5f68e19..d3568ad32
--- a/Server/db/mongo/modules/settingsModule.js
+++ b/server/db/mongo/modules/settingsModule.js
@@ -14,11 +14,22 @@ const getAppSettings = async () => {
const updateAppSettings = async (newSettings) => {
try {
- const settings = await AppSettings.findOneAndUpdate(
- {},
- { $set: newSettings },
- { new: true }
- );
+ const update = { $set: { ...newSettings } };
+
+ if (newSettings.pagespeedApiKey === "") {
+ update.$unset = { pagespeedApiKey: "" };
+ delete update.$set.pagespeedApiKey;
+ }
+
+ if (newSettings.systemEmailPassword === "") {
+ update.$unset = { systemEmailPassword: "" };
+ delete update.$set.systemEmailPassword;
+ }
+
+ const settings = await AppSettings.findOneAndUpdate({}, update, {
+ new: true,
+ upsert: true,
+ });
return settings;
} catch (error) {
error.service = SERVICE_NAME;
diff --git a/server/db/mongo/modules/statusPageModule.js b/server/db/mongo/modules/statusPageModule.js
new file mode 100755
index 000000000..e5c88eecb
--- /dev/null
+++ b/server/db/mongo/modules/statusPageModule.js
@@ -0,0 +1,312 @@
+import StatusPage from "../../models/StatusPage.js";
+import Monitor from "../../models/Monitor.js";
+import { NormalizeData } from "../../../utils/dataUtils.js";
+import ServiceRegistry from "../../../service/serviceRegistry.js";
+import StringService from "../../../service/stringService.js";
+
+const SERVICE_NAME = "statusPageModule";
+
+const createStatusPage = async (statusPageData, image) => {
+ const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
+
+ try {
+ const statusPage = new StatusPage({ ...statusPageData });
+ if (image) {
+ statusPage.logo = {
+ data: image.buffer,
+ contentType: image.mimetype,
+ };
+ }
+ await statusPage.save();
+ return statusPage;
+ } catch (error) {
+ if (error?.code === 11000) {
+ // Handle duplicate URL errors
+ error.status = 400;
+ error.message = stringService.statusPageUrlNotUnique;
+ }
+ error.service = SERVICE_NAME;
+ error.method = "createStatusPage";
+ throw error;
+ }
+};
+
+const updateStatusPage = async (statusPageData, image) => {
+ try {
+ if (image) {
+ statusPageData.logo = {
+ data: image.buffer,
+ contentType: image.mimetype,
+ };
+ }else{
+ statusPageData.logo = null;
+ }
+
+ if (statusPageData.deleteSubmonitors === "true") {
+ statusPageData.subMonitors = [];
+ }
+ const statusPage = await StatusPage.findOneAndUpdate(
+ { url: statusPageData.url },
+ statusPageData,
+ {
+ new: true,
+ }
+ );
+
+ return statusPage;
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "updateStatusPage";
+ throw error;
+ }
+};
+
+const getDistributedStatusPageByUrl = async ({ url, daysToShow = 30 }) => {
+ const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
+ try {
+ const statusPage = await StatusPage.findOne({ url }).lean();
+
+ if (!statusPage) {
+ const error = new Error(stringService.statusPageNotFound);
+ error.status = 404;
+ throw error;
+ }
+
+ // No sub monitors, return status page
+ if (statusPage.subMonitors.length === 0) {
+ return statusPage;
+ }
+ // Sub monitors, return status page with sub monitors
+ const daysAgo = new Date();
+ daysAgo.setDate(daysAgo.getDate() - daysToShow);
+
+ const subMonitors = await Monitor.aggregate([
+ { $match: { _id: { $in: statusPage.subMonitors } } },
+ {
+ $addFields: {
+ orderIndex: { $indexOfArray: [statusPage.subMonitors, "$_id"] },
+ },
+ },
+
+ // Return 30 days of checks by default
+ {
+ $lookup: {
+ from: "checks",
+ let: { monitorId: "$_id" },
+ pipeline: [
+ {
+ $match: {
+ $expr: {
+ $and: [
+ { $eq: ["$monitorId", "$$monitorId"] },
+ { $gte: ["$updatedAt", daysAgo] },
+ ],
+ },
+ },
+ },
+ {
+ $group: {
+ _id: {
+ $dateToString: { format: "%Y-%m-%d", date: "$updatedAt" },
+ },
+ responseTime: {
+ $avg: "$responseTime",
+ },
+ trueCount: {
+ $sum: {
+ $cond: [{ $eq: ["$status", true] }, 1, 0],
+ },
+ },
+ totalCount: {
+ $sum: 1,
+ },
+ },
+ },
+ {
+ $project: {
+ _id: 1,
+ responseTime: 1,
+ upPercentage: {
+ $cond: [
+ { $eq: ["$totalCount", 0] },
+ 0,
+ { $multiply: [{ $divide: ["$trueCount", "$totalCount"] }, 100] },
+ ],
+ },
+ },
+ },
+ {
+ $sort: { _id: -1 },
+ },
+ ],
+ as: "checks",
+ },
+ },
+ { $sort: { orderIndex: 1 } },
+ { $project: { orderIndex: 0 } },
+ ]);
+
+ const normalizedSubMonitors = subMonitors.map((monitor) => {
+ return {
+ ...monitor,
+ checks: NormalizeData(monitor.checks, 10, 100),
+ };
+ });
+ return { ...statusPage, subMonitors: normalizedSubMonitors };
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "getDistributedStatusPageByUrl";
+ throw error;
+ }
+};
+
+const getStatusPageByUrl = async (url, type) => {
+ // TODO This is deprecated, can remove and have controller call getStatusPage
+ try {
+ return getStatusPage(url);
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "getStatusPageByUrl";
+ throw error;
+ }
+};
+
+const getStatusPagesByTeamId = async (teamId) => {
+ try {
+ const statusPages = await StatusPage.find({ teamId });
+ return statusPages;
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "getStatusPagesByTeamId";
+ throw error;
+ }
+};
+
+const getStatusPage = async (url) => {
+ const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
+
+ try {
+ const statusPageQuery = await StatusPage.aggregate([
+ { $match: { url: url } },
+ {
+ $set: {
+ originalMonitors: "$monitors",
+ },
+ },
+ {
+ $lookup: {
+ from: "monitors",
+ localField: "monitors",
+ foreignField: "_id",
+ as: "monitors",
+ },
+ },
+ {
+ $unwind: "$monitors",
+ },
+ {
+ $lookup: {
+ from: "checks",
+ let: { monitorId: "$monitors._id" },
+ pipeline: [
+ {
+ $match: {
+ $expr: { $eq: ["$monitorId", "$$monitorId"] },
+ },
+ },
+ { $sort: { createdAt: -1 } },
+ { $limit: 25 },
+ ],
+ as: "monitors.checks",
+ },
+ },
+ {
+ $addFields: {
+ "monitors.orderIndex": {
+ $indexOfArray: ["$originalMonitors", "$monitors._id"],
+ },
+ },
+ },
+ {
+ $group: {
+ _id: "$_id",
+ statusPage: { $first: "$$ROOT" },
+ monitors: { $push: "$monitors" },
+ },
+ },
+ {
+ $project: {
+ statusPage: {
+ _id: 1,
+ color: 1,
+ companyName: 1,
+ isPublished: 1,
+ logo: 1,
+ originalMonitors: 1,
+ showCharts: 1,
+ showUptimePercentage: 1,
+ timezone: 1,
+ url: 1,
+ },
+ monitors: {
+ $sortArray: {
+ input: "$monitors",
+ sortBy: { orderIndex: 1 },
+ },
+ },
+ },
+ },
+ ]);
+ if (!statusPageQuery.length) {
+ const error = new Error(stringService.statusPageNotFound);
+ error.status = 404;
+ throw error;
+ }
+
+ const { statusPage, monitors } = statusPageQuery[0];
+
+ const normalizedMonitors = monitors.map((monitor) => {
+ return {
+ ...monitor,
+ checks: NormalizeData(monitor.checks, 10, 100),
+ };
+ });
+
+ return { statusPage, monitors: normalizedMonitors };
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "getStatusPageByUrl";
+ throw error;
+ }
+};
+
+const deleteStatusPage = async (url) => {
+ try {
+ await StatusPage.deleteOne({ url });
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "deleteStatusPage";
+ throw error;
+ }
+};
+
+const deleteStatusPagesByMonitorId = async (monitorId) => {
+ try {
+ await StatusPage.deleteMany({ monitors: { $in: [monitorId] } });
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "deleteStatusPageByMonitorId";
+ throw error;
+ }
+};
+
+export {
+ createStatusPage,
+ updateStatusPage,
+ getStatusPagesByTeamId,
+ getStatusPage,
+ getStatusPageByUrl,
+ getDistributedStatusPageByUrl,
+ deleteStatusPage,
+ deleteStatusPagesByMonitorId,
+};
diff --git a/Server/db/mongo/modules/userModule.js b/server/db/mongo/modules/userModule.js
old mode 100644
new mode 100755
similarity index 91%
rename from Server/db/mongo/modules/userModule.js
rename to server/db/mongo/modules/userModule.js
index 5b951ff64..4069be8c6
--- a/Server/db/mongo/modules/userModule.js
+++ b/server/db/mongo/modules/userModule.js
@@ -1,10 +1,11 @@
import UserModel from "../../models/User.js";
import TeamModel from "../../models/Team.js";
-import { errorMessages } from "../../../utils/messages.js";
import { GenerateAvatarImage } from "../../../utils/imageProcessing.js";
const DUPLICATE_KEY_CODE = 11000; // MongoDB error code for duplicate key
import { ParseBoolean } from "../../../utils/utils.js";
+import ServiceRegistry from "../../../service/serviceRegistry.js";
+import StringService from "../../../service/stringService.js";
const SERVICE_NAME = "userModule";
/**
@@ -20,6 +21,7 @@ const insertUser = async (
imageFile,
generateAvatarImage = GenerateAvatarImage
) => {
+ const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
if (imageFile) {
// 1. Save the full size image
@@ -50,7 +52,7 @@ const insertUser = async (
.select("-profileImage"); // .select() doesn't work with create, need to save then find
} catch (error) {
if (error.code === DUPLICATE_KEY_CODE) {
- error.message = errorMessages.DB_USER_EXISTS;
+ error.message = stringService.dbUserExists;
}
error.service = SERVICE_NAME;
error.method = "insertUser";
@@ -70,12 +72,14 @@ const insertUser = async (
* @throws {Error}
*/
const getUserByEmail = async (email) => {
+ const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
+
try {
// Need the password to be able to compare, removed .select()
// We can strip the hash before returning the user
const user = await UserModel.findOne({ email: email }).select("-profileImage");
if (!user) {
- throw new Error(errorMessages.DB_USER_NOT_FOUND);
+ throw new Error(stringService.dbUserNotFound);
}
return user;
} catch (error) {
@@ -150,10 +154,12 @@ const updateUser = async (
* @throws {Error}
*/
const deleteUser = async (userId) => {
+ const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
+
try {
const deletedUser = await UserModel.findByIdAndDelete(userId);
if (!deletedUser) {
- throw new Error(errorMessages.DB_USER_NOT_FOUND);
+ throw new Error(stringService.dbUserNotFound);
}
return deletedUser;
} catch (error) {
diff --git a/server/db/mongo/utils/seedDb.js b/server/db/mongo/utils/seedDb.js
new file mode 100755
index 000000000..d8317c89b
--- /dev/null
+++ b/server/db/mongo/utils/seedDb.js
@@ -0,0 +1,177 @@
+import Monitor from "../../models/Monitor.js";
+import Check from "../../models/Check.js";
+import DistributedUptimeCheck from "../../models/DistributedUptimeCheck.js";
+import logger from "../../../utils/logger.js";
+
+const generateRandomUrl = () => {
+ const domains = ["example.com", "test.org", "demo.net", "sample.io", "mock.dev"];
+ const paths = ["api", "status", "health", "ping", "check"];
+ return `https://${domains[Math.floor(Math.random() * domains.length)]}/${paths[Math.floor(Math.random() * paths.length)]}`;
+};
+
+const generateChecks = (monitorId, teamId, count) => {
+ const checks = [];
+ const endTime = new Date(Date.now() - 10 * 60 * 1000); // 10 minutes ago
+ const startTime = new Date(endTime - count * 60 * 1000); // count minutes before endTime
+
+ for (let i = 0; i < count; i++) {
+ const timestamp = new Date(startTime.getTime() + i * 60 * 1000);
+ const status = Math.random() > 0.05; // 95% chance of being up
+
+ checks.push({
+ monitorId,
+ teamId,
+ status,
+ responseTime: Math.floor(Math.random() * 1000), // Random response time between 0-1000ms
+ createdAt: timestamp,
+ updatedAt: timestamp,
+ });
+ }
+
+ return checks;
+};
+
+const seedDb = async (userId, teamId) => {
+ try {
+ logger.info({
+ message: "Deleting all monitors and checks",
+ service: "seedDb",
+ method: "seedDb",
+ });
+ await Monitor.deleteMany({});
+ await Check.deleteMany({});
+ logger.info({
+ message: "Adding monitors",
+ service: "DB",
+ method: "seedDb",
+ });
+ for (let i = 0; i < 300; i++) {
+ const monitor = await Monitor.create({
+ name: `Monitor ${i}`,
+ url: generateRandomUrl(),
+ type: "http",
+ userId,
+ teamId,
+ interval: 60000,
+ active: false,
+ });
+ logger.info({
+ message: `Adding monitor and checks for monitor ${i}`,
+ service: "DB",
+ method: "seedDb",
+ });
+ const checks = generateChecks(monitor._id, teamId, 10000);
+ await Check.insertMany(checks);
+ }
+ } catch (error) {
+ logger.error({
+ message: "Error seeding DB",
+ service: "DB",
+ method: "seedDb",
+ stack: error.stack,
+ });
+ }
+};
+
+const generateDistributedChecks = (monitorId, teamId, count = 2880) => {
+ const checks = [];
+ const endTime = new Date();
+ const startTime = new Date(endTime - 48 * 60 * 60 * 1000);
+
+ // Sample locations for variety
+ const locations = [
+ {
+ city: "New York",
+ countryCode: "US",
+ continent: "NA",
+ location: { lat: 40.7128, lng: -74.006 },
+ },
+ {
+ city: "London",
+ countryCode: "GB",
+ continent: "EU",
+ location: { lat: 51.5074, lng: -0.1278 },
+ },
+ {
+ city: "Singapore",
+ countryCode: "SG",
+ continent: "AS",
+ location: { lat: 1.3521, lng: 103.8198 },
+ },
+ ];
+
+ for (let i = 0; i < count; i++) {
+ const timestamp = new Date(startTime.getTime() + i * 60 * 1000);
+ const location = locations[Math.floor(Math.random() * locations.length)];
+ const status = Math.random() > 0.05; // 95% success rate
+
+ checks.push({
+ monitorId,
+ teamId,
+ status,
+ responseTime: Math.floor(Math.random() * 1000), // Random response time between 0-1000ms
+ first_byte_took: Math.floor(Math.random() * 300000), // 0-300ms
+ body_read_took: Math.floor(Math.random() * 100000), // 0-100ms
+ dns_took: Math.floor(Math.random() * 100000), // 0-100ms
+ conn_took: Math.floor(Math.random() * 200000), // 0-200ms
+ connect_took: Math.floor(Math.random() * 150000), // 0-150ms
+ tls_took: Math.floor(Math.random() * 200000), // 0-200ms
+ location: location.location,
+ continent: location.continent,
+ countryCode: location.countryCode,
+ city: location.city,
+ uptBurnt: "0.01", // Will be converted to Decimal128 by the schema
+ createdAt: timestamp,
+ updatedAt: timestamp,
+ });
+ }
+
+ return checks;
+};
+
+export const seedDistributedTest = async (userId, teamId) => {
+ try {
+ logger.info({
+ message: "Deleting all test monitors and checks",
+ service: "DB",
+ method: "seedDistributedTest",
+ });
+
+ const testMonitors = await Monitor.find({
+ type: "distributed_test",
+ });
+
+ testMonitors.forEach(async (monitor) => {
+ await DistributedUptimeCheck.deleteMany({ monitorId: monitor._id });
+ await Monitor.deleteOne({ _id: monitor._id });
+ });
+
+ logger.info({
+ message: "Adding test monitors and checks",
+ service: "DB",
+ method: "seedDistributedTest",
+ });
+ const monitor = await Monitor.create({
+ name: "Distributed Test",
+ url: "https://distributed-test.com",
+ type: "distributed_test",
+ userId,
+ teamId,
+ interval: 60000,
+ active: false,
+ });
+ const checks = generateDistributedChecks(monitor._id, teamId, 2800);
+ await DistributedUptimeCheck.insertMany(checks);
+ return monitor;
+ } catch (error) {
+ logger.error({
+ message: "Error seeding distributed test",
+ service: "DB",
+ method: "seedDistributedTest",
+ stack: error.stack,
+ });
+ throw error;
+ }
+};
+
+export default seedDb;
diff --git a/Server/eslint.config.js b/server/eslint.config.js
old mode 100644
new mode 100755
similarity index 100%
rename from Server/eslint.config.js
rename to server/eslint.config.js
diff --git a/Server/index.js b/server/index.js
old mode 100644
new mode 100755
similarity index 63%
rename from Server/index.js
rename to server/index.js
index 7a4129bc9..f299b32e9
--- a/Server/index.js
+++ b/server/index.js
@@ -5,6 +5,7 @@ import swaggerUi from "swagger-ui-express";
import express from "express";
import helmet from "helmet";
import cors from "cors";
+import compression from "compression";
import logger from "./utils/logger.js";
import { verifyJWT } from "./middleware/verifyJWT.js";
import { handleErrors } from "./middleware/handleErrors.js";
@@ -38,6 +39,12 @@ import QueueController from "./controllers/queueController.js";
import DistributedUptimeRoutes from "./routes/distributedUptimeRoute.js";
import DistributedUptimeController from "./controllers/distributedUptimeController.js";
+import NotificationRoutes from "./routes/notificationRoute.js";
+import NotificationController from "./controllers/notificationController.js";
+
+import DiagnosticRoutes from "./routes/diagnosticRoute.js";
+import DiagnosticController from "./controllers/diagnosticController.js";
+
//JobQueue service and dependencies
import JobQueue from "./service/jobQueue.js";
import { Queue, Worker } from "bullmq";
@@ -49,7 +56,6 @@ import ping from "ping";
import http from "http";
import Docker from "dockerode";
import net from "net";
-import ngrok from "ngrok";
// Email service and dependencies
import EmailService from "./service/emailService.js";
import nodemailer from "nodemailer";
@@ -67,12 +73,21 @@ import StatusService from "./service/statusService.js";
// Notification Service and dependencies
import NotificationService from "./service/notificationService.js";
+// Buffer Service and dependencies
+import BufferService from "./service/bufferService.js";
+
// Service Registry
import ServiceRegistry from "./service/serviceRegistry.js";
import MongoDB from "./db/mongo/MongoDB.js";
+// Redis Service and dependencies
import IORedis from "ioredis";
+import RedisService from "./service/redisService.js";
+
+import TranslationService from "./service/translationService.js";
+import languageMiddleware from "./middleware/languageMiddleware.js";
+import StringService from "./service/stringService.js";
const SERVICE_NAME = "Server";
const SHUTDOWN_TIMEOUT = 1000;
@@ -84,9 +99,6 @@ const openApiSpec = JSON.parse(
);
let server;
-let ngrokUrl;
-
-const PORT = 5000;
const shutdown = async () => {
if (isShuttingDown) {
@@ -101,23 +113,16 @@ const shutdown = async () => {
method: "shutdown",
});
// flush Redis
- const settings =
- ServiceRegistry.get(SettingsService.SERVICE_NAME).getSettings() || {};
+ const redisService = ServiceRegistry.get(RedisService.SERVICE_NAME);
+ await redisService.flushall();
- const { redisHost = "127.0.0.1", redisPort = 6379 } = settings;
- const redis = new IORedis({
- host: redisHost,
- port: redisPort,
- });
- logger.info({ message: "Flushing Redis" });
- await redis.flushall();
- logger.info({ message: "Redis flushed" });
process.exit(1);
}, SHUTDOWN_TIMEOUT);
try {
server.close();
await ServiceRegistry.get(JobQueue.SERVICE_NAME).obliterate();
await ServiceRegistry.get(MongoDB.SERVICE_NAME).disconnect();
+ await ServiceRegistry.get(RedisService.SERVICE_NAME).flushall();
logger.info({ message: "Graceful shutdown complete" });
process.exit(0);
} catch (error) {
@@ -132,37 +137,32 @@ const shutdown = async () => {
// Need to wrap server setup in a function to handle async nature of JobQueue
const startApp = async () => {
const app = express();
- if (process.env.NODE_ENV === "development") {
- try {
- ngrokUrl = await ngrok.connect({
- proto: "http",
- addr: PORT,
- authtoken: process.env.NGROK_AUTH_TOKEN,
- api_addr: false,
- });
- process.env.NGROK_URL = ngrokUrl;
- logger.info({
- message: `ngrok url: ${ngrokUrl}`,
- service: SERVICE_NAME,
- method: "startApp",
- });
- } catch (error) {
- logger.error({
- message: `Error connecting to ngrok`,
- service: SERVICE_NAME,
- method: "startApp",
- stack: error.stack,
- });
- }
- }
-
- // Create DB
- const db = new MongoDB();
- await db.connect();
+ // Create and Register Primary services
+ const translationService = new TranslationService(logger);
+ const stringService = new StringService(translationService);
+ ServiceRegistry.register(StringService.SERVICE_NAME, stringService);
// Create services
const settingsService = new SettingsService(AppSettings);
- await settingsService.loadSettings();
+ const appSettings = settingsService.loadSettings();
+
+ // Create DB
+ const db = new MongoDB({ appSettings });
+ await db.connect();
+
+ // Set allowed origin
+ const allowedOrigin = appSettings.clientHost;
+
+ const networkService = new NetworkService(
+ axios,
+ ping,
+ logger,
+ http,
+ Docker,
+ net,
+ stringService,
+ settingsService
+ );
const emailService = new EmailService(
settingsService,
fs,
@@ -172,20 +172,34 @@ const startApp = async () => {
nodemailer,
logger
);
- const networkService = new NetworkService(axios, ping, logger, http, Docker, net);
- const statusService = new StatusService(db, logger);
- const notificationService = new NotificationService(emailService, db, logger);
+ const bufferService = new BufferService({ db, logger });
+ const statusService = new StatusService({ db, logger, buffer: bufferService });
+ const notificationService = new NotificationService(
+ emailService,
+ db,
+ logger,
+ networkService,
+ stringService
+ );
- const jobQueue = new JobQueue(
+ const redisService = await RedisService.createInstance({
+ logger,
+ IORedis,
+ SettingsService: settingsService,
+ });
+
+ const jobQueue = new JobQueue({
db,
statusService,
networkService,
notificationService,
settingsService,
+ stringService,
logger,
Queue,
- Worker
- );
+ Worker,
+ redisService,
+ });
// Register services
ServiceRegistry.register(JobQueue.SERVICE_NAME, jobQueue);
@@ -193,10 +207,17 @@ const startApp = async () => {
ServiceRegistry.register(SettingsService.SERVICE_NAME, settingsService);
ServiceRegistry.register(EmailService.SERVICE_NAME, emailService);
ServiceRegistry.register(NetworkService.SERVICE_NAME, networkService);
+ ServiceRegistry.register(BufferService.SERVICE_NAME, bufferService);
ServiceRegistry.register(StatusService.SERVICE_NAME, statusService);
ServiceRegistry.register(NotificationService.SERVICE_NAME, notificationService);
- server = app.listen(PORT, () => {
- logger.info({ message: `server started on port:${PORT}` });
+ ServiceRegistry.register(TranslationService.SERVICE_NAME, translationService);
+ ServiceRegistry.register(RedisService.SERVICE_NAME, redisService);
+
+ await translationService.initialize();
+
+ const port = appSettings.port || 52345;
+ server = app.listen(port, () => {
+ logger.info({ message: `Server started on port:${port}` });
});
process.on("SIGUSR2", shutdown);
@@ -208,43 +229,69 @@ const startApp = async () => {
ServiceRegistry.get(MongoDB.SERVICE_NAME),
ServiceRegistry.get(SettingsService.SERVICE_NAME),
ServiceRegistry.get(EmailService.SERVICE_NAME),
- ServiceRegistry.get(JobQueue.SERVICE_NAME)
+ ServiceRegistry.get(JobQueue.SERVICE_NAME),
+ ServiceRegistry.get(StringService.SERVICE_NAME)
);
const monitorController = new MonitorController(
ServiceRegistry.get(MongoDB.SERVICE_NAME),
ServiceRegistry.get(SettingsService.SERVICE_NAME),
- ServiceRegistry.get(JobQueue.SERVICE_NAME)
+ ServiceRegistry.get(JobQueue.SERVICE_NAME),
+ ServiceRegistry.get(StringService.SERVICE_NAME),
+ ServiceRegistry.get(EmailService.SERVICE_NAME)
);
const settingsController = new SettingsController(
ServiceRegistry.get(MongoDB.SERVICE_NAME),
- ServiceRegistry.get(SettingsService.SERVICE_NAME)
+ ServiceRegistry.get(SettingsService.SERVICE_NAME),
+ ServiceRegistry.get(StringService.SERVICE_NAME)
);
const checkController = new CheckController(
ServiceRegistry.get(MongoDB.SERVICE_NAME),
- ServiceRegistry.get(SettingsService.SERVICE_NAME)
+ ServiceRegistry.get(SettingsService.SERVICE_NAME),
+ ServiceRegistry.get(StringService.SERVICE_NAME)
);
const inviteController = new InviteController(
ServiceRegistry.get(MongoDB.SERVICE_NAME),
ServiceRegistry.get(SettingsService.SERVICE_NAME),
- ServiceRegistry.get(EmailService.SERVICE_NAME)
+ ServiceRegistry.get(EmailService.SERVICE_NAME),
+ ServiceRegistry.get(StringService.SERVICE_NAME)
);
const maintenanceWindowController = new MaintenanceWindowController(
ServiceRegistry.get(MongoDB.SERVICE_NAME),
- ServiceRegistry.get(SettingsService.SERVICE_NAME)
+ ServiceRegistry.get(SettingsService.SERVICE_NAME),
+ ServiceRegistry.get(StringService.SERVICE_NAME)
);
- const queueController = new QueueController(ServiceRegistry.get(JobQueue.SERVICE_NAME));
+ const queueController = new QueueController(
+ ServiceRegistry.get(JobQueue.SERVICE_NAME),
+ ServiceRegistry.get(StringService.SERVICE_NAME)
+ );
const statusPageController = new StatusPageController(
- ServiceRegistry.get(MongoDB.SERVICE_NAME)
+ ServiceRegistry.get(MongoDB.SERVICE_NAME),
+ ServiceRegistry.get(StringService.SERVICE_NAME)
);
- const distributedUptimeController = new DistributedUptimeController();
+ const notificationController = new NotificationController(
+ ServiceRegistry.get(NotificationService.SERVICE_NAME),
+ ServiceRegistry.get(StringService.SERVICE_NAME),
+ ServiceRegistry.get(StatusService.SERVICE_NAME)
+ );
+
+ const distributedUptimeController = new DistributedUptimeController({
+ db: ServiceRegistry.get(MongoDB.SERVICE_NAME),
+ http,
+ statusService: ServiceRegistry.get(StatusService.SERVICE_NAME),
+ logger,
+ });
+
+ const diagnosticController = new DiagnosticController(
+ ServiceRegistry.get(MongoDB.SERVICE_NAME)
+ );
//Create routes
const authRoutes = new AuthRoutes(authController);
@@ -260,21 +307,40 @@ const startApp = async () => {
const distributedUptimeRoutes = new DistributedUptimeRoutes(
distributedUptimeController
);
+ const notificationRoutes = new NotificationRoutes(notificationController);
+ const diagnosticRoutes = new DiagnosticRoutes(diagnosticController);
// Init job queue
await jobQueue.initJobQueue();
// Middleware
+ app.use(responseHandler);
app.use(
- cors()
- //We will add configuration later
+ cors({
+ origin: allowedOrigin,
+ methods: "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS",
+ allowedHeaders: "*",
+ credentials: true,
+ })
);
app.use(express.json());
app.use(helmet());
+ app.use(
+ compression({
+ level: 6,
+ threshold: 1024,
+ filter: (req, res) => {
+ if (req.headers["x-no-compression"]) {
+ return false;
+ }
+ return compression.filter(req, res);
+ },
+ })
+ );
+
+ app.use(languageMiddleware(stringService, translationService, settingsService));
// Swagger UI
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(openApiSpec));
//routes
- app.use(responseHandler);
-
app.use("/api/v1/auth", authRoutes.getRouter());
app.use("/api/v1/settings", verifyJWT, settingsRoutes.getRouter());
app.use("/api/v1/invite", inviteRoutes.getRouter());
@@ -284,6 +350,13 @@ const startApp = async () => {
app.use("/api/v1/queue", verifyJWT, queueRoutes.getRouter());
app.use("/api/v1/distributed-uptime", distributedUptimeRoutes.getRouter());
app.use("/api/v1/status-page", statusPageRoutes.getRouter());
+ app.use("/api/v1/notifications", verifyJWT, notificationRoutes.getRouter());
+ app.use("/api/v1/diagnostic", verifyJWT, diagnosticRoutes.getRouter());
+ app.use("/api/v1/health", (req, res) => {
+ res.json({
+ status: "OK",
+ });
+ });
app.use(handleErrors);
};
diff --git a/server/locales/en.json b/server/locales/en.json
new file mode 100755
index 000000000..a693c6eef
--- /dev/null
+++ b/server/locales/en.json
@@ -0,0 +1,165 @@
+{
+ "dontHaveAccount": "Don't have account",
+ "email": "E-mail",
+ "forgotPassword": "Forgot Password",
+ "password": "password",
+ "signUp": "Sign up",
+ "submit": "Submit",
+ "title": "Title",
+ "continue": "Continue",
+ "enterEmail": "Enter your email",
+ "authLoginTitle": "Log In",
+ "authLoginEnterPassword": "Enter your password",
+ "commonPassword": "Password",
+ "commonBack": "Back",
+ "authForgotPasswordTitle": "Forgot password?",
+ "authForgotPasswordResetPassword": "Reset password",
+ "createPassword": "Create your password",
+ "createAPassword": "Create a password",
+ "authRegisterAlreadyHaveAccount": "Already have an account?",
+ "commonAppName": "BlueWave Uptime",
+ "authLoginEnterEmail": "Enter your email",
+ "authRegisterTitle": "Create an account",
+ "authRegisterStepOneTitle": "Create your account",
+ "authRegisterStepOneDescription": "Enter your details to get started",
+ "authRegisterStepTwoTitle": "Set up your profile",
+ "authRegisterStepTwoDescription": "Tell us more about yourself",
+ "authRegisterStepThreeTitle": "Almost done!",
+ "authRegisterStepThreeDescription": "Review your information",
+ "authForgotPasswordDescription": "No worries, we'll send you reset instructions.",
+ "authForgotPasswordSendInstructions": "Send instructions",
+ "authForgotPasswordBackTo": "Back to",
+ "authCheckEmailTitle": "Check your email",
+ "authCheckEmailDescription": "We sent a password reset link to {{email}}",
+ "authCheckEmailResendEmail": "Resend email",
+ "authCheckEmailBackTo": "Back to",
+ "goBackTo": "Go back to",
+ "authCheckEmailDidntReceiveEmail": "Didn't receive the email?",
+ "authCheckEmailClickToResend": "Click to resend",
+ "authSetNewPasswordTitle": "Set new password",
+ "authSetNewPasswordDescription": "Your new password must be different from previously used passwords.",
+ "authSetNewPasswordNewPassword": "New password",
+ "authSetNewPasswordConfirmPassword": "Confirm password",
+ "confirmPassword": "Confirm your password",
+ "authSetNewPasswordResetPassword": "Reset password",
+ "authSetNewPasswordBackTo": "Back to",
+ "authPasswordMustBeAtLeast": "Must be at least",
+ "authPasswordCharactersLong": "8 characters long",
+ "authPasswordMustContainAtLeast": "Must contain at least",
+ "authPasswordSpecialCharacter": "one special character",
+ "authPasswordOneNumber": "one number",
+ "authPasswordUpperCharacter": "one upper character",
+ "authPasswordLowerCharacter": "one lower character",
+ "authPasswordConfirmAndPassword": "Confirm password and password",
+ "authPasswordMustMatch": "must match",
+ "friendlyError": "Something went wrong...",
+ "unknownError": "An unknown error occurred",
+ "unauthorized": "Unauthorized access",
+ "authAdminExists": "Admin already exists",
+ "authInviteNotFound": "Invite not found",
+ "unknownService": "Unknown service",
+ "noAuthToken": "No auth token provided",
+ "invalidAuthToken": "Invalid auth token",
+ "expiredAuthToken": "Token expired",
+ "noRefreshToken": "No refresh token provided",
+ "invalidRefreshToken": "Invalid refresh token",
+ "expiredRefreshToken": "Refresh token expired",
+ "requestNewAccessToken": "Request new access token",
+ "invalidPayload": "Invalid payload",
+ "verifyOwnerNotFound": "Document not found",
+ "verifyOwnerUnauthorized": "Unauthorized access",
+ "insufficientPermissions": "Insufficient permissions",
+ "dbUserExists": "User already exists",
+ "dbUserNotFound": "User not found",
+ "dbTokenNotFound": "Token not found",
+ "dbResetPasswordBadMatch": "New password must be different from old password",
+ "dbFindMonitorById": "Monitor with id ${monitorId} not found",
+ "dbDeleteChecks": "No checks found for monitor with id ${monitorId}",
+ "authIncorrectPassword": "Incorrect password",
+ "authUnauthorized": "Unauthorized access",
+ "monitorGetById": "Monitor not found",
+ "monitorGetByUserId": "No monitors found for user",
+ "jobQueueWorkerClose": "Error closing worker",
+ "jobQueueDeleteJob": "Job not found in queue",
+ "jobQueueObliterate": "Error obliterating queue",
+ "pingCannotResolve": "No response",
+ "statusPageNotFound": "Status page not found",
+ "statusPageUrlNotUnique": "Status page url must be unique",
+ "dockerFail": "Failed to fetch Docker container information",
+ "dockerNotFound": "Docker container not found",
+ "portFail": "Failed to connect to port",
+ "alertCreate": "Alert created successfully",
+ "alertGetByUser": "Got alerts successfully",
+ "alertGetByMonitor": "Got alerts by Monitor successfully",
+ "alertGetById": "Got alert by Id successfully",
+ "alertEdit": "Alert edited successfully",
+ "alertDelete": "Alert deleted successfully",
+ "authCreateUser": "User created successfully",
+ "authLoginUser": "User logged in successfully",
+ "authLogoutUser": "User logged out successfully",
+ "authUpdateUser": "User updated successfully",
+ "authCreateRecoveryToken": "Recovery token created successfully",
+ "authVerifyRecoveryToken": "Recovery token verified successfully",
+ "authResetPassword": "Password reset successfully",
+ "authAdminCheck": "Admin check completed successfully",
+ "authDeleteUser": "User deleted successfully",
+ "authTokenRefreshed": "Auth token is refreshed",
+ "authGetAllUsers": "Got all users successfully",
+ "inviteIssued": "Invite sent successfully",
+ "inviteVerified": "Invite verified successfully",
+ "checkCreate": "Check created successfully",
+ "checkGet": "Got checks successfully",
+ "checkDelete": "Checks deleted successfully",
+ "checkUpdateTtl": "Checks TTL updated successfully",
+ "monitorGetAll": "Got all monitors successfully",
+ "monitorStatsById": "Got monitor stats by Id successfully",
+ "monitorGetByIdSuccess": "Got monitor by Id successfully",
+ "monitorGetByTeamId": "Got monitors by Team Id successfully",
+ "monitorGetByUserIdSuccess": "Got monitor for ${userId} successfully",
+ "monitorCreate": "Monitor created successfully",
+ "bulkMonitorsCreate": "Monitors created successfully",
+ "monitorDelete": "Monitor deleted successfully",
+ "monitorEdit": "Monitor edited successfully",
+ "monitorCertificate": "Got monitor certificate successfully",
+ "monitorDemoAdded": "Successfully added demo monitors",
+ "queueGetMetrics": "Got metrics successfully",
+ "queueAddJob": "Job added successfully",
+ "queueObliterate": "Queue obliterated",
+ "jobQueueDeleteJobSuccess": "Job removed successfully",
+ "jobQueuePauseJob": "Job paused successfully",
+ "jobQueueResumeJob": "Job resumed successfully",
+ "maintenanceWindowGetById": "Got Maintenance Window by Id successfully",
+ "maintenanceWindowCreate": "Maintenance Window created successfully",
+ "maintenanceWindowGetByTeam": "Got Maintenance Windows by Team successfully",
+ "maintenanceWindowDelete": "Maintenance Window deleted successfully",
+ "maintenanceWindowEdit": "Maintenance Window edited successfully",
+ "pingSuccess": "Success",
+ "getAppSettings": "Got app settings successfully",
+ "updateAppSettings": "Updated app settings successfully",
+ "statusPageByUrl": "Got status page by url successfully",
+ "statusPageCreate": "Status page created successfully",
+ "newTermsAdded": "New terms added to POEditor",
+ "dockerSuccess": "Docker container status fetched successfully",
+ "portSuccess": "Port connected successfully",
+ "monitorPause": "Monitor paused successfully",
+ "monitorResume": "Monitor resumed successfully",
+ "statusPageDelete": "Status page deleted successfully",
+ "statusPageUpdate": "Status page updated successfully",
+ "statusPageByTeamId": "Got status pages by team id successfully",
+ "httpNetworkError": "Network error",
+ "httpNotJson": "Response data is not json",
+ "httpJsonPathError": "Failed to parse json data",
+ "httpEmptyResult": "Result is empty",
+ "httpMatchSuccess": "Response data match successfully",
+ "httpMatchFail": "Failed to match response data",
+ "webhookSendSuccess": "Webhook notification sent successfully",
+ "telegramRequiresBotTokenAndChatId": "Telegram notifications require both botToken and chatId",
+ "webhookUrlRequired": "Webhook URL is required",
+ "platformRequired": "Platform is required",
+ "testNotificationFailed": "Failed to send test notification",
+ "monitorUpAlert": "Uptime Alert: One of your monitors is back online.\n📌 Monitor: {monitorName}\n📅 Time: {time}\n⚠️ Status: UP\n📟 Status Code: {code}\n\u200B\n",
+ "monitorDownAlert": "Downtime Alert: One of your monitors went offline.\n📌 Monitor: {monitorName}\n📅 Time: {time}\n⚠️ Status: DOWN\n📟 Status Code: {code}\n\u200B\n",
+ "sendTestEmail": "Test email sent successfully",
+ "errorForValidEmailAddress": "A valid recipient email address is required.",
+ "testEmailSubject": "Test E-mail from Checkmate"
+}
diff --git a/server/locales/en.json.bak b/server/locales/en.json.bak
new file mode 100755
index 000000000..eaef58eef
--- /dev/null
+++ b/server/locales/en.json.bak
@@ -0,0 +1,147 @@
+{
+ "dontHaveAccount": "Don't have account",
+ "email": "E-mail",
+ "forgotPassword": "Forgot Password",
+ "password": "password",
+ "signUp": "Sign up",
+ "submit": "Submit",
+ "title": "Title",
+ "continue": "Continue",
+ "enterEmail": "Enter your email",
+ "authLoginTitle": "Log In",
+ "authLoginEnterPassword": "Enter your password",
+ "commonPassword": "Password",
+ "commonBack": "Back",
+ "authForgotPasswordTitle": "Forgot password?",
+ "authForgotPasswordResetPassword": "Reset password",
+ "createPassword": "Create your password",
+ "createAPassword": "Create a password",
+ "authRegisterAlreadyHaveAccount": "Already have an account?",
+ "commonAppName": "BlueWave Uptime",
+ "authLoginEnterEmail": "Enter your email",
+ "authRegisterTitle": "Create an account",
+ "authRegisterStepOneTitle": "Create your account",
+ "authRegisterStepOneDescription": "Enter your details to get started",
+ "authRegisterStepTwoTitle": "Set up your profile",
+ "authRegisterStepTwoDescription": "Tell us more about yourself",
+ "authRegisterStepThreeTitle": "Almost done!",
+ "authRegisterStepThreeDescription": "Review your information",
+ "authForgotPasswordDescription": "No worries, we'll send you reset instructions.",
+ "authForgotPasswordSendInstructions": "Send instructions",
+ "authForgotPasswordBackTo": "Back to",
+ "authCheckEmailTitle": "Check your email",
+ "authCheckEmailDescription": "We sent a password reset link to {{email}}",
+ "authCheckEmailResendEmail": "Resend email",
+ "authCheckEmailBackTo": "Back to",
+ "goBackTo": "Go back to",
+ "authCheckEmailDidntReceiveEmail": "Didn't receive the email?",
+ "authCheckEmailClickToResend": "Click to resend",
+ "authSetNewPasswordTitle": "Set new password",
+ "authSetNewPasswordDescription": "Your new password must be different from previously used passwords.",
+ "authSetNewPasswordNewPassword": "New password",
+ "authSetNewPasswordConfirmPassword": "Confirm password",
+ "confirmPassword": "Confirm your password",
+ "authSetNewPasswordResetPassword": "Reset password",
+ "authSetNewPasswordBackTo": "Back to",
+ "authPasswordMustBeAtLeast": "Must be at least",
+ "authPasswordCharactersLong": "8 characters long",
+ "authPasswordMustContainAtLeast": "Must contain at least",
+ "authPasswordSpecialCharacter": "one special character",
+ "authPasswordOneNumber": "one number",
+ "authPasswordUpperCharacter": "one upper character",
+ "authPasswordLowerCharacter": "one lower character",
+ "authPasswordConfirmAndPassword": "Confirm password and password",
+ "authPasswordMustMatch": "must match",
+ "friendlyError": "Something went wrong...",
+ "unknownError": "An unknown error occurred",
+ "unauthorized": "Unauthorized access",
+ "authAdminExists": "Admin already exists",
+ "authInviteNotFound": "Invite not found",
+ "unknownService": "Unknown service",
+ "noAuthToken": "No auth token provided",
+ "invalidAuthToken": "Invalid auth token",
+ "expiredAuthToken": "Token expired",
+ "noRefreshToken": "No refresh token provided",
+ "invalidRefreshToken": "Invalid refresh token",
+ "expiredRefreshToken": "Refresh token expired",
+ "requestNewAccessToken": "Request new access token",
+ "invalidPayload": "Invalid payload",
+ "verifyOwnerNotFound": "Document not found",
+ "verifyOwnerUnauthorized": "Unauthorized access",
+ "insufficientPermissions": "Insufficient permissions",
+ "dbUserExists": "User already exists",
+ "dbUserNotFound": "User not found",
+ "dbTokenNotFound": "Token not found",
+ "dbResetPasswordBadMatch": "New password must be different from old password",
+ "dbFindMonitorById": "Monitor with id ${monitorId} not found",
+ "dbDeleteChecks": "No checks found for monitor with id ${monitorId}",
+ "authIncorrectPassword": "Incorrect password",
+ "authUnauthorized": "Unauthorized access",
+ "monitorGetById": "Monitor not found",
+ "monitorGetByUserId": "No monitors found for user",
+ "jobQueueWorkerClose": "Error closing worker",
+ "jobQueueDeleteJob": "Job not found in queue",
+ "jobQueueObliterate": "Error obliterating queue",
+ "pingCannotResolve": "No response",
+ "statusPageNotFound": "Status page not found",
+ "statusPageUrlNotUnique": "Status page url must be unique",
+ "dockerFail": "Failed to fetch Docker container information",
+ "dockerNotFound": "Docker container not found",
+ "portFail": "Failed to connect to port",
+ "alertCreate": "Alert created successfully",
+ "alertGetByUser": "Got alerts successfully",
+ "alertGetByMonitor": "Got alerts by Monitor successfully",
+ "alertGetById": "Got alert by Id successfully",
+ "alertEdit": "Alert edited successfully",
+ "alertDelete": "Alert deleted successfully",
+ "authCreateUser": "User created successfully",
+ "authLoginUser": "User logged in successfully",
+ "authLogoutUser": "User logged out successfully",
+ "authUpdateUser": "User updated successfully",
+ "authCreateRecoveryToken": "Recovery token created successfully",
+ "authVerifyRecoveryToken": "Recovery token verified successfully",
+ "authResetPassword": "Password reset successfully",
+ "authAdminCheck": "Admin check completed successfully",
+ "authDeleteUser": "User deleted successfully",
+ "authTokenRefreshed": "Auth token is refreshed",
+ "authGetAllUsers": "Got all users successfully",
+ "inviteIssued": "Invite sent successfully",
+ "inviteVerified": "Invite verified successfully",
+ "checkCreate": "Check created successfully",
+ "checkGet": "Got checks successfully",
+ "checkDelete": "Checks deleted successfully",
+ "checkUpdateTtl": "Checks TTL updated successfully",
+ "monitorGetAll": "Got all monitors successfully",
+ "monitorStatsById": "Got monitor stats by Id successfully",
+ "monitorGetByIdSuccess": "Got monitor by Id successfully",
+ "monitorGetByTeamId": "Got monitors by Team Id successfully",
+ "monitorGetByUserIdSuccess": "Got monitor for ${userId} successfully",
+ "monitorCreate": "Monitor created successfully",
+ "monitorDelete": "Monitor deleted successfully",
+ "monitorEdit": "Monitor edited successfully",
+ "monitorCertificate": "Got monitor certificate successfully",
+ "monitorDemoAdded": "Successfully added demo monitors",
+ "queueGetMetrics": "Got metrics successfully",
+ "queueAddJob": "Job added successfully",
+ "queueObliterate": "Queue obliterated",
+ "jobQueueDeleteJobSuccess": "Job removed successfully",
+ "jobQueuePauseJob": "Job paused successfully",
+ "jobQueueResumeJob": "Job resumed successfully",
+ "maintenanceWindowGetById": "Got Maintenance Window by Id successfully",
+ "maintenanceWindowCreate": "Maintenance Window created successfully",
+ "maintenanceWindowGetByTeam": "Got Maintenance Windows by Team successfully",
+ "maintenanceWindowDelete": "Maintenance Window deleted successfully",
+ "maintenanceWindowEdit": "Maintenance Window edited successfully",
+ "pingSuccess": "Success",
+ "getAppSettings": "Got app settings successfully",
+ "updateAppSettings": "Updated app settings successfully",
+ "statusPageByUrl": "Got status page by url successfully",
+ "statusPageCreate": "Status page created successfully",
+ "newTermsAdded": "New terms added to POEditor",
+ "dockerSuccess": "Docker container status fetched successfully",
+ "portSuccess": "Port connected successfully",
+ "monitorPause": "Monitor paused successfully",
+ "monitorResume": "Monitor resumed successfully",
+ "statusPageDelete": "Status page deleted successfully",
+ "statusPageUpdate": "Status page updated successfully"
+}
diff --git a/server/locales/tr.json b/server/locales/tr.json
new file mode 100755
index 000000000..cc1ef4c64
--- /dev/null
+++ b/server/locales/tr.json
@@ -0,0 +1,146 @@
+{
+ "dontHaveAccount": "Hesabınız yok mu",
+ "email": "E-posta",
+ "forgotPassword": "Parolamı Unuttum",
+ "password": "Parola",
+ "signUp": "Kayıt ol",
+ "submit": "Gönder",
+ "title": "Başlık",
+ "continue": "Devam et",
+ "enterEmail": "E-posta adresinizi girin",
+ "authLoginTitle": "Giriş Yap",
+ "authLoginEnterPassword": "Parolanızı girin",
+ "commonPassword": "Parola",
+ "commonBack": "Geri",
+ "authForgotPasswordTitle": "Parolanı mi unuttun?",
+ "authForgotPasswordResetPassword": "Parola sıfırla",
+ "createPassword": "Parolanızı oluşturun",
+ "createAPassword": "Bir parola oluşturun",
+ "authRegisterAlreadyHaveAccount": "Zaten hesabınız var mı?",
+ "commonAppName": "BlueWave Uptime",
+ "authLoginEnterEmail": "E-posta adresinizi girin",
+ "authRegisterTitle": "Hesap oluştur",
+ "authRegisterStepOneTitle": "Hesabınızı oluşturun",
+ "authRegisterStepOneDescription": "Başlamak için bilgilerinizi girin",
+ "authRegisterStepTwoTitle": "Profilinizi ayarlayın",
+ "authRegisterStepTwoDescription": "Kendiniz hakkında daha fazla bilgi verin",
+ "authRegisterStepThreeTitle": "Neredeyse bitti!",
+ "authRegisterStepThreeDescription": "Bilgilerinizi gözden geçirin",
+ "authForgotPasswordDescription": "Endişelenmeyin, size sıfırlama talimatlarını göndereceğiz.",
+ "authForgotPasswordSendInstructions": "Talimatları gönder",
+ "authForgotPasswordBackTo": "Geri dön",
+ "authCheckEmailTitle": "E-postanızı kontrol edin",
+ "authCheckEmailDescription": "{{email}} adresine bir şifre sıfırlama bağlantısı gönderdik",
+ "authCheckEmailResendEmail": "E-postayı yeniden gönder",
+ "authCheckEmailBackTo": "Geri dön",
+ "goBackTo": "Geri dön",
+ "authCheckEmailDidntReceiveEmail": "E-postayı almadınız mı?",
+ "authCheckEmailClickToResend": "Yeniden göndermek için tıklayın",
+ "authSetNewPasswordTitle": "Yeni şifre belirleyin",
+ "authSetNewPasswordDescription": "Yeni şifreniz, daha önce kullanılan şifrelerden farklı olmalıdır.",
+ "authSetNewPasswordNewPassword": "Yeni şifre",
+ "authSetNewPasswordConfirmPassword": "Parolayı onayla",
+ "confirmPassword": "Parolanızı onaylayın",
+ "authSetNewPasswordResetPassword": "Parolayı sıfırla",
+ "authSetNewPasswordBackTo": "Geri dön",
+ "authPasswordMustBeAtLeast": "En az",
+ "authPasswordCharactersLong": "8 karakter uzunluğunda olmalı",
+ "authPasswordMustContainAtLeast": "En az içermeli",
+ "authPasswordSpecialCharacter": "bir özel karakter",
+ "authPasswordOneNumber": "bir rakam",
+ "authPasswordUpperCharacter": "bir büyük harf",
+ "authPasswordLowerCharacter": "bir küçük harf",
+ "authPasswordConfirmAndPassword": "Onay şifresi ve şifre",
+ "authPasswordMustMatch": "eşleşmelidir",
+ "friendlyError": "Bir şeyler yanlış gitti...",
+ "unknownError": "Bilinmeyen bir hata oluştu",
+ "unauthorized": "Yetkisiz erişim",
+ "authAdminExists": "Yönetici zaten mevcut",
+ "authInviteNotFound": "Davet bulunamadı",
+ "unknownService": "Bilinmeyen servis",
+ "noAuthToken": "Kimlik doğrulama belirteci sağlanmadı",
+ "invalidAuthToken": "Geçersiz kimlik doğrulama belirteci",
+ "expiredAuthToken": "Belirteç süresi doldu",
+ "noRefreshToken": "Yenileme belirteci sağlanmadı",
+ "invalidRefreshToken": "Geçersiz yenileme belirteci",
+ "expiredRefreshToken": "Yenileme belirteci süresi doldu",
+ "requestNewAccessToken": "Yeni erişim belirteci isteyin",
+ "invalidPayload": "Geçersiz veri",
+ "verifyOwnerNotFound": "Belge bulunamadı",
+ "verifyOwnerUnauthorized": "Yetkisiz erişim",
+ "insufficientPermissions": "Yetersiz izinler",
+ "dbUserExists": "Kullanıcı zaten mevcut",
+ "dbUserNotFound": "Kullanıcı bulunamadı",
+ "dbTokenNotFound": "Belirteç bulunamadı",
+ "dbResetPasswordBadMatch": "Yeni şifre eski şifreden farklı olmalıdır",
+ "dbFindMonitorById": "${monitorId} kimlikli monitör bulunamadı",
+ "dbDeleteChecks": "${monitorId} kimlikli monitör için kontrol bulunamadı",
+ "authIncorrectPassword": "Geçersiz parola",
+ "authUnauthorized": "Yetkisiz erişim",
+ "monitorGetById": "Monitör bulunamadı",
+ "monitorGetByUserId": "Kullanıcı için monitör bulunamadı",
+ "jobQueueWorkerClose": "İşçi kapatılırken hata oluştu",
+ "jobQueueDeleteJob": "İş kuyrukta bulunamadı",
+ "jobQueueObliterate": "Kuyruk yok edilirken hata oluştu",
+ "pingCannotResolve": "Yanıt yok",
+ "statusPageNotFound": "Durum sayfası bulunamadı",
+ "statusPageUrlNotUnique": "Durum sayfası URL'si benzersiz olmalıdır",
+ "dockerFail": "Docker konteyner bilgisi alınamadı",
+ "dockerNotFound": "Docker konteyner bulunamadı",
+ "portFail": "Porta bağlanılamadı",
+ "alertCreate": "Uyarı başarıyla oluşturuldu",
+ "alertGetByUser": "Uyarılar başarıyla alındı",
+ "alertGetByMonitor": "Monitöre göre uyarılar başarıyla alındı",
+ "alertGetById": "Kimliğe göre uyarı başarıyla alındı",
+ "alertEdit": "Uyarı başarıyla düzenlendi",
+ "alertDelete": "Uyarı başarıyla silindi",
+ "authCreateUser": "Kullanıcı başarıyla oluşturuldu",
+ "authLoginUser": "Kullanıcı başarıyla giriş yaptı",
+ "authLogoutUser": "Kullanıcı başarıyla çıkış yaptı",
+ "authUpdateUser": "Kullanıcı başarıyla güncellendi",
+ "authCreateRecoveryToken": "Kurtarma belirteci başarıyla oluşturuldu",
+ "authVerifyRecoveryToken": "Kurtarma belirteci başarıyla doğrulandı",
+ "authResetPassword": "Şifre başarıyla sıfırlandı",
+ "authAdminCheck": "Yönetici kontrolü başarıyla tamamlandı",
+ "authDeleteUser": "Kullanıcı başarıyla silindi",
+ "authTokenRefreshed": "Kimlik doğrulama belirteci yenilendi",
+ "authGetAllUsers": "Tüm kullanıcılar başarıyla alındı",
+ "inviteIssued": "Davet başarıyla gönderildi",
+ "inviteVerified": "Davet başarıyla doğrulandı",
+ "checkCreate": "Kontrol başarıyla oluşturuldu",
+ "checkGet": "Kontroller başarıyla alındı",
+ "checkDelete": "Kontroller başarıyla silindi",
+ "checkUpdateTtl": "Kontrol TTL başarıyla güncellendi",
+ "monitorGetAll": "Tüm monitörler başarıyla alındı",
+ "monitorStatsById": "Kimliğe göre monitör istatistikleri başarıyla alındı",
+ "monitorGetByIdSuccess": "Kimliğe göre monitör başarıyla alındı",
+ "monitorGetByTeamId": "Takım kimliğine göre monitörler başarıyla alındı",
+ "monitorGetByUserIdSuccess": "${userId} için monitör başarıyla alındı",
+ "monitorCreate": "Monitör başarıyla oluşturuldu",
+ "monitorDelete": "Monitör başarıyla silindi",
+ "monitorEdit": "Monitör başarıyla düzenlendi",
+ "monitorCertificate": "Monitör sertifikası başarıyla alındı",
+ "monitorDemoAdded": "Demo monitörler başarıyla eklendi",
+ "queueGetMetrics": "Metrikler başarıyla alındı",
+ "queueAddJob": "İş başarıyla eklendi",
+ "queueObliterate": "Kuyruk yok edildi",
+ "jobQueueDeleteJobSuccess": "İş başarıyla kaldırıldı",
+ "jobQueuePauseJob": "İş başarıyla duraklatıldı",
+ "jobQueueResumeJob": "İş başarıyla devam ettirildi",
+ "maintenanceWindowGetById": "Kimliğe göre bakım penceresi başarıyla alındı",
+ "maintenanceWindowCreate": "Bakım penceresi başarıyla oluşturuldu",
+ "maintenanceWindowGetByTeam": "Takıma göre bakım pencereleri başarıyla alındı",
+ "maintenanceWindowDelete": "Bakım penceresi başarıyla silindi",
+ "maintenanceWindowEdit": "Bakım penceresi başarıyla düzenlendi",
+ "pingSuccess": "Başarılı",
+ "getAppSettings": "Uygulama ayarları başarıyla alındı",
+ "updateAppSettings": "Uygulama ayarları başarıyla güncellendi",
+ "statusPageByUrl": "URL'ye göre durum sayfası başarıyla alındı",
+ "statusPageCreate": "Durum sayfası başarıyla oluşturuldu",
+ "dockerSuccess": "Docker konteyner durumu başarıyla alındı",
+ "portSuccess": "Porta başarıyla bağlanıldı",
+ "newTermsAdded": "POEditor'a yeni terimler eklendi",
+ "monitorPause": "Monitör başarıyla duraklatıldı",
+ "monitorResume": "Monitör başarıyla devam ettirildi",
+ "monitorDelete2": ""
+}
diff --git a/server/middleware/handleErrors.js b/server/middleware/handleErrors.js
new file mode 100755
index 000000000..b64cda897
--- /dev/null
+++ b/server/middleware/handleErrors.js
@@ -0,0 +1,22 @@
+import logger from "../utils/logger.js";
+import ServiceRegistry from "../service/serviceRegistry.js";
+import StringService from "../service/stringService.js";
+
+const handleErrors = (error, req, res, next) => {
+ const status = error.status || 500;
+ const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
+ const message = error.message || stringService.friendlyError;
+ const service = error.service || stringService.unknownService;
+ logger.error({
+ message: message,
+ service: service,
+ method: error.method,
+ stack: error.stack,
+ });
+ res.error({
+ status,
+ msg: message,
+ });
+};
+
+export { handleErrors };
diff --git a/Server/middleware/isAllowed.js b/server/middleware/isAllowed.js
old mode 100644
new mode 100755
similarity index 79%
rename from Server/middleware/isAllowed.js
rename to server/middleware/isAllowed.js
index bd75b00ad..4c6f89aa3
--- a/Server/middleware/isAllowed.js
+++ b/server/middleware/isAllowed.js
@@ -2,17 +2,16 @@ import jwt from "jsonwebtoken";
const TOKEN_PREFIX = "Bearer ";
const SERVICE_NAME = "allowedRoles";
import ServiceRegistry from "../service/serviceRegistry.js";
+import StringService from "../service/stringService.js";
import SettingsService from "../service/settingsService.js";
-import { errorMessages } from "../utils/messages.js";
-
const isAllowed = (allowedRoles) => {
return (req, res, next) => {
const token = req.headers["authorization"];
-
+ const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
// If no token is pressent, return an error
if (!token) {
- const error = new Error(errorMessages.NO_AUTH_TOKEN);
+ const error = new Error(stringService.noAuthToken);
error.status = 401;
error.service = SERVICE_NAME;
next(error);
@@ -21,7 +20,7 @@ const isAllowed = (allowedRoles) => {
// If the token is improperly formatted, return an error
if (!token.startsWith(TOKEN_PREFIX)) {
- const error = new Error(errorMessages.INVALID_AUTH_TOKEN);
+ const error = new Error(stringService.invalidAuthToken);
error.status = 400;
error.service = SERVICE_NAME;
next(error);
@@ -41,8 +40,8 @@ const isAllowed = (allowedRoles) => {
next();
return;
} else {
- const error = new Error(errorMessages.INSUFFICIENT_PERMISSIONS);
- error.status = 401;
+ const error = new Error(stringService.insufficientPermissions);
+ error.status = 403;
error.service = SERVICE_NAME;
next(error);
return;
diff --git a/server/middleware/languageMiddleware.js b/server/middleware/languageMiddleware.js
new file mode 100755
index 000000000..1449e203f
--- /dev/null
+++ b/server/middleware/languageMiddleware.js
@@ -0,0 +1,28 @@
+import logger from "../utils/logger.js";
+
+const languageMiddleware =
+ (stringService, translationService) => async (req, res, next) => {
+ try {
+ const acceptLanguage = req.headers["accept-language"] || "en";
+ const language = acceptLanguage.split(",")[0].slice(0, 2).toLowerCase();
+
+ translationService.setLanguage(language);
+ stringService.setLanguage(language);
+
+ next();
+ } catch (error) {
+ logger.error({
+ message: error.message,
+ service: "languageMiddleware",
+ });
+ const acceptLanguage = req.headers["accept-language"] || "en";
+ const language = acceptLanguage.split(",")[0].slice(0, 2).toLowerCase();
+
+ translationService.setLanguage(language);
+ stringService.setLanguage(language);
+
+ next();
+ }
+ };
+
+export default languageMiddleware;
diff --git a/server/middleware/responseHandler.js b/server/middleware/responseHandler.js
new file mode 100755
index 000000000..a58e2e845
--- /dev/null
+++ b/server/middleware/responseHandler.js
@@ -0,0 +1,46 @@
+/**
+ * Middleware that adds standardized response methods to the Express response object.
+ * This allows for consistent API responses throughout the application.
+ *
+ * @param {import('express').Request} req - Express request object
+ * @param {import('express').Response} res - Express response object
+ * @param {import('express').NextFunction} next - Express next middleware function
+ */
+const responseHandler = (req, res, next) => {
+ /**
+ * Sends a standardized success response
+ *
+ * @param {Object} options - Success response options
+ * @param {number} [options.status=200] - HTTP status code
+ * @param {string} [options.msg="OK"] - Success message
+ * @param {*} [options.data=null] - Response data payload
+ * @returns {Object} Express response object
+ */
+ res.success = ({ status = 200, msg = "OK", data = null }) => {
+ return res.status(status).json({
+ success: true,
+ msg: msg,
+ data: data,
+ });
+ };
+
+ /**
+ * Sends a standardized error response
+ *
+ * @param {Object} options - Error response options
+ * @param {number} [options.status=500] - HTTP status code
+ * @param {string} [options.msg="Internal server error"] - Error message
+ * @param {*} [options.data=null] - Additional error data (if any)
+ * @returns {Object} Express response object
+ */
+ res.error = ({ status = 500, msg = "Internal server error", data = null }) => {
+ return res.status(status).json({
+ success: false,
+ msg,
+ data,
+ });
+ };
+ next();
+};
+
+export { responseHandler };
diff --git a/server/middleware/verifyJWT.js b/server/middleware/verifyJWT.js
new file mode 100755
index 000000000..bd17edcfd
--- /dev/null
+++ b/server/middleware/verifyJWT.js
@@ -0,0 +1,57 @@
+import jwt from "jsonwebtoken";
+import ServiceRegistry from "../service/serviceRegistry.js";
+import SettingsService from "../service/settingsService.js";
+import StringService from "../service/stringService.js";
+const SERVICE_NAME = "verifyJWT";
+const TOKEN_PREFIX = "Bearer ";
+
+/**
+ * Verifies the JWT token
+ * @function
+ * @param {express.Request} req
+ * @param {express.Response} res
+ * @param {express.NextFunction} next
+ * @returns {express.Response}
+ */
+const verifyJWT = (req, res, next) => {
+ const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
+ const token = req.headers["authorization"];
+ // Make sure a token is provided
+ if (!token) {
+ const error = new Error(stringService.noAuthToken);
+ error.status = 401;
+ error.service = SERVICE_NAME;
+ next(error);
+ return;
+ }
+ // Make sure it is properly formatted
+ if (!token.startsWith(TOKEN_PREFIX)) {
+ const error = new Error(stringService.invalidAuthToken); // Instantiate a new Error object for improperly formatted token
+ error.status = 401;
+ error.service = SERVICE_NAME;
+ error.method = "verifyJWT";
+ next(error);
+ return;
+ }
+
+ const parsedToken = token.slice(TOKEN_PREFIX.length, token.length);
+ // Verify the token's authenticity
+ const { jwtSecret } = ServiceRegistry.get(SettingsService.SERVICE_NAME).getSettings();
+ jwt.verify(parsedToken, jwtSecret, (err, decoded) => {
+ if (err) {
+ if (err) {
+ const errorMessage =
+ err.name === "TokenExpiredError"
+ ? stringService.expiredAuthToken
+ : stringService.invalidAuthToken;
+ return res.status(401).json({ success: false, msg: errorMessage });
+ }
+ } else {
+ // Token is valid, carry on
+ req.user = decoded;
+ next();
+ }
+ });
+};
+
+export { verifyJWT };
diff --git a/Server/middleware/verifyOwnership.js b/server/middleware/verifyOwnership.js
old mode 100644
new mode 100755
similarity index 71%
rename from Server/middleware/verifyOwnership.js
rename to server/middleware/verifyOwnership.js
index d812dd543..ca2476f54
--- a/Server/middleware/verifyOwnership.js
+++ b/server/middleware/verifyOwnership.js
@@ -1,8 +1,10 @@
import logger from "../utils/logger.js";
-import { errorMessages } from "../utils/messages.js";
+import ServiceRegistry from "../service/serviceRegistry.js";
+import StringService from "../service/stringService.js";
const SERVICE_NAME = "verifyOwnership";
const verifyOwnership = (Model, paramName) => {
+ const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
return async (req, res, next) => {
const userId = req.user._id;
const documentId = req.params[paramName];
@@ -11,11 +13,11 @@ const verifyOwnership = (Model, paramName) => {
//If the document is not found, return a 404 error
if (!doc) {
logger.error({
- message: errorMessages.VERIFY_OWNER_NOT_FOUND,
+ message: stringService.verifyOwnerNotFound,
service: SERVICE_NAME,
method: "verifyOwnership",
});
- const error = new Error(errorMessages.VERIFY_OWNER_NOT_FOUND);
+ const error = new Error(stringService.verifyOwnerNotFound);
error.status = 404;
throw error;
}
@@ -23,7 +25,7 @@ const verifyOwnership = (Model, paramName) => {
// Special case for User model, as it will not have a `userId` field as other docs will
if (Model.modelName === "User") {
if (userId.toString() !== doc._id.toString()) {
- const error = new Error(errorMessages.VERIFY_OWNER_UNAUTHORIZED);
+ const error = new Error(stringService.verifyOwnerUnauthorized);
error.status = 403;
throw error;
}
@@ -33,7 +35,7 @@ const verifyOwnership = (Model, paramName) => {
// If the userID does not match the document's userID, return a 403 error
if (userId.toString() !== doc.userId.toString()) {
- const error = new Error(errorMessages.VERIFY_OWNER_UNAUTHORIZED);
+ const error = new Error(stringService.verifyOwnerUnauthorized);
error.status = 403;
throw error;
}
diff --git a/Server/middleware/verifySuperAdmin.js b/server/middleware/verifySuperAdmin.js
old mode 100644
new mode 100755
similarity index 73%
rename from Server/middleware/verifySuperAdmin.js
rename to server/middleware/verifySuperAdmin.js
index bf4c780a7..98c336fad
--- a/Server/middleware/verifySuperAdmin.js
+++ b/server/middleware/verifySuperAdmin.js
@@ -2,9 +2,9 @@ const jwt = require("jsonwebtoken");
const logger = require("../utils/logger");
const SERVICE_NAME = "verifyAdmin";
const TOKEN_PREFIX = "Bearer ";
-const { errorMessages } = require("../utils/messages");
import ServiceRegistry from "../service/serviceRegistry.js";
import SettingsService from "../service/settingsService.js";
+import StringService from "../service/stringService.js";
/**
* Verifies the JWT token
* @function
@@ -14,10 +14,11 @@ import SettingsService from "../service/settingsService.js";
* @returns {express.Response}
*/
const verifySuperAdmin = (req, res, next) => {
+ const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
const token = req.headers["authorization"];
// Make sure a token is provided
if (!token) {
- const error = new Error(errorMessages.NO_AUTH_TOKEN);
+ const error = new Error(stringService.noAuthToken);
error.status = 401;
error.service = SERVICE_NAME;
next(error);
@@ -25,7 +26,7 @@ const verifySuperAdmin = (req, res, next) => {
}
// Make sure it is properly formatted
if (!token.startsWith(TOKEN_PREFIX)) {
- const error = new Error(errorMessages.INVALID_AUTH_TOKEN); // Instantiate a new Error object for improperly formatted token
+ const error = new Error(stringService.invalidAuthToken); // Instantiate a new Error object for improperly formatted token
error.status = 400;
error.service = SERVICE_NAME;
error.method = "verifySuperAdmin";
@@ -44,21 +45,21 @@ const verifySuperAdmin = (req, res, next) => {
service: SERVICE_NAME,
method: "verifySuperAdmin",
stack: err.stack,
- details: errorMessages.INVALID_AUTH_TOKEN,
+ details: stringService.invalidAuthToken,
});
return res
.status(401)
- .json({ success: false, msg: errorMessages.INVALID_AUTH_TOKEN });
+ .json({ success: false, msg: stringService.invalidAuthToken });
}
if (decoded.role.includes("superadmin") === false) {
logger.error({
- message: errorMessages.INVALID_AUTH_TOKEN,
+ message: stringService.invalidAuthToken,
service: SERVICE_NAME,
method: "verifySuperAdmin",
stack: err.stack,
});
- return res.status(401).json({ success: false, msg: errorMessages.UNAUTHORIZED });
+ return res.status(401).json({ success: false, msg: stringService.unauthorized });
}
next();
});
diff --git a/server/nodemon.json b/server/nodemon.json
new file mode 100755
index 000000000..928d1abc2
--- /dev/null
+++ b/server/nodemon.json
@@ -0,0 +1,5 @@
+{
+ "ignore": ["locales/*", "*.log", "node_modules/*"],
+ "watch": ["*.js", "*.json"],
+ "ext": "js,json"
+}
diff --git a/Server/openapi.json b/server/openapi.json
old mode 100644
new mode 100755
similarity index 100%
rename from Server/openapi.json
rename to server/openapi.json
diff --git a/Server/package-lock.json b/server/package-lock.json
old mode 100644
new mode 100755
similarity index 88%
rename from Server/package-lock.json
rename to server/package-lock.json
index 67399c8a1..f236139d8
--- a/Server/package-lock.json
+++ b/server/package-lock.json
@@ -10,15 +10,17 @@
"license": "ISC",
"dependencies": {
"axios": "^1.7.2",
- "bcrypt": "5.1.1",
- "bullmq": "5.35.1",
+ "bcryptjs": "3.0.2",
+ "bullmq": "5.41.2",
+ "compression": "1.8.0",
"cors": "^2.8.5",
- "dockerode": "4.0.4",
+ "dockerode": "4.0.6",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"handlebars": "^4.7.8",
"helmet": "^8.0.0",
"ioredis": "^5.4.2",
+ "jmespath": "^0.16.0",
"joi": "^17.13.1",
"jsonwebtoken": "9.0.2",
"mailersend": "^2.2.0",
@@ -35,13 +37,12 @@
"devDependencies": {
"@eslint/js": "^9.17.0",
"c8": "10.1.3",
- "chai": "5.1.2",
+ "chai": "5.2.0",
"eslint": "^9.17.0",
"eslint-plugin-mocha": "^10.5.0",
"esm": "3.2.25",
"globals": "^15.14.0",
"mocha": "11.1.0",
- "ngrok": "5.0.0-beta.2",
"nodemon": "3.1.9",
"prettier": "^3.3.3",
"sinon": "19.0.2"
@@ -71,9 +72,9 @@
}
},
"node_modules/@babel/runtime": {
- "version": "7.26.0",
- "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.0.tgz",
- "integrity": "sha512-FDSOghenHTiToteC/QRlv2q3DhPZ/oOXTBoirfWNx1Cx3TMVcGWQtMMmQcSvb/JjpNeGzx8Pq/b4fKEJuWm1sw==",
+ "version": "7.26.10",
+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.10.tgz",
+ "integrity": "sha512-2WJMeRQPHKSPemqk/awGrAiuFfzBmOIPXKizAsVhWH9YJqLZ0H+HS4c8loHGgW6utJ3E/ejXQUsiGaQy2NZ9Fw==",
"license": "MIT",
"dependencies": {
"regenerator-runtime": "^0.14.0"
@@ -192,23 +193,6 @@
"concat-map": "0.0.1"
}
},
- "node_modules/@eslint/config-array/node_modules/debug": {
- "version": "4.4.0",
- "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz",
- "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==",
- "dev": true,
- "dependencies": {
- "ms": "^2.1.3"
- },
- "engines": {
- "node": ">=6.0"
- },
- "peerDependenciesMeta": {
- "supports-color": {
- "optional": true
- }
- }
- },
"node_modules/@eslint/config-array/node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
@@ -222,12 +206,6 @@
"node": "*"
}
},
- "node_modules/@eslint/config-array/node_modules/ms": {
- "version": "2.1.3",
- "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
- "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
- "dev": true
- },
"node_modules/@eslint/core": {
"version": "0.10.0",
"resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.10.0.tgz",
@@ -275,23 +253,6 @@
"concat-map": "0.0.1"
}
},
- "node_modules/@eslint/eslintrc/node_modules/debug": {
- "version": "4.4.0",
- "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz",
- "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==",
- "dev": true,
- "dependencies": {
- "ms": "^2.1.3"
- },
- "engines": {
- "node": ">=6.0"
- },
- "peerDependenciesMeta": {
- "supports-color": {
- "optional": true
- }
- }
- },
"node_modules/@eslint/eslintrc/node_modules/globals": {
"version": "14.0.0",
"resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz",
@@ -317,16 +278,10 @@
"node": "*"
}
},
- "node_modules/@eslint/eslintrc/node_modules/ms": {
- "version": "2.1.3",
- "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
- "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
- "dev": true
- },
"node_modules/@eslint/js": {
- "version": "9.18.0",
- "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.18.0.tgz",
- "integrity": "sha512-fK6L7rxcq6/z+AaQMtiFTkvbHkBLNlwyRxHpKawP0x3u9+NC6MQTnFW+AdpwC6gfHTW0051cokQgtTN2FqlxQA==",
+ "version": "9.20.0",
+ "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.20.0.tgz",
+ "integrity": "sha512-iZA07H9io9Wn836aVTytRaNqh00Sad+EamwOVJT12GTLw1VGMFV/4JaME+JjLtr9fiGaoWgYnS54wrfWsSs4oQ==",
"dev": true,
"license": "MIT",
"engines": {
@@ -895,26 +850,6 @@
"url": "https://opencollective.com/js-sdsl"
}
},
- "node_modules/@mapbox/node-pre-gyp": {
- "version": "1.0.11",
- "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz",
- "integrity": "sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ==",
- "license": "BSD-3-Clause",
- "dependencies": {
- "detect-libc": "^2.0.0",
- "https-proxy-agent": "^5.0.0",
- "make-dir": "^3.1.0",
- "node-fetch": "^2.6.7",
- "nopt": "^5.0.0",
- "npmlog": "^5.0.1",
- "rimraf": "^3.0.2",
- "semver": "^7.3.5",
- "tar": "^6.1.11"
- },
- "bin": {
- "node-pre-gyp": "bin/node-pre-gyp"
- }
- },
"node_modules/@mongodb-js/saslprep": {
"version": "1.1.9",
"resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.1.9.tgz",
@@ -1104,19 +1039,6 @@
"integrity": "sha512-RNiOoTPkptFtSVzQevY/yWtZwf/RxyVnPy/OcA9HBM3MlGDnBEYL5B41H0MTn0Uec8Hi+2qUtTfG2WWZBmMejQ==",
"license": "BSD-3-Clause"
},
- "node_modules/@sindresorhus/is": {
- "version": "4.6.0",
- "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz",
- "integrity": "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=10"
- },
- "funding": {
- "url": "https://github.com/sindresorhus/is?sponsor=1"
- }
- },
"node_modules/@sinonjs/commons": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.1.tgz",
@@ -1166,19 +1088,6 @@
"dev": true,
"license": "(Unlicense OR Apache-2.0)"
},
- "node_modules/@szmarczak/http-timer": {
- "version": "4.0.6",
- "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.6.tgz",
- "integrity": "sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "defer-to-connect": "^2.0.0"
- },
- "engines": {
- "node": ">=10"
- }
- },
"node_modules/@trysound/sax": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/@trysound/sax/-/sax-0.2.0.tgz",
@@ -1188,32 +1097,12 @@
"node": ">=10.13.0"
}
},
- "node_modules/@types/cacheable-request": {
- "version": "6.0.3",
- "resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.3.tgz",
- "integrity": "sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/http-cache-semantics": "*",
- "@types/keyv": "^3.1.4",
- "@types/node": "*",
- "@types/responselike": "^1.0.0"
- }
- },
"node_modules/@types/estree": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz",
"integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==",
"dev": true
},
- "node_modules/@types/http-cache-semantics": {
- "version": "4.0.4",
- "resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.0.4.tgz",
- "integrity": "sha512-1m0bIFVc7eJWyve9S0RnuRgcQqF/Xd5QsUZAZeQFr1Q3/p9JWoQQEqmVy+DPTNpGXwhgIetAoYF8JSc33q29QA==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/@types/istanbul-lib-coverage": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz",
@@ -1227,16 +1116,6 @@
"integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
"dev": true
},
- "node_modules/@types/keyv": {
- "version": "3.1.4",
- "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz",
- "integrity": "sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/node": "*"
- }
- },
"node_modules/@types/node": {
"version": "22.10.4",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.10.4.tgz",
@@ -1246,16 +1125,6 @@
"undici-types": "~6.20.0"
}
},
- "node_modules/@types/responselike": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.3.tgz",
- "integrity": "sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/node": "*"
- }
- },
"node_modules/@types/triple-beam": {
"version": "1.3.5",
"resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz",
@@ -1277,23 +1146,6 @@
"@types/webidl-conversions": "*"
}
},
- "node_modules/@types/yauzl": {
- "version": "2.10.3",
- "resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz",
- "integrity": "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==",
- "dev": true,
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "@types/node": "*"
- }
- },
- "node_modules/abbrev": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz",
- "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==",
- "license": "ISC"
- },
"node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
@@ -1340,27 +1192,6 @@
"node": ">= 6.0.0"
}
},
- "node_modules/agent-base/node_modules/debug": {
- "version": "4.3.5",
- "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.5.tgz",
- "integrity": "sha512-pt0bNEmneDIvdL1Xsd9oDQ/wrQRkXDT4AUWlNZNPKvW5x/jyO9VFXkJUP07vQ2upmw5PlaITaPKc31jK13V+jg==",
- "dependencies": {
- "ms": "2.1.2"
- },
- "engines": {
- "node": ">=6.0"
- },
- "peerDependenciesMeta": {
- "supports-color": {
- "optional": true
- }
- }
- },
- "node_modules/agent-base/node_modules/ms": {
- "version": "2.1.2",
- "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
- "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
- },
"node_modules/ajv": {
"version": "6.12.6",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
@@ -1432,26 +1263,6 @@
"integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",
"license": "MIT"
},
- "node_modules/aproba": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz",
- "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==",
- "license": "ISC"
- },
- "node_modules/are-we-there-yet": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz",
- "integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==",
- "deprecated": "This package is no longer supported.",
- "license": "ISC",
- "dependencies": {
- "delegates": "^1.0.0",
- "readable-stream": "^3.6.0"
- },
- "engines": {
- "node": ">=10"
- }
- },
"node_modules/argparse": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
@@ -1496,9 +1307,9 @@
"license": "MIT"
},
"node_modules/axios": {
- "version": "1.7.9",
- "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz",
- "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==",
+ "version": "1.8.2",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.2.tgz",
+ "integrity": "sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
@@ -1532,20 +1343,6 @@
],
"license": "MIT"
},
- "node_modules/bcrypt": {
- "version": "5.1.1",
- "resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-5.1.1.tgz",
- "integrity": "sha512-AGBHOG5hPYZ5Xl9KXzU5iKq9516yEmvCKDg3ecP5kX2aB6UqTeXZxk2ELnDgDm6BQSMlLt9rDB4LoSMx0rYwww==",
- "hasInstallScript": true,
- "license": "MIT",
- "dependencies": {
- "@mapbox/node-pre-gyp": "^1.0.11",
- "node-addon-api": "^5.0.0"
- },
- "engines": {
- "node": ">= 10.0.0"
- }
- },
"node_modules/bcrypt-pbkdf": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
@@ -1555,6 +1352,15 @@
"tweetnacl": "^0.14.3"
}
},
+ "node_modules/bcryptjs": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.2.tgz",
+ "integrity": "sha512-k38b3XOZKv60C4E2hVsXTolJWfkGRMbILBIe2IBITXciy5bOsTKot5kDrf3ZfufQtQOUN5mXceUEpU1rTl9Uog==",
+ "license": "BSD-3-Clause",
+ "bin": {
+ "bcrypt": "bin/bcrypt"
+ }
+ },
"node_modules/binary-extensions": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
@@ -1716,16 +1522,6 @@
"ieee754": "^1.1.13"
}
},
- "node_modules/buffer-crc32": {
- "version": "0.2.13",
- "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",
- "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": "*"
- }
- },
"node_modules/buffer-equal-constant-time": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
@@ -1748,9 +1544,9 @@
}
},
"node_modules/bullmq": {
- "version": "5.35.1",
- "resolved": "https://registry.npmjs.org/bullmq/-/bullmq-5.35.1.tgz",
- "integrity": "sha512-LnzqisWyF4V8KhgFnK7iaJdQn9Q61EdHdCT6sVTzA3jZr6CHxw/OBmBZhzA8Xq4bsvsmvdjr8pmGftC78aWgXQ==",
+ "version": "5.41.2",
+ "resolved": "https://registry.npmjs.org/bullmq/-/bullmq-5.41.2.tgz",
+ "integrity": "sha512-wqsUIHW2Td86mTKTepqQpKLLUtP4gmX89bUO1YL2fAorxwj3da1GYtroGZMCg/zgB/+zMRsbylL6DHyMUWX7fA==",
"license": "MIT",
"dependencies": {
"cron-parser": "^4.9.0",
@@ -1816,35 +1612,6 @@
}
}
},
- "node_modules/cacheable-lookup": {
- "version": "5.0.4",
- "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz",
- "integrity": "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=10.6.0"
- }
- },
- "node_modules/cacheable-request": {
- "version": "7.0.4",
- "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.4.tgz",
- "integrity": "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "clone-response": "^1.0.2",
- "get-stream": "^5.1.0",
- "http-cache-semantics": "^4.0.0",
- "keyv": "^4.0.0",
- "lowercase-keys": "^2.0.0",
- "normalize-url": "^6.0.1",
- "responselike": "^2.0.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
"node_modules/call-bind-apply-helpers": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.1.tgz",
@@ -1929,9 +1696,9 @@
"license": "CC-BY-4.0"
},
"node_modules/chai": {
- "version": "5.1.2",
- "resolved": "https://registry.npmjs.org/chai/-/chai-5.1.2.tgz",
- "integrity": "sha512-aGtmf24DW6MLHHG5gCx4zaI3uBq3KRtxeVs0DjFH6Z0rDNbsvTxFASFvdj79pxjxZ8/5u3PIiN3IwEIQkiiuPw==",
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-5.2.0.tgz",
+ "integrity": "sha512-mCuXncKXk5iCLhfhwTc0izo0gtEmpz5CtG2y8GiOINBlMVS6v8TMRc5TaLWKS6692m9+dVVfzgeVxR5UxWHTYw==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -2034,15 +1801,6 @@
"fsevents": "~2.3.2"
}
},
- "node_modules/chownr": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz",
- "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==",
- "license": "ISC",
- "engines": {
- "node": ">=10"
- }
- },
"node_modules/cliui": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
@@ -2115,19 +1873,6 @@
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
- "node_modules/clone-response": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.3.tgz",
- "integrity": "sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "mimic-response": "^1.0.0"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
"node_modules/cluster-key-slot": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz",
@@ -2178,15 +1923,6 @@
"simple-swizzle": "^0.2.2"
}
},
- "node_modules/color-support": {
- "version": "1.1.3",
- "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz",
- "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==",
- "license": "ISC",
- "bin": {
- "color-support": "bin.js"
- }
- },
"node_modules/colord": {
"version": "2.9.3",
"resolved": "https://registry.npmjs.org/colord/-/colord-2.9.3.tgz",
@@ -2249,10 +1985,65 @@
"node": ">=18"
}
},
+ "node_modules/compressible": {
+ "version": "2.0.18",
+ "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz",
+ "integrity": "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": ">= 1.43.0 < 2"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/compression": {
+ "version": "1.8.0",
+ "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.0.tgz",
+ "integrity": "sha512-k6WLKfunuqCYD3t6AsuPGvQWaKwuLLh2/xHNcX4qE+vIfDNXpSqnrhwA7O53R7WVQUnt8dVAIW+YHr7xTgOgGA==",
+ "license": "MIT",
+ "dependencies": {
+ "bytes": "3.1.2",
+ "compressible": "~2.0.18",
+ "debug": "2.6.9",
+ "negotiator": "~0.6.4",
+ "on-headers": "~1.0.2",
+ "safe-buffer": "5.2.1",
+ "vary": "~1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.8.0"
+ }
+ },
+ "node_modules/compression/node_modules/debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "2.0.0"
+ }
+ },
+ "node_modules/compression/node_modules/ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
+ "license": "MIT"
+ },
+ "node_modules/compression/node_modules/negotiator": {
+ "version": "0.6.4",
+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.4.tgz",
+ "integrity": "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
+ "dev": true,
"license": "MIT"
},
"node_modules/concat-stream": {
@@ -2300,12 +2091,6 @@
"safe-buffer": "~5.1.0"
}
},
- "node_modules/console-control-strings": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz",
- "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==",
- "license": "ISC"
- },
"node_modules/content-disposition": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
@@ -2638,35 +2423,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
- "node_modules/decompress-response": {
- "version": "6.0.0",
- "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
- "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "mimic-response": "^3.1.0"
- },
- "engines": {
- "node": ">=10"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/decompress-response/node_modules/mimic-response": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
- "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=10"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
"node_modules/deep-eql": {
"version": "5.0.2",
"resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",
@@ -2683,16 +2439,6 @@
"integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==",
"dev": true
},
- "node_modules/defer-to-connect": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.1.tgz",
- "integrity": "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=10"
- }
- },
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
@@ -2702,12 +2448,6 @@
"node": ">=0.4.0"
}
},
- "node_modules/delegates": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz",
- "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==",
- "license": "MIT"
- },
"node_modules/denque": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz",
@@ -2777,9 +2517,9 @@
}
},
"node_modules/dockerode": {
- "version": "4.0.4",
- "resolved": "https://registry.npmjs.org/dockerode/-/dockerode-4.0.4.tgz",
- "integrity": "sha512-6GYP/EdzEY50HaOxTVTJ2p+mB5xDHTMJhS+UoGrVyS6VC+iQRh7kZ4FRpUYq6nziby7hPqWhOrFFUFTMUZJJ5w==",
+ "version": "4.0.6",
+ "resolved": "https://registry.npmjs.org/dockerode/-/dockerode-4.0.6.tgz",
+ "integrity": "sha512-FbVf3Z8fY/kALB9s+P9epCpWhfi/r0N2DgYYcYpsAUlaTxPjdsitsFobnltb+lyCgAIvf9C+4PSWlTnHlJMf1w==",
"license": "Apache-2.0",
"dependencies": {
"@balena/dockerignore": "^1.0.2",
@@ -2787,7 +2527,7 @@
"@grpc/proto-loader": "^0.7.13",
"docker-modem": "^5.0.6",
"protobufjs": "^7.3.2",
- "tar-fs": "~2.0.1",
+ "tar-fs": "~2.1.2",
"uuid": "^10.0.0"
},
"engines": {
@@ -3071,18 +2811,18 @@
}
},
"node_modules/eslint": {
- "version": "9.18.0",
- "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.18.0.tgz",
- "integrity": "sha512-+waTfRWQlSbpt3KWE+CjrPPYnbq9kfZIYUqapc0uBXyjTp8aYXZDsUH16m39Ryq3NjAVP4tjuF7KaukeqoCoaA==",
+ "version": "9.20.1",
+ "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.20.1.tgz",
+ "integrity": "sha512-m1mM33o6dBUjxl2qb6wv6nGNwCAsns1eKtaQ4l/NPHeTvhiUPbtdfMyktxN4B3fgHIgsYh1VT3V9txblpQHq+g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/eslint-utils": "^4.2.0",
"@eslint-community/regexpp": "^4.12.1",
"@eslint/config-array": "^0.19.0",
- "@eslint/core": "^0.10.0",
+ "@eslint/core": "^0.11.0",
"@eslint/eslintrc": "^3.2.0",
- "@eslint/js": "9.18.0",
+ "@eslint/js": "9.20.0",
"@eslint/plugin-kit": "^0.2.5",
"@humanfs/node": "^0.16.6",
"@humanwhocodes/module-importer": "^1.0.1",
@@ -3217,6 +2957,19 @@
"url": "https://opencollective.com/eslint"
}
},
+ "node_modules/eslint/node_modules/@eslint/core": {
+ "version": "0.11.0",
+ "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.11.0.tgz",
+ "integrity": "sha512-DWUB2pksgNEb6Bz2fggIy1wh6fGgZP4Xyy/Mt0QZPiloKKXerbqq9D3SBQTlCRYOrcRPu4vuz+CGjwdfqxnoWA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@types/json-schema": "^7.0.15"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ }
+ },
"node_modules/eslint/node_modules/brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
@@ -3399,27 +3152,6 @@
"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
"license": "MIT"
},
- "node_modules/extract-zip": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz",
- "integrity": "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==",
- "dev": true,
- "license": "BSD-2-Clause",
- "dependencies": {
- "debug": "^4.1.1",
- "get-stream": "^5.1.0",
- "yauzl": "^2.10.0"
- },
- "bin": {
- "extract-zip": "cli.js"
- },
- "engines": {
- "node": ">= 10.17.0"
- },
- "optionalDependencies": {
- "@types/yauzl": "^2.9.1"
- }
- },
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -3438,16 +3170,6 @@
"integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==",
"dev": true
},
- "node_modules/fd-slicer": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz",
- "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "pend": "~1.2.0"
- }
- },
"node_modules/fecha": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz",
@@ -3637,36 +3359,6 @@
"integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
"license": "MIT"
},
- "node_modules/fs-minipass": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz",
- "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==",
- "license": "ISC",
- "dependencies": {
- "minipass": "^3.0.0"
- },
- "engines": {
- "node": ">= 8"
- }
- },
- "node_modules/fs-minipass/node_modules/minipass": {
- "version": "3.3.6",
- "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
- "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
- "license": "ISC",
- "dependencies": {
- "yallist": "^4.0.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/fs.realpath": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
- "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
- "license": "ISC"
- },
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
@@ -3690,74 +3382,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
- "node_modules/gauge": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz",
- "integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==",
- "deprecated": "This package is no longer supported.",
- "license": "ISC",
- "dependencies": {
- "aproba": "^1.0.3 || ^2.0.0",
- "color-support": "^1.1.2",
- "console-control-strings": "^1.0.0",
- "has-unicode": "^2.0.1",
- "object-assign": "^4.1.1",
- "signal-exit": "^3.0.0",
- "string-width": "^4.2.3",
- "strip-ansi": "^6.0.1",
- "wide-align": "^1.1.2"
- },
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/gauge/node_modules/ansi-regex": {
- "version": "5.0.1",
- "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
- "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
- "license": "MIT",
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/gauge/node_modules/emoji-regex": {
- "version": "8.0.0",
- "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
- "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
- "license": "MIT"
- },
- "node_modules/gauge/node_modules/signal-exit": {
- "version": "3.0.7",
- "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
- "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
- "license": "ISC"
- },
- "node_modules/gauge/node_modules/string-width": {
- "version": "4.2.3",
- "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
- "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
- "license": "MIT",
- "dependencies": {
- "emoji-regex": "^8.0.0",
- "is-fullwidth-code-point": "^3.0.0",
- "strip-ansi": "^6.0.1"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/gauge/node_modules/strip-ansi": {
- "version": "6.0.1",
- "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
- "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
- "license": "MIT",
- "dependencies": {
- "ansi-regex": "^5.0.1"
- },
- "engines": {
- "node": ">=8"
- }
- },
"node_modules/gaxios": {
"version": "5.1.3",
"resolved": "https://registry.npmjs.org/gaxios/-/gaxios-5.1.3.tgz",
@@ -3806,22 +3430,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
- "node_modules/get-stream": {
- "version": "5.2.0",
- "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",
- "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "pump": "^3.0.0"
- },
- "engines": {
- "node": ">=8"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
"node_modules/glob": {
"version": "10.4.5",
"resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz",
@@ -3855,10 +3463,11 @@
}
},
"node_modules/globals": {
- "version": "15.14.0",
- "resolved": "https://registry.npmjs.org/globals/-/globals-15.14.0.tgz",
- "integrity": "sha512-OkToC372DtlQeje9/zHIo5CT8lRP/FUgEOKBEhU4e0abL7J7CD24fD9ohiLN5hagG/kWCYj4K5oaxxtj2Z0Dig==",
+ "version": "15.15.0",
+ "resolved": "https://registry.npmjs.org/globals/-/globals-15.15.0.tgz",
+ "integrity": "sha512-7ACyT3wmyp3I61S4fG682L0VA2RGD9otkqGJIwNUMF1SWUombIIk+af1unuDYgMm082aHYwD+mzJvv9Iu8dsgg==",
"dev": true,
+ "license": "MIT",
"engines": {
"node": ">=18"
},
@@ -3878,32 +3487,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
- "node_modules/got": {
- "version": "11.8.6",
- "resolved": "https://registry.npmjs.org/got/-/got-11.8.6.tgz",
- "integrity": "sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@sindresorhus/is": "^4.0.0",
- "@szmarczak/http-timer": "^4.0.5",
- "@types/cacheable-request": "^6.0.1",
- "@types/responselike": "^1.0.0",
- "cacheable-lookup": "^5.0.3",
- "cacheable-request": "^7.0.2",
- "decompress-response": "^6.0.0",
- "http2-wrapper": "^1.0.0-beta.5.2",
- "lowercase-keys": "^2.0.0",
- "p-cancelable": "^2.0.0",
- "responselike": "^2.0.0"
- },
- "engines": {
- "node": ">=10.19.0"
- },
- "funding": {
- "url": "https://github.com/sindresorhus/got?sponsor=1"
- }
- },
"node_modules/handlebars": {
"version": "4.7.8",
"resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.8.tgz",
@@ -3947,12 +3530,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
- "node_modules/has-unicode": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz",
- "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==",
- "license": "ISC"
- },
"node_modules/hasown": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
@@ -3984,14 +3561,6 @@
"node": ">=18.0.0"
}
},
- "node_modules/hpagent": {
- "version": "0.1.2",
- "resolved": "https://registry.npmjs.org/hpagent/-/hpagent-0.1.2.tgz",
- "integrity": "sha512-ePqFXHtSQWAFXYmj+JtOTHr84iNrII4/QRlAAPPE+zqnKy4xJo7Ie1Y4kC7AdB+LxLxSTTzBMASsEcy0q8YyvQ==",
- "dev": true,
- "license": "MIT",
- "optional": true
- },
"node_modules/html-escaper": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",
@@ -4065,13 +3634,6 @@
"entities": "^4.4.0"
}
},
- "node_modules/http-cache-semantics": {
- "version": "4.1.1",
- "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz",
- "integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==",
- "dev": true,
- "license": "BSD-2-Clause"
- },
"node_modules/http-errors": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
@@ -4088,20 +3650,6 @@
"node": ">= 0.8"
}
},
- "node_modules/http2-wrapper": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-1.0.3.tgz",
- "integrity": "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "quick-lru": "^5.1.1",
- "resolve-alpn": "^1.0.0"
- },
- "engines": {
- "node": ">=10.19.0"
- }
- },
"node_modules/https-proxy-agent": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
@@ -4188,17 +3736,6 @@
"node": ">=0.8.19"
}
},
- "node_modules/inflight": {
- "version": "1.0.6",
- "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
- "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
- "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.",
- "license": "ISC",
- "dependencies": {
- "once": "^1.3.0",
- "wrappy": "1"
- }
- },
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
@@ -4206,9 +3743,10 @@
"license": "ISC"
},
"node_modules/ioredis": {
- "version": "5.4.2",
- "resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.4.2.tgz",
- "integrity": "sha512-0SZXGNGZ+WzISQ67QDyZ2x0+wVxjjUndtD8oSeik/4ajifeiRufed8fCb8QW8VMyi4MXcS+UO1k/0NGhvq1PAg==",
+ "version": "5.5.0",
+ "resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.5.0.tgz",
+ "integrity": "sha512-7CutT89g23FfSa8MDoIFs2GYYa0PaNiW/OrT+nRyjRXHDZd17HmIgy+reOQ/yhh72NznNjGuS8kbCAcA4Ro4mw==",
+ "license": "MIT",
"dependencies": {
"@ioredis/commands": "^1.1.1",
"cluster-key-slot": "^1.1.0",
@@ -4427,6 +3965,15 @@
"@pkgjs/parseargs": "^0.11.0"
}
},
+ "node_modules/jmespath": {
+ "version": "0.16.0",
+ "resolved": "https://registry.npmjs.org/jmespath/-/jmespath-0.16.0.tgz",
+ "integrity": "sha512-9FzQjJ7MATs1tSpnco1K6ayiYE3figslrXA72G2HQ/n76RzvYlofyi5QM+iX4YRs/pu3yzxlVQSST23+dMDknw==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">= 0.6.0"
+ }
+ },
"node_modules/joi": {
"version": "17.13.3",
"resolved": "https://registry.npmjs.org/joi/-/joi-17.13.3.tgz",
@@ -4678,13 +4225,6 @@
"integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==",
"license": "MIT"
},
- "node_modules/lodash.clonedeep": {
- "version": "4.5.0",
- "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz",
- "integrity": "sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/lodash.defaults": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz",
@@ -4811,16 +4351,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/lowercase-keys": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz",
- "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=8"
- }
- },
"node_modules/lru-cache": {
"version": "10.4.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
@@ -4847,30 +4377,6 @@
"qs": "^6.11.0"
}
},
- "node_modules/make-dir": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
- "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==",
- "license": "MIT",
- "dependencies": {
- "semver": "^6.0.0"
- },
- "engines": {
- "node": ">=8"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/make-dir/node_modules/semver": {
- "version": "6.3.1",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
- "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
- "license": "ISC",
- "bin": {
- "semver": "bin/semver.js"
- }
- },
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@@ -4958,16 +4464,6 @@
"node": ">= 0.6"
}
},
- "node_modules/mimic-response": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz",
- "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=4"
- }
- },
"node_modules/minimatch": {
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz",
@@ -5001,31 +4497,6 @@
"node": ">=16 || 14 >=14.17"
}
},
- "node_modules/minizlib": {
- "version": "2.1.2",
- "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz",
- "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==",
- "license": "MIT",
- "dependencies": {
- "minipass": "^3.0.0",
- "yallist": "^4.0.0"
- },
- "engines": {
- "node": ">= 8"
- }
- },
- "node_modules/minizlib/node_modules/minipass": {
- "version": "3.3.6",
- "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
- "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
- "license": "ISC",
- "dependencies": {
- "yallist": "^4.0.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
"node_modules/mjml": {
"version": "5.0.0-alpha.6",
"resolved": "https://registry.npmjs.org/mjml/-/mjml-5.0.0-alpha.6.tgz",
@@ -5515,9 +4986,9 @@
}
},
"node_modules/mongodb": {
- "version": "6.12.0",
- "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.12.0.tgz",
- "integrity": "sha512-RM7AHlvYfS7jv7+BXund/kR64DryVI+cHbVAy9P61fnb1RcWZqOW1/Wj2YhqMCx+MuYhqTRGv7AwHBzmsCKBfA==",
+ "version": "6.13.0",
+ "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.13.0.tgz",
+ "integrity": "sha512-KeESYR5TEaFxOuwRqkOm3XOsMqCSkdeDMjaW5u2nuKfX7rqaofp7JQGoi7sVqQcNJTKuveNbzZtWMstb8ABP6Q==",
"license": "Apache-2.0",
"dependencies": {
"@mongodb-js/saslprep": "^1.1.9",
@@ -5571,14 +5042,14 @@
}
},
"node_modules/mongoose": {
- "version": "8.9.5",
- "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-8.9.5.tgz",
- "integrity": "sha512-SPhOrgBm0nKV3b+IIHGqpUTOmgVL5Z3OO9AwkFEmvOZznXTvplbomstCnPOGAyungtRXE5pJTgKpKcZTdjeESg==",
+ "version": "8.10.1",
+ "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-8.10.1.tgz",
+ "integrity": "sha512-5beTeBZnJNndRXU9rxPol0JmTWZMAtgkPbooROkGilswvrZALDERY4cJrGZmgGwDS9dl0mxiB7si+Mv9Yms2fg==",
"license": "MIT",
"dependencies": {
"bson": "^6.10.1",
"kareem": "2.6.3",
- "mongodb": "~6.12.0",
+ "mongodb": "~6.13.0",
"mpath": "0.9.0",
"mquery": "5.0.0",
"ms": "2.1.3",
@@ -5714,40 +5185,6 @@
"integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==",
"license": "MIT"
},
- "node_modules/ngrok": {
- "version": "5.0.0-beta.2",
- "resolved": "https://registry.npmjs.org/ngrok/-/ngrok-5.0.0-beta.2.tgz",
- "integrity": "sha512-UzsyGiJ4yTTQLCQD11k1DQaMwq2/SsztBg2b34zAqcyjS25qjDpogMKPaCKHwe/APRTHeel3iDXcVctk5CNaCQ==",
- "dev": true,
- "hasInstallScript": true,
- "license": "BSD-2-Clause",
- "dependencies": {
- "extract-zip": "^2.0.1",
- "got": "^11.8.5",
- "lodash.clonedeep": "^4.5.0",
- "uuid": "^7.0.0 || ^8.0.0",
- "yaml": "^2.2.2"
- },
- "bin": {
- "ngrok": "bin/ngrok"
- },
- "engines": {
- "node": ">=14.2"
- },
- "optionalDependencies": {
- "hpagent": "^0.1.2"
- }
- },
- "node_modules/ngrok/node_modules/uuid": {
- "version": "8.3.2",
- "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
- "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
- "dev": true,
- "license": "MIT",
- "bin": {
- "uuid": "dist/bin/uuid"
- }
- },
"node_modules/nise": {
"version": "6.1.1",
"resolved": "https://registry.npmjs.org/nise/-/nise-6.1.1.tgz",
@@ -5778,12 +5215,6 @@
"integrity": "sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ==",
"license": "MIT"
},
- "node_modules/node-addon-api": {
- "version": "5.1.0",
- "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-5.1.0.tgz",
- "integrity": "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA==",
- "license": "MIT"
- },
"node_modules/node-fetch": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
@@ -5932,21 +5363,6 @@
"node": ">=4"
}
},
- "node_modules/nopt": {
- "version": "5.0.0",
- "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz",
- "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==",
- "license": "ISC",
- "dependencies": {
- "abbrev": "1"
- },
- "bin": {
- "nopt": "bin/nopt.js"
- },
- "engines": {
- "node": ">=6"
- }
- },
"node_modules/normalize-path": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
@@ -5956,32 +5372,6 @@
"node": ">=0.10.0"
}
},
- "node_modules/normalize-url": {
- "version": "6.1.0",
- "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz",
- "integrity": "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=10"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/npmlog": {
- "version": "5.0.1",
- "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz",
- "integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==",
- "deprecated": "This package is no longer supported.",
- "license": "ISC",
- "dependencies": {
- "are-we-there-yet": "^2.0.0",
- "console-control-strings": "^1.1.0",
- "gauge": "^3.0.0",
- "set-blocking": "^2.0.0"
- }
- },
"node_modules/nth-check": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz",
@@ -6027,6 +5417,15 @@
"node": ">= 0.8"
}
},
+ "node_modules/on-headers": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz",
+ "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
@@ -6062,16 +5461,6 @@
"node": ">= 0.8.0"
}
},
- "node_modules/p-cancelable": {
- "version": "2.1.1",
- "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz",
- "integrity": "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=8"
- }
- },
"node_modules/p-limit": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
@@ -6196,15 +5585,6 @@
"node": ">=8"
}
},
- "node_modules/path-is-absolute": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
- "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
- "license": "MIT",
- "engines": {
- "node": ">=0.10.0"
- }
- },
"node_modules/path-key": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
@@ -6246,13 +5626,6 @@
"node": ">= 14.16"
}
},
- "node_modules/pend": {
- "version": "1.2.0",
- "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",
- "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -6868,9 +6241,9 @@
}
},
"node_modules/prettier": {
- "version": "3.4.2",
- "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.4.2.tgz",
- "integrity": "sha512-e9MewbtFo+Fevyuxn/4rrcDAaq0IYxPGLvObpQjiZBMAzB9IGmzlnG9RZy3FFas+eBMu2vA0CszMeduow5dIuQ==",
+ "version": "3.5.1",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.5.1.tgz",
+ "integrity": "sha512-hPpFQvHwL3Qv5AdRvBFMhnKo4tYxp0ReXiPn2bxkiohEX6mBeBwEpBSQTkD458RaaDKQMYSp4hX4UtfUTA5wDw==",
"license": "MIT",
"bin": {
"prettier": "bin/prettier.cjs"
@@ -6972,19 +6345,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
- "node_modules/quick-lru": {
- "version": "5.1.1",
- "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz",
- "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=10"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
"node_modules/rambda": {
"version": "7.5.0",
"resolved": "https://registry.npmjs.org/rambda/-/rambda-7.5.0.tgz",
@@ -7087,13 +6447,6 @@
"node": ">=0.10.0"
}
},
- "node_modules/resolve-alpn": {
- "version": "1.2.1",
- "resolved": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.2.1.tgz",
- "integrity": "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/resolve-from": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
@@ -7103,78 +6456,6 @@
"node": ">=4"
}
},
- "node_modules/responselike": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.1.tgz",
- "integrity": "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "lowercase-keys": "^2.0.0"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/rimraf": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
- "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==",
- "deprecated": "Rimraf versions prior to v4 are no longer supported",
- "license": "ISC",
- "dependencies": {
- "glob": "^7.1.3"
- },
- "bin": {
- "rimraf": "bin.js"
- },
- "funding": {
- "url": "https://github.com/sponsors/isaacs"
- }
- },
- "node_modules/rimraf/node_modules/brace-expansion": {
- "version": "1.1.11",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
- "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
- "license": "MIT",
- "dependencies": {
- "balanced-match": "^1.0.0",
- "concat-map": "0.0.1"
- }
- },
- "node_modules/rimraf/node_modules/glob": {
- "version": "7.2.3",
- "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
- "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
- "deprecated": "Glob versions prior to v9 are no longer supported",
- "license": "ISC",
- "dependencies": {
- "fs.realpath": "^1.0.0",
- "inflight": "^1.0.4",
- "inherits": "2",
- "minimatch": "^3.1.1",
- "once": "^1.3.0",
- "path-is-absolute": "^1.0.0"
- },
- "engines": {
- "node": "*"
- },
- "funding": {
- "url": "https://github.com/sponsors/isaacs"
- }
- },
- "node_modules/rimraf/node_modules/minimatch": {
- "version": "3.1.2",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
- "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
- "license": "ISC",
- "dependencies": {
- "brace-expansion": "^1.1.7"
- },
- "engines": {
- "node": "*"
- }
- },
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
@@ -7295,12 +6576,6 @@
"node": ">= 0.8.0"
}
},
- "node_modules/set-blocking": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
- "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
- "license": "ISC"
- },
"node_modules/setprototypeof": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
@@ -7816,33 +7091,16 @@
"express": ">=4.0.0 || >=5.0.0-beta"
}
},
- "node_modules/tar": {
- "version": "6.2.1",
- "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz",
- "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==",
- "license": "ISC",
- "dependencies": {
- "chownr": "^2.0.0",
- "fs-minipass": "^2.0.0",
- "minipass": "^5.0.0",
- "minizlib": "^2.1.1",
- "mkdirp": "^1.0.3",
- "yallist": "^4.0.0"
- },
- "engines": {
- "node": ">=10"
- }
- },
"node_modules/tar-fs": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.0.1.tgz",
- "integrity": "sha512-6tzWDMeroL87uF/+lin46k+Q+46rAJ0SyPGz7OW7wTgblI273hsBqk2C1j0/xNadNLKDTUL9BukSjB7cwgmlPA==",
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz",
+ "integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==",
"license": "MIT",
"dependencies": {
"chownr": "^1.1.1",
"mkdirp-classic": "^0.5.2",
"pump": "^3.0.0",
- "tar-stream": "^2.0.0"
+ "tar-stream": "^2.1.4"
}
},
"node_modules/tar-fs/node_modules/chownr": {
@@ -7867,27 +7125,6 @@
"node": ">=6"
}
},
- "node_modules/tar/node_modules/minipass": {
- "version": "5.0.0",
- "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz",
- "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==",
- "license": "ISC",
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/tar/node_modules/mkdirp": {
- "version": "1.0.4",
- "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",
- "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==",
- "license": "MIT",
- "bin": {
- "mkdirp": "bin/cmd.js"
- },
- "engines": {
- "node": ">=10"
- }
- },
"node_modules/test-exclude": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-7.0.1.tgz",
@@ -8053,9 +7290,9 @@
"license": "MIT"
},
"node_modules/undici": {
- "version": "6.21.0",
- "resolved": "https://registry.npmjs.org/undici/-/undici-6.21.0.tgz",
- "integrity": "sha512-BUgJXc752Kou3oOIuU1i+yZZypyZRqNPW0vqoMPl8VaoalSfeR0D8/t4iAS3yirs79SSMTxTag+ZC86uswv+Cw==",
+ "version": "6.21.1",
+ "resolved": "https://registry.npmjs.org/undici/-/undici-6.21.1.tgz",
+ "integrity": "sha512-q/1rj5D0/zayJB2FraXdaWxbhWiNKDvu8naDT2dl1yTlvJp4BLtOcp2a5BvgGNQpYYJzau7tf1WgKv3b+7mqpQ==",
"license": "MIT",
"engines": {
"node": ">=18.17"
@@ -8377,56 +7614,6 @@
"node": ">= 8"
}
},
- "node_modules/wide-align": {
- "version": "1.1.5",
- "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz",
- "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==",
- "license": "ISC",
- "dependencies": {
- "string-width": "^1.0.2 || 2 || 3 || 4"
- }
- },
- "node_modules/wide-align/node_modules/ansi-regex": {
- "version": "5.0.1",
- "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
- "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
- "license": "MIT",
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/wide-align/node_modules/emoji-regex": {
- "version": "8.0.0",
- "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
- "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
- "license": "MIT"
- },
- "node_modules/wide-align/node_modules/string-width": {
- "version": "4.2.3",
- "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
- "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
- "license": "MIT",
- "dependencies": {
- "emoji-regex": "^8.0.0",
- "is-fullwidth-code-point": "^3.0.0",
- "strip-ansi": "^6.0.1"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/wide-align/node_modules/strip-ansi": {
- "version": "6.0.1",
- "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
- "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
- "license": "MIT",
- "dependencies": {
- "ansi-regex": "^5.0.1"
- },
- "engines": {
- "node": ">=8"
- }
- },
"node_modules/winston": {
"version": "3.17.0",
"resolved": "https://registry.npmjs.org/winston/-/winston-3.17.0.tgz",
@@ -8597,25 +7784,6 @@
"node": ">=10"
}
},
- "node_modules/yallist": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
- "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
- "license": "ISC"
- },
- "node_modules/yaml": {
- "version": "2.7.0",
- "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.7.0.tgz",
- "integrity": "sha512-+hSoy/QHluxmC9kCIJyL/uyFmLmc+e5CFR5Wa+bpIhIj85LVb9ZH2nVnqrHoSvKogwODv0ClqZkmiSSaIH5LTA==",
- "dev": true,
- "license": "ISC",
- "bin": {
- "yaml": "bin.mjs"
- },
- "engines": {
- "node": ">= 14"
- }
- },
"node_modules/yargs": {
"version": "17.7.2",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",
@@ -8700,17 +7868,6 @@
"node": ">=8"
}
},
- "node_modules/yauzl": {
- "version": "2.10.0",
- "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz",
- "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "buffer-crc32": "~0.2.3",
- "fd-slicer": "~1.1.0"
- }
- },
"node_modules/yocto-queue": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
diff --git a/Server/package.json b/server/package.json
old mode 100644
new mode 100755
similarity index 84%
rename from Server/package.json
rename to server/package.json
index 873f8ce67..097cf4443
--- a/Server/package.json
+++ b/server/package.json
@@ -17,22 +17,25 @@
"license": "ISC",
"dependencies": {
"axios": "^1.7.2",
- "bcrypt": "5.1.1",
- "bullmq": "5.35.1",
+ "bcryptjs": "3.0.2",
+ "bullmq": "5.41.2",
+ "compression": "1.8.0",
"cors": "^2.8.5",
- "dockerode": "4.0.4",
+ "dockerode": "4.0.6",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"handlebars": "^4.7.8",
"helmet": "^8.0.0",
"ioredis": "^5.4.2",
+ "jmespath": "^0.16.0",
"joi": "^17.13.1",
"jsonwebtoken": "9.0.2",
"mailersend": "^2.2.0",
"mjml": "^5.0.0-alpha.4",
"mongoose": "^8.3.3",
- "multer": "1.4.5-lts.1",
+ "multer": "^1.4.5-lts.1",
"nodemailer": "^6.9.14",
+ "papaparse": "^5.5.2",
"ping": "0.4.4",
"sharp": "0.33.5",
"ssl-checker": "2.0.10",
@@ -42,13 +45,12 @@
"devDependencies": {
"@eslint/js": "^9.17.0",
"c8": "10.1.3",
- "chai": "5.1.2",
+ "chai": "5.2.0",
"eslint": "^9.17.0",
"eslint-plugin-mocha": "^10.5.0",
"esm": "3.2.25",
"globals": "^15.14.0",
"mocha": "11.1.0",
- "ngrok": "5.0.0-beta.2",
"nodemon": "3.1.9",
"prettier": "^3.3.3",
"sinon": "19.0.2"
diff --git a/server/routes/announcementsRoute.js b/server/routes/announcementsRoute.js
new file mode 100755
index 000000000..0b234cb96
--- /dev/null
+++ b/server/routes/announcementsRoute.js
@@ -0,0 +1,38 @@
+import { Router } from "express";
+import { verifyJWT } from "../middleware/verifyJWT.js";
+import { isAllowed } from "../middleware/isAllowed.js";
+
+class AnnouncementRoutes {
+ constructor(controller) {
+ this.router = Router();
+ this.announcementController = controller;
+ this.initRoutes();
+ }
+
+ initRoutes() {
+ /**
+ * @route POST /
+ * @desc Create a new announcement
+ * @access Private (Requires JWT verification)
+ */
+ this.router.post(
+ "/",
+ verifyJWT,
+ isAllowed(["admin", "superadmin"]),
+ this.announcementController.createAnnouncement
+ );
+
+ /**
+ * @route GET /
+ * @desc Get announcements
+ * @access Public
+ */
+ this.router.get("/", this.announcementController.getAnnouncement);
+ }
+
+ getRouter() {
+ return this.router;
+ }
+}
+
+export default AnnouncementRoutes;
diff --git a/Server/routes/authRoute.js b/server/routes/authRoute.js
old mode 100644
new mode 100755
similarity index 95%
rename from Server/routes/authRoute.js
rename to server/routes/authRoute.js
index cebe9a211..aabd8de89
--- a/Server/routes/authRoute.js
+++ b/server/routes/authRoute.js
@@ -21,7 +21,6 @@ class AuthRoutes {
this.authController.registerUser
);
this.router.post("/login", this.authController.loginUser);
- this.router.post("/refresh", this.authController.refreshAuthToken);
this.router.put(
"/user/:userId",
diff --git a/Server/routes/checkRoute.js b/server/routes/checkRoute.js
old mode 100644
new mode 100755
similarity index 100%
rename from Server/routes/checkRoute.js
rename to server/routes/checkRoute.js
diff --git a/server/routes/diagnosticRoute.js b/server/routes/diagnosticRoute.js
new file mode 100755
index 000000000..c5ee7cdeb
--- /dev/null
+++ b/server/routes/diagnosticRoute.js
@@ -0,0 +1,28 @@
+import { Router } from "express";
+
+class DiagnosticRoutes {
+ constructor(diagnosticController) {
+ this.router = Router();
+ this.diagnosticController = diagnosticController;
+ this.initRoutes();
+ }
+ initRoutes() {
+ this.router.get(
+ "/db/execution-stats/:monitorId",
+ this.diagnosticController.getDistributedUptimeDbExecutionStats
+ );
+
+ this.router.get(
+ "/db/get-monitors-by-team-id/:teamId",
+ this.diagnosticController.getMonitorsByTeamIdExecutionStats
+ );
+
+ this.router.post("/db/stats", this.diagnosticController.getDbStats);
+ }
+
+ getRouter() {
+ return this.router;
+ }
+}
+
+export default DiagnosticRoutes;
diff --git a/server/routes/distributedUptimeRoute.js b/server/routes/distributedUptimeRoute.js
new file mode 100755
index 000000000..51e8086cb
--- /dev/null
+++ b/server/routes/distributedUptimeRoute.js
@@ -0,0 +1,44 @@
+import { Router } from "express";
+import { verifyJWT } from "../middleware/verifyJWT.js";
+class DistributedUptimeRoutes {
+ constructor(distributedUptimeController) {
+ this.router = Router();
+ this.distributedUptimeController = distributedUptimeController;
+ this.initRoutes();
+ }
+ initRoutes() {
+ this.router.post("/callback", this.distributedUptimeController.resultsCallback);
+
+ this.router.get(
+ "/monitors/:teamId/initial",
+ verifyJWT,
+ this.distributedUptimeController.getDistributedUptimeMonitors
+ );
+
+ this.router.get(
+ "/monitors/:teamId",
+ this.distributedUptimeController.subscribeToDistributedUptimeMonitors
+ );
+
+ this.router.get(
+ "/monitors/details/:monitorId/initial",
+ verifyJWT,
+ this.distributedUptimeController.getDistributedUptimeMonitorDetails
+ );
+ this.router.get(
+ "/monitors/details/public/:monitorId/initial",
+ this.distributedUptimeController.getDistributedUptimeMonitorDetails
+ );
+
+ this.router.get(
+ "/monitors/details/:monitorId",
+ this.distributedUptimeController.subscribeToDistributedUptimeMonitorDetails
+ );
+ }
+
+ getRouter() {
+ return this.router;
+ }
+}
+
+export default DistributedUptimeRoutes;
diff --git a/Server/routes/inviteRoute.js b/server/routes/inviteRoute.js
old mode 100644
new mode 100755
similarity index 83%
rename from Server/routes/inviteRoute.js
rename to server/routes/inviteRoute.js
index c66c573f1..301959389
--- a/Server/routes/inviteRoute.js
+++ b/server/routes/inviteRoute.js
@@ -14,8 +14,10 @@ class InviteRoutes {
"/",
isAllowed(["admin", "superadmin"]),
verifyJWT,
- this.inviteController.issueInvitation
+ this.inviteController.getInviteToken
);
+
+ this.router.post("/send", this.inviteController.sendInviteEmail);
this.router.post("/verify", this.inviteController.inviteVerifyController);
}
diff --git a/Server/routes/maintenanceWindowRoute.js b/server/routes/maintenanceWindowRoute.js
old mode 100644
new mode 100755
similarity index 100%
rename from Server/routes/maintenanceWindowRoute.js
rename to server/routes/maintenanceWindowRoute.js
diff --git a/Server/routes/monitorRoute.js b/server/routes/monitorRoute.js
old mode 100644
new mode 100755
similarity index 77%
rename from Server/routes/monitorRoute.js
rename to server/routes/monitorRoute.js
index 964bbee7a..f9ef460c6
--- a/Server/routes/monitorRoute.js
+++ b/server/routes/monitorRoute.js
@@ -1,7 +1,12 @@
import { Router } from "express";
import { isAllowed } from "../middleware/isAllowed.js";
+import multer from "multer";
import { fetchMonitorCertificate } from "../controllers/controllerUtils.js";
+const upload = multer({
+ storage: multer.memoryStorage() // Store file in memory as Buffer
+ });
+
class MonitorRoutes {
constructor(monitorController) {
this.router = Router();
@@ -34,6 +39,16 @@ class MonitorRoutes {
this.router.get("/team/:teamId", this.monitorController.getMonitorsByTeamId);
+ this.router.get(
+ "/summary/team/:teamId",
+ this.monitorController.getMonitorsAndSummaryByTeamId
+ );
+
+ this.router.get(
+ "/team/:teamId/with-checks",
+ this.monitorController.getMonitorsWithChecksByTeamId
+ );
+
this.router.get(
"/resolution/url",
isAllowed(["admin", "superadmin"]),
@@ -76,7 +91,20 @@ class MonitorRoutes {
this.monitorController.addDemoMonitors
);
+ this.router.post(
+ "/bulk",
+ isAllowed(["admin", "superadmin"]),
+ upload.single("csvFile"),
+ this.monitorController.createBulkMonitors
+ );
+
this.router.post("/seed", isAllowed(["superadmin"]), this.monitorController.seedDb);
+
+ this.router.post(
+ "/test-email",
+ isAllowed(["admin", "superadmin"]),
+ this.monitorController.sendTestEmail
+ );
}
getRouter() {
diff --git a/server/routes/notificationRoute.js b/server/routes/notificationRoute.js
new file mode 100755
index 000000000..7ea94843e
--- /dev/null
+++ b/server/routes/notificationRoute.js
@@ -0,0 +1,30 @@
+import { Router } from "express";
+import { verifyJWT } from "../middleware/verifyJWT.js";
+
+class NotificationRoutes {
+ constructor(notificationController) {
+ this.router = Router();
+ this.notificationController = notificationController;
+ this.initializeRoutes();
+ }
+
+ initializeRoutes() {
+ this.router.use(verifyJWT);
+
+ this.router.post(
+ "/trigger",
+ this.notificationController.triggerNotification
+ );
+
+ this.router.post(
+ "/test-webhook",
+ this.notificationController.testWebhook
+ );
+ }
+
+ getRouter() {
+ return this.router;
+ }
+}
+
+export default NotificationRoutes;
\ No newline at end of file
diff --git a/server/routes/queueRoute.js b/server/routes/queueRoute.js
new file mode 100755
index 000000000..38ac32a26
--- /dev/null
+++ b/server/routes/queueRoute.js
@@ -0,0 +1,52 @@
+import { Router } from "express";
+import { isAllowed } from "../middleware/isAllowed.js";
+class QueueRoutes {
+ constructor(queueController) {
+ this.router = Router();
+ this.queueController = queueController;
+ this.initRoutes();
+ }
+ initRoutes() {
+ this.router.get(
+ "/metrics",
+ isAllowed(["admin", "superadmin"]),
+ this.queueController.getMetrics
+ );
+
+ this.router.get(
+ "/jobs",
+ isAllowed(["admin", "superadmin"]),
+ this.queueController.getJobs
+ );
+
+ this.router.post(
+ "/jobs",
+ isAllowed(["admin", "superadmin"]),
+ this.queueController.addJob
+ );
+
+ this.router.post(
+ "/obliterate",
+ isAllowed(["admin", "superadmin"]),
+ this.queueController.obliterateQueue
+ );
+
+ this.router.post(
+ "/flush",
+ isAllowed(["admin", "superadmin"]),
+ this.queueController.flushQueue
+ );
+
+ this.router.get(
+ "/health",
+ isAllowed(["admin", "superadmin"]),
+ this.queueController.checkQueueHealth
+ );
+ }
+
+ getRouter() {
+ return this.router;
+ }
+}
+
+export default QueueRoutes;
diff --git a/Server/routes/settingsRoute.js b/server/routes/settingsRoute.js
old mode 100644
new mode 100755
similarity index 92%
rename from Server/routes/settingsRoute.js
rename to server/routes/settingsRoute.js
index 8da262427..a5501aaf3
--- a/Server/routes/settingsRoute.js
+++ b/server/routes/settingsRoute.js
@@ -12,7 +12,7 @@ class SettingsRoutes {
this.router.get("/", this.settingsController.getAppSettings);
this.router.put(
"/",
- isAllowed(["superadmin"]),
+ isAllowed(["admin", "superadmin"]),
this.settingsController.updateAppSettings
);
}
diff --git a/server/routes/statusPageRoute.js b/server/routes/statusPageRoute.js
new file mode 100755
index 000000000..bac960b08
--- /dev/null
+++ b/server/routes/statusPageRoute.js
@@ -0,0 +1,46 @@
+import { Router } from "express";
+import { verifyJWT } from "../middleware/verifyJWT.js";
+import multer from "multer";
+const upload = multer();
+
+class StatusPageRoutes {
+ constructor(statusPageController) {
+ this.router = Router();
+ this.statusPageController = statusPageController;
+ this.initRoutes();
+ }
+
+ initRoutes() {
+ this.router.get("/", this.statusPageController.getStatusPage);
+ this.router.get(
+ "/team/:teamId",
+ verifyJWT,
+ this.statusPageController.getStatusPagesByTeamId
+ );
+ this.router.get("/:url", this.statusPageController.getStatusPageByUrl);
+ this.router.get(
+ "/distributed/:url",
+ this.statusPageController.getDistributedStatusPageByUrl
+ );
+
+ this.router.post(
+ "/",
+ upload.single("logo"),
+ verifyJWT,
+ this.statusPageController.createStatusPage
+ );
+ this.router.put(
+ "/",
+ upload.single("logo"),
+ verifyJWT,
+ this.statusPageController.updateStatusPage
+ );
+ this.router.delete("/:url(*)", verifyJWT, this.statusPageController.deleteStatusPage);
+ }
+
+ getRouter() {
+ return this.router;
+ }
+}
+
+export default StatusPageRoutes;
diff --git a/server/service/bufferService.js b/server/service/bufferService.js
new file mode 100755
index 000000000..c98dde759
--- /dev/null
+++ b/server/service/bufferService.js
@@ -0,0 +1,95 @@
+const SERVICE_NAME = "BufferService";
+const BUFFER_TIMEOUT = 1000 * 60 * 1; // 1 minute
+const TYPE_MAP = {
+ http: "checks",
+ ping: "checks",
+ port: "checks",
+ docker: "checks",
+ pagespeed: "pagespeedChecks",
+ hardware: "hardwareChecks",
+ distributed_http: "distributedChecks",
+};
+
+class BufferService {
+ constructor({ db, logger }) {
+ this.db = db;
+ this.logger = logger;
+ this.SERVICE_NAME = SERVICE_NAME;
+ this.buffers = {
+ checks: [],
+ pagespeedChecks: [],
+ hardwareChecks: [],
+ distributedChecks: [],
+ };
+ this.OPERATION_MAP = {
+ checks: this.db.createChecks,
+ pagespeedChecks: this.db.createPageSpeedChecks,
+ hardwareChecks: this.db.createHardwareChecks,
+ distributedChecks: this.db.createDistributedChecks,
+ };
+
+ this.scheduleNextFlush();
+ this.logger.info({
+ message: `Buffer service initialized, flushing every ${BUFFER_TIMEOUT / 1000}s`,
+ service: this.SERVICE_NAME,
+ method: "constructor",
+ });
+ }
+ static SERVICE_NAME = SERVICE_NAME;
+
+ addToBuffer({ check, type }) {
+ try {
+ this.buffers[TYPE_MAP[type]].push(check);
+ } catch (error) {
+ this.logger.error({
+ message: error.message,
+ service: this.SERVICE_NAME,
+ method: "addToBuffer",
+ stack: error.stack,
+ });
+ }
+ }
+
+ scheduleNextFlush() {
+ this.bufferTimer = setTimeout(async () => {
+ try {
+ await this.flushBuffers();
+ } catch (error) {
+ this.logger.error({
+ message: `Error in flush cycle: ${error.message}`,
+ service: this.SERVICE_NAME,
+ method: "scheduleNextFlush",
+ stack: error.stack,
+ });
+ } finally {
+ // Schedule the next flush only after the current one completes
+ this.scheduleNextFlush();
+ }
+ }, BUFFER_TIMEOUT);
+ }
+ async flushBuffers() {
+ let items = 0;
+ for (const [bufferName, buffer] of Object.entries(this.buffers)) {
+ items += buffer.length;
+ const operation = this.OPERATION_MAP[bufferName];
+ if (!operation) {
+ this.logger.error({
+ message: `No operation found for ${bufferName}`,
+ service: this.SERVICE_NAME,
+ method: "flushBuffers",
+ });
+ continue;
+ }
+ await operation(buffer);
+ this.buffers[bufferName] = [];
+ }
+ this.logger.info({
+ message: `Flushed ${items} items`,
+ service: this.SERVICE_NAME,
+ method: "flushBuffers",
+ });
+ items = 0;
+ }
+}
+
+export default BufferService;
diff --git a/Server/service/emailService.js b/server/service/emailService.js
old mode 100644
new mode 100755
similarity index 89%
rename from Server/service/emailService.js
rename to server/service/emailService.js
index 3aeb2c8a8..94d19f0f4
--- a/Server/service/emailService.js
+++ b/server/service/emailService.js
@@ -29,7 +29,10 @@ class EmailService {
this.mjml2html = mjml2html;
this.nodemailer = nodemailer;
this.logger = logger;
+ this.init();
+ }
+ init = async () => {
/**
* Loads an email template from the filesystem.
*
@@ -67,28 +70,14 @@ class EmailService {
serverIsUpTemplate: this.loadTemplate("serverIsUp"),
passwordResetTemplate: this.loadTemplate("passwordReset"),
hardwareIncidentTemplate: this.loadTemplate("hardwareIncident"),
+ testEmailTemplate: this.loadTemplate("testEmailTemplate"),
};
/**
* The email transporter used to send emails.
* @type {Object}
*/
-
- const { systemEmailHost, systemEmailPort, systemEmailAddress, systemEmailPassword } =
- this.settingsService.getSettings();
-
- const emailConfig = {
- host: systemEmailHost,
- port: systemEmailPort,
- secure: true,
- auth: {
- user: systemEmailAddress,
- pass: systemEmailPassword,
- },
- };
-
- this.transporter = this.nodemailer.createTransport(emailConfig);
- }
+ };
/**
* Asynchronously builds and sends an email using a specified template and context.
@@ -100,6 +89,28 @@ class EmailService {
* @returns {Promise} A promise that resolves to the messageId of the sent email.
*/
buildAndSendEmail = async (template, context, to, subject) => {
+ // TODO - Consider an update transporter method so this only needs to be recreated when smtp settings change
+ const {
+ systemEmailHost,
+ systemEmailPort,
+ systemEmailUser,
+ systemEmailAddress,
+ systemEmailPassword,
+ } = await this.settingsService.getDBSettings();
+
+ const emailConfig = {
+ host: systemEmailHost,
+ port: systemEmailPort,
+ secure: true,
+ auth: {
+ user: systemEmailUser || systemEmailAddress,
+ pass: systemEmailPassword,
+ },
+ connectionTimeout: 5000,
+ };
+
+ this.transporter = this.nodemailer.createTransport(emailConfig);
+
const buildHtml = async (template, context) => {
try {
const mjml = this.templateLookup[template](context);
@@ -119,6 +130,7 @@ class EmailService {
try {
const info = await this.transporter.sendMail({
to: to,
+ from: systemEmailAddress,
subject: subject,
html: html,
});
diff --git a/Server/service/jobQueue.js b/server/service/jobQueue.js
old mode 100644
new mode 100755
similarity index 73%
rename from Server/service/jobQueue.js
rename to server/service/jobQueue.js
index 419785540..8f16f910d
--- a/Server/service/jobQueue.js
+++ b/server/service/jobQueue.js
@@ -1,6 +1,7 @@
-const QUEUE_NAMES = ["uptime", "pagespeed", "hardware"];
+const QUEUE_NAMES = ["uptime", "pagespeed", "hardware", "distributed"];
const SERVICE_NAME = "JobQueue";
const JOBS_PER_WORKER = 5;
+const HEALTH_CHECK_INTERVAL = 10 * 60 * 1000; // 10 minutes
const QUEUE_LOOKUP = {
hardware: "hardware",
http: "uptime",
@@ -8,34 +9,30 @@ const QUEUE_LOOKUP = {
port: "uptime",
docker: "uptime",
pagespeed: "pagespeed",
+ distributed_http: "distributed",
};
const getSchedulerId = (monitor) => `scheduler:${monitor.type}:${monitor._id}`;
-import { successMessages, errorMessages } from "../utils/messages.js";
class NewJobQueue {
static SERVICE_NAME = SERVICE_NAME;
- constructor(
+ constructor({
db,
statusService,
networkService,
notificationService,
settingsService,
+ stringService,
logger,
Queue,
- Worker
- ) {
- const settings = settingsService.getSettings() || {};
- const { redisHost = "127.0.0.1", redisPort = 6379 } = settings;
- const connection = {
- host: redisHost,
- port: redisPort,
- };
-
+ Worker,
+ redisService,
+ }) {
+ this.connection = redisService.getConnection();
this.queues = {};
this.workers = {};
+ this.lastJobProcessedTime = {};
- this.connection = connection;
this.db = db;
this.networkService = networkService;
this.statusService = statusService;
@@ -43,11 +40,44 @@ class NewJobQueue {
this.settingsService = settingsService;
this.logger = logger;
this.Worker = Worker;
+ this.stringService = stringService;
QUEUE_NAMES.forEach((name) => {
- this.queues[name] = new Queue(name, { connection });
+ const q = new Queue(name, { connection: this.connection });
+ this.lastJobProcessedTime[q.name] = Date.now();
+ q.on("error", (error) => {
+ this.logger.error({
+ message: error.message,
+ service: SERVICE_NAME,
+ method: "queue:error",
+ stack: error.stack,
+ });
+ });
+ this.queues[name] = q;
+
this.workers[name] = [];
});
+
+ this.healthCheckInterval = setInterval(async () => {
+ try {
+ const health = await this.checkQueueHealth();
+ if (health.stuck === true) {
+ this.logger.error({
+ message: `Queue is stuck: ${health.stuckQueues.join(", ")}`,
+ service: SERVICE_NAME,
+ method: "healthCheckInterval",
+ });
+ await this.flushQueue();
+ }
+ } catch (error) {
+ this.logger.error({
+ message: error.message,
+ service: SERVICE_NAME,
+ method: "periodicHealthCheck",
+ stack: error.stack,
+ });
+ }
+ }, HEALTH_CHECK_INTERVAL);
}
/**
@@ -59,6 +89,7 @@ class NewJobQueue {
* @returns {Promise}
*/
async initJobQueue() {
+ await this.connection.flushall();
const monitors = await this.db.getAllMonitors();
await Promise.all(
monitors
@@ -144,6 +175,8 @@ class NewJobQueue {
createJobHandler() {
return async (job) => {
try {
+ // Update the last job processed time for this queue
+ this.lastJobProcessedTime[job.queue.name] = Date.now();
// Get all maintenance windows for this monitor
await job.updateProgress(0);
const monitorId = job.data._id;
@@ -163,6 +196,12 @@ class NewJobQueue {
// Get the current status
await job.updateProgress(30);
const networkResponse = await this.networkService.getStatus(job);
+ if (
+ job.data.type === "distributed_http" ||
+ job.data.type === "distributed_test"
+ ) {
+ return;
+ }
// Handle status change
await job.updateProgress(60);
const { monitor, statusChanged, prevStatus } =
@@ -215,56 +254,54 @@ class NewJobQueue {
* @throws {Error} If worker creation fails or connection is invalid
*/
createWorker(queue) {
- const worker = new this.Worker(queue.name, this.createJobHandler(), {
- connection: this.connection,
- concurrency: 5,
- });
+ try {
+ const worker = new this.Worker(queue.name, this.createJobHandler(), {
+ connection: this.connection,
+ concurrency: 5,
+ stalledInterval: 10000,
+ maxStalledCount: 1,
+ lockDuration: 60000,
+ });
- // worker.on("active", (job) => {
- // this.logger.info({
- // message: `Worker started processing job: ${job.id}`,
- // service: SERVICE_NAME,
- // method: "createWorker",
- // });
- // });
+ worker.on("failed", (job, err) => {
+ this.logger.error({
+ message: `Job ${job.id} failed: ${err.message}`,
+ service: SERVICE_NAME,
+ method: "worker:failed",
+ stack: err.stack,
+ jobData: job.data,
+ });
+ });
+ worker.on("error", (job, err) => {
+ this.logger.error({
+ message: `Job ${job.id} error: ${err.message}`,
+ service: SERVICE_NAME,
+ method: "worker:error",
+ stack: err.stack,
+ jobData: job.data,
+ });
+ });
- // worker.on("completed", (job) => {
- // this.logger.info({
- // message: `Worker completed job: ${job.id}`,
- // service: SERVICE_NAME,
- // method: "createWorker",
- // });
- // });
+ worker.on("stalled", (jobId) => {
+ this.logger.warn({
+ message: `Job ${jobId} stalled`,
+ service: SERVICE_NAME,
+ method: "worker:stalled",
+ });
+ });
- // // Log job progress updates
- // worker.on("progress", (job, progress) => {
- // this.logger.info({
- // message: `Job progress: ${job.id}`,
- // service: SERVICE_NAME,
- // method: "createWorker",
- // details: `Progress: ${progress}%`,
- // });
- // });
-
- // // Log when a job fails
- // worker.on("failed", (job, err) => {
- // this.logger.error({
- // message: `Worker failed job: ${job.id}`,
- // service: SERVICE_NAME,
- // method: "createWorker",
- // details: `Error: ${err.message}`,
- // stack: err.stack,
- // });
- // });
-
- // worker.on("stalled", (jobId) => {
- // this.logger.warn({
- // message: `Worker stalled job: ${jobId}`,
- // service: SERVICE_NAME,
- // method: "createWorker",
- // });
- // });
- return worker;
+ return worker;
+ } catch (error) {
+ this.logger.error({
+ message: error.message,
+ service: SERVICE_NAME,
+ method: "createWorker",
+ stack: error.stack,
+ });
+ error.service = SERVICE_NAME;
+ error.method = "createWorker";
+ throw error;
+ }
}
/**
@@ -392,7 +429,6 @@ class NewJobQueue {
const jobs = await queue.getJobs();
const ret = await Promise.all(
jobs.map(async (job) => {
- console.log(job);
const state = await job.getState();
return { url: job.data.url, state, progress: job.progress };
})
@@ -497,7 +533,7 @@ class NewJobQueue {
if (wasDeleted === true) {
this.logger.info({
- message: successMessages.JOB_QUEUE_DELETE_JOB,
+ message: this.stringService.jobQueueDeleteJob,
service: SERVICE_NAME,
method: "deleteJob",
details: `Deleted job ${monitor._id}`,
@@ -506,7 +542,7 @@ class NewJobQueue {
await this.scaleWorkers(workerStats, queue);
} else {
this.logger.error({
- message: errorMessages.JOB_QUEUE_DELETE_JOB,
+ message: this.stringService.jobQueueDeleteJob,
service: SERVICE_NAME,
method: "deleteJob",
details: `Failed to delete job ${monitor._id}`,
@@ -596,6 +632,12 @@ class NewJobQueue {
service: SERVICE_NAME,
method: "obliterate",
});
+
+ if (this.healthCheckInterval) {
+ clearInterval(this.healthCheckInterval);
+ this.healthCheckInterval = null;
+ }
+
await Promise.all(
QUEUE_NAMES.map(async (name) => {
const queue = this.queues[name];
@@ -629,7 +671,7 @@ class NewJobQueue {
const metrics = await this.getMetrics();
this.logger.info({
- message: successMessages.JOB_QUEUE_OBLITERATE,
+ message: this.stringService.jobQueueObliterate,
service: SERVICE_NAME,
method: "obliterate",
details: metrics,
@@ -641,6 +683,132 @@ class NewJobQueue {
throw error;
}
}
+
+ // **************************
+ // Queue Health Checks
+ // **************************
+ async getKeyValuePairs() {
+ try {
+ // Get all keys
+ const keys = await this.connection.keys("*");
+
+ if (keys.length === 0) {
+ return {}; // Return an empty object if no keys are found
+ }
+
+ // Get values for all keys
+ const values = await this.connection.mget(keys);
+
+ // Combine keys and values into an object
+ const keyValuePairs = keys.reduce((result, key, index) => {
+ result[key] = values[index];
+ return result;
+ }, {});
+ this.logger.info({
+ message: "Redis key-value",
+ service: SERVICE_NAME,
+ method: "flushQueue",
+ details: keyValuePairs,
+ });
+ return keyValuePairs;
+ } catch (error) {
+ error.service === undefined ? (error.service = SERVICE_NAME) : null;
+ error.method === undefined ? (error.method = "getKeyValuePairs") : null;
+ throw error;
+ }
+ }
+
+ async flushQueue() {
+ try {
+ const keyValuePairs = await this.getKeyValuePairs();
+ this.logger.info({
+ message: "Before flush",
+ service: SERVICE_NAME,
+ method: "flushQueue",
+ details: keyValuePairs,
+ });
+ const flushResult = await this.connection.flushall();
+ const keyValuePairsAfter = await this.getKeyValuePairs();
+ this.logger.info({
+ message: "After flush",
+ service: SERVICE_NAME,
+ method: "flushQueue",
+ details: keyValuePairsAfter,
+ });
+ if (flushResult !== "OK") {
+ throw new Error("Failed to flush queue");
+ }
+ await this.initJobQueue();
+ return {
+ keyValuePairs,
+ flush: flushResult,
+ keyValuePairsAfter,
+ init: true,
+ };
+ } catch (error) {
+ error.service === undefined ? (error.service = SERVICE_NAME) : null;
+ error.method === undefined ? (error.method = "flushQueue") : null;
+ throw error;
+ }
+ }
+
+ /**
+ * Gets metrics for a specific queue
+ * @async
+ * @function getQueueHealthMetrics
+ * @param {Queue} queue - The queue to get metrics for
+ * @returns {Promise} Queue metrics
+ */
+ async getQueueHealthMetrics(queue) {
+ return await queue.getJobCounts();
+ }
+
+ getQueueIdleTimes() {
+ const now = Date.now();
+ const idleTimes = {};
+ Object.entries(this.lastJobProcessedTime).forEach(([queueName, lastProcessed]) => {
+ idleTimes[queueName] = now - lastProcessed;
+ });
+ return idleTimes;
+ }
+ async checkQueueHealth() {
+ try {
+ const currentTime = Date.now();
+ const stuckQueues = [];
+ const idleTimes = this.getQueueIdleTimes();
+ for (const queueName of QUEUE_NAMES) {
+ const queue = this.queues[queueName];
+
+ const jobCounts = await this.getQueueHealthMetrics(queue);
+ const hasJobs = Object.values(jobCounts).some((count) => count > 0);
+
+ const timeSinceLastProcessed = currentTime - this.lastJobProcessedTime[queueName];
+ const isStuck = hasJobs && timeSinceLastProcessed > HEALTH_CHECK_INTERVAL;
+
+ if (isStuck) {
+ stuckQueues.push(queueName);
+ }
+ }
+
+ const queueHealth = { stuck: false, stuckQueues, idleTimes };
+
+ if (stuckQueues.length > 0) {
+ queueHealth.stuck = true;
+ }
+
+ this.logger.info({
+ message: "Queue health check",
+ service: SERVICE_NAME,
+ method: "checkQueueHealth",
+ details: queueHealth,
+ });
+ return queueHealth;
+ } catch (error) {
+ error.service === undefined ? (error.service = SERVICE_NAME) : null;
+ error.method === undefined ? (error.method = "checkQueueHealth") : null;
+ throw error;
+ }
+ }
}
export default NewJobQueue;
diff --git a/Server/service/networkService.js b/server/service/networkService.js
old mode 100644
new mode 100755
similarity index 70%
rename from Server/service/networkService.js
rename to server/service/networkService.js
index 54edf39f9..9be1f2d85
--- a/Server/service/networkService.js
+++ b/server/service/networkService.js
@@ -1,5 +1,8 @@
-import { errorMessages, successMessages } from "../utils/messages.js";
+import jmespath from "jmespath";
+import https from "https";
+
const SERVICE_NAME = "NetworkService";
+const UPROCK_ENDPOINT = "https://api.uprock.com/checkmate/push";
/**
* Constructs a new NetworkService instance.
@@ -12,13 +15,16 @@ const SERVICE_NAME = "NetworkService";
*/
class NetworkService {
static SERVICE_NAME = SERVICE_NAME;
- constructor(axios, ping, logger, http, Docker, net) {
+
+ constructor(axios, ping, logger, http, Docker, net, stringService, settingsService) {
this.TYPE_PING = "ping";
this.TYPE_HTTP = "http";
this.TYPE_PAGESPEED = "pagespeed";
this.TYPE_HARDWARE = "hardware";
this.TYPE_DOCKER = "docker";
this.TYPE_PORT = "port";
+ this.TYPE_DISTRIBUTED_HTTP = "distributed_http";
+ this.TYPE_DISTRIBUTED_TEST = "distributed_test";
this.SERVICE_NAME = SERVICE_NAME;
this.NETWORK_ERROR = 5000;
this.PING_ERROR = 5001;
@@ -28,6 +34,8 @@ class NetworkService {
this.http = http;
this.Docker = Docker;
this.net = net;
+ this.stringService = stringService;
+ this.settingsService = settingsService;
}
/**
@@ -85,13 +93,13 @@ class NetworkService {
if (error) {
pingResponse.status = false;
pingResponse.code = this.PING_ERROR;
- pingResponse.message = errorMessages.PING_CANNOT_RESOLVE;
+ pingResponse.message = "No response";
return pingResponse;
}
pingResponse.code = 200;
pingResponse.status = response.alive;
- pingResponse.message = successMessages.PING_SUCCESS;
+ pingResponse.message = "Success";
return pingResponse;
} catch (error) {
error.service = this.SERVICE_NAME;
@@ -119,20 +127,36 @@ class NetworkService {
*/
async requestHttp(job) {
try {
- const url = job.data.url;
+ const {
+ url,
+ secret,
+ _id,
+ name,
+ teamId,
+ type,
+ ignoreTlsErrors,
+ jsonPath,
+ matchMethod,
+ expectedValue,
+ } = job.data;
const config = {};
- job.data.secret !== undefined &&
- (config.headers = { Authorization: `Bearer ${job.data.secret}` });
+ secret !== undefined && (config.headers = { Authorization: `Bearer ${secret}` });
+
+ if (ignoreTlsErrors === true) {
+ config.httpsAgent = new https.Agent({
+ rejectUnauthorized: false,
+ });
+ }
const { response, responseTime, error } = await this.timeRequest(() =>
this.axios.get(url, config)
);
const httpResponse = {
- monitorId: job.data._id,
- teamId: job.data.teamId,
- type: job.data.type,
+ monitorId: _id,
+ teamId,
+ type,
responseTime,
payload: response?.data,
};
@@ -141,12 +165,65 @@ class NetworkService {
const code = error.response?.status || this.NETWORK_ERROR;
httpResponse.code = code;
httpResponse.status = false;
- httpResponse.message = this.http.STATUS_CODES[code] || "Network Error";
+ httpResponse.message =
+ this.http.STATUS_CODES[code] || this.stringService.httpNetworkError;
return httpResponse;
}
- httpResponse.status = true;
+
httpResponse.code = response.status;
- httpResponse.message = this.http.STATUS_CODES[response.status];
+
+ if (!expectedValue) {
+ // not configure expected value, return
+ httpResponse.status = true;
+ httpResponse.message = this.http.STATUS_CODES[response.status];
+ return httpResponse;
+ }
+
+ // validate if response data match expected value
+ let result = response?.data;
+
+ this.logger.info({
+ service: this.SERVICE_NAME,
+ method: "requestHttp",
+ message: `Job: [${name}](${_id}) match result with expected value`,
+ details: { expectedValue, result, jsonPath, matchMethod },
+ });
+
+ if (jsonPath) {
+ const contentType = response.headers["content-type"];
+
+ const isJson = contentType?.includes("application/json");
+ if (!isJson) {
+ httpResponse.status = false;
+ httpResponse.message = this.stringService.httpNotJson;
+ return httpResponse;
+ }
+
+ try {
+ result = jmespath.search(result, jsonPath);
+ } catch (error) {
+ httpResponse.status = false;
+ httpResponse.message = this.stringService.httpJsonPathError;
+ return httpResponse;
+ }
+ }
+
+ if (result === null || result === undefined) {
+ httpResponse.status = false;
+ httpResponse.message = this.stringService.httpEmptyResult;
+ return httpResponse;
+ }
+
+ let match;
+ result = typeof result === "object" ? JSON.stringify(result) : result.toString();
+ if (matchMethod === "include") match = result.includes(expectedValue);
+ else if (matchMethod === "regex") match = new RegExp(expectedValue).test(result);
+ else match = result === expectedValue;
+
+ httpResponse.status = match;
+ httpResponse.message = match
+ ? this.stringService.httpMatchSuccess
+ : this.stringService.httpMatchFail;
return httpResponse;
} catch (error) {
error.service = this.SERVICE_NAME;
@@ -175,7 +252,20 @@ class NetworkService {
try {
const url = job.data.url;
const updatedJob = { ...job };
- const pagespeedUrl = `https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed?url=${url}&category=seo&category=accessibility&category=best-practices&category=performance`;
+ let pagespeedUrl = `https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed?url=${url}&category=seo&category=accessibility&category=best-practices&category=performance`;
+
+ const dbSettings = await this.settingsService.getDBSettings();
+ if (dbSettings?.pagespeedApiKey) {
+ pagespeedUrl += `&key=${dbSettings.pagespeedApiKey}`;
+ } else {
+ this.logger.info({
+ message: "Pagespeed API key not found",
+ service: this.SERVICE_NAME,
+ method: "requestPagespeed",
+ details: { url },
+ });
+ return;
+ }
updatedJob.data.url = pagespeedUrl;
return await this.requestHttp(updatedJob);
} catch (error) {
@@ -238,7 +328,7 @@ class NetworkService {
const containers = await docker.listContainers({ all: true });
const containerExists = containers.some((c) => c.Id.startsWith(job.data.url));
if (!containerExists) {
- throw new Error(errorMessages.DOCKER_NOT_FOUND);
+ throw new Error(this.stringService.dockerNotFound);
}
const container = docker.getContainer(job.data.url);
@@ -255,12 +345,13 @@ class NetworkService {
if (error) {
dockerResponse.status = false;
dockerResponse.code = error.statusCode || this.NETWORK_ERROR;
- dockerResponse.message = error.reason || errorMessages.DOCKER_FAIL;
+ dockerResponse.message =
+ error.reason || "Failed to fetch Docker container information";
return dockerResponse;
}
dockerResponse.status = response?.State?.Status === "running" ? true : false;
dockerResponse.code = 200;
- dockerResponse.message = successMessages.DOCKER_SUCCESS;
+ dockerResponse.message = "Docker container status fetched successfully";
return dockerResponse;
} catch (error) {
error.service = this.SERVICE_NAME;
@@ -308,13 +399,13 @@ class NetworkService {
if (error) {
portResponse.status = false;
portResponse.code = this.NETWORK_ERROR;
- portResponse.message = errorMessages.PORT_FAIL;
+ portResponse.message = this.stringService.portFail;
return portResponse;
}
portResponse.status = response.success;
portResponse.code = 200;
- portResponse.message = successMessages.PORT_SUCCESS;
+ portResponse.message = this.stringService.portSuccess;
return portResponse;
} catch (error) {
error.service = this.SERVICE_NAME;
@@ -323,6 +414,41 @@ class NetworkService {
}
}
+ async requestDistributedHttp(job) {
+ try {
+ const monitor = job.data;
+ const CALLBACK_URL = process.env.CALLBACK_URL;
+
+ const response = await this.axios.post(
+ UPROCK_ENDPOINT,
+ {
+ id: monitor._id,
+ url: monitor.url,
+ callback: `${CALLBACK_URL}/api/v1/distributed-uptime/callback`,
+ },
+ {
+ headers: {
+ "Content-Type": "application/json",
+ "x-checkmate-key": process.env.UPROCK_API_KEY,
+ },
+ }
+ );
+ if (response.data.success === false) {
+ throw new Error(response.data.message);
+ }
+ } catch (error) {
+ this.logger.error({
+ message: "Error in requestDistributedHttp",
+ service: this.SERVICE_NAME,
+ method: "requestDistributedHttp",
+ stack: error.stack,
+ });
+ error.service = this.SERVICE_NAME;
+ error.method = "requestDistributedHttp";
+ throw error;
+ }
+ }
+
/**
* Handles unsupported job types by throwing an error with details.
*
@@ -336,6 +462,44 @@ class NetworkService {
throw err;
}
+ async requestWebhook(platform, url, message) {
+ try {
+ const response = await this.axios.post(url, message, {
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+
+ return {
+ type: "webhook",
+ status: true,
+ code: response.status,
+ message: `Successfully sent ${platform} notification`,
+ payload: response.data,
+ };
+ } catch (error) {
+ this.logger.warn({
+ message: error.message,
+ service: this.SERVICE_NAME,
+ method: "requestWebhook",
+ url,
+ platform,
+ error: error.message,
+ statusCode: error.response?.status,
+ responseData: error.response?.data,
+ requestPayload: message,
+ });
+
+ return {
+ type: "webhook",
+ status: false,
+ code: error.response?.status || this.NETWORK_ERROR,
+ message: `Failed to send ${platform} notification`,
+ payload: error.response?.data,
+ };
+ }
+ }
+
/**
* Gets the status of a job based on its type and returns the appropriate response.
*
@@ -360,7 +524,10 @@ class NetworkService {
return await this.requestDocker(job);
case this.TYPE_PORT:
return await this.requestPort(job);
-
+ case this.TYPE_DISTRIBUTED_HTTP:
+ return await this.requestDistributedHttp(job);
+ case this.TYPE_DISTRIBUTED_TEST:
+ return;
default:
return this.handleUnsupportedType(type);
}
diff --git a/server/service/notificationService.js b/server/service/notificationService.js
new file mode 100755
index 000000000..624056694
--- /dev/null
+++ b/server/service/notificationService.js
@@ -0,0 +1,335 @@
+const SERVICE_NAME = "NotificationService";
+const TELEGRAM_API_BASE_URL = "https://api.telegram.org/bot";
+const PLATFORM_TYPES = ["telegram", "slack", "discord"];
+
+const MESSAGE_FORMATTERS = {
+ telegram: (messageText, chatId) => ({ chat_id: chatId, text: messageText }),
+ slack: (messageText) => ({ text: messageText }),
+ discord: (messageText) => ({ content: messageText }),
+};
+
+class NotificationService {
+ static SERVICE_NAME = SERVICE_NAME;
+ /**
+ * Creates an instance of NotificationService.
+ *
+ * @param {Object} emailService - The email service used for sending notifications.
+ * @param {Object} db - The database instance for storing notification data.
+ * @param {Object} logger - The logger instance for logging activities.
+ * @param {Object} networkService - The network service for sending webhook notifications.
+ */
+ constructor(emailService, db, logger, networkService, stringService) {
+ this.SERVICE_NAME = SERVICE_NAME;
+ this.emailService = emailService;
+ this.db = db;
+ this.logger = logger;
+ this.networkService = networkService;
+ this.stringService = stringService;
+ }
+
+ /**
+ * Formats a notification message based on the monitor status and platform.
+ *
+ * @param {Object} monitor - The monitor object.
+ * @param {string} monitor.name - The name of the monitor.
+ * @param {string} monitor.url - The URL of the monitor.
+ * @param {boolean} status - The current status of the monitor (true for up, false for down).
+ * @param {string} platform - The notification platform (e.g., "telegram", "slack", "discord").
+ * @param {string} [chatId] - The chat ID for platforms that require it (e.g., Telegram).
+ * @returns {Object|null} The formatted message object for the specified platform, or null if the platform is unsupported.
+ */
+
+ formatNotificationMessage(monitor, status, platform, chatId, code, timestamp) {
+ // Format timestamp using the local system timezone
+ const formatTime = (timestamp) => {
+ const date = new Date(timestamp);
+
+ // Get timezone abbreviation and format the date
+ const timeZoneAbbr = date.toLocaleTimeString('en-US', { timeZoneName: 'short' })
+ .split(' ').pop();
+
+ // Format the date with readable format
+ return date.toLocaleString('en-US', {
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ hour12: false
+ }).replace(/(\d+)\/(\d+)\/(\d+),\s/, '$3-$1-$2 ') + ' ' + timeZoneAbbr;
+ };
+
+ // Get formatted time
+ const formattedTime = timestamp
+ ? formatTime(timestamp)
+ : formatTime(new Date().getTime());
+
+ // Create different messages based on status with extra spacing
+ let messageText;
+ if (status === true) {
+ messageText = this.stringService.monitorUpAlert
+ .replace("{monitorName}", monitor.name)
+ .replace("{time}", formattedTime)
+ .replace("{code}", code || 'Unknown');
+ } else {
+ messageText = this.stringService.monitorDownAlert
+ .replace("{monitorName}", monitor.name)
+ .replace("{time}", formattedTime)
+ .replace("{code}", code || 'Unknown');
+ }
+
+ if (!PLATFORM_TYPES.includes(platform)) {
+ return undefined;
+ }
+
+ return MESSAGE_FORMATTERS[platform](messageText, chatId);
+ }
+
+ /**
+ * Sends a webhook notification to a specified platform.
+ *
+ * @param {Object} networkResponse - The response object from the network.
+ * @param {Object} networkResponse.monitor - The monitor object.
+ * @param {boolean} networkResponse.status - The monitor's status (true for up, false for down).
+ * @param {Object} notification - The notification settings.
+ * @param {string} notification.platform - The target platform ("telegram", "slack", "discord").
+ * @param {Object} notification.config - The configuration object for the webhook.
+ * @param {string} notification.config.webhookUrl - The webhook URL for the platform.
+ * @param {string} [notification.config.botToken] - The bot token for Telegram notifications.
+ * @param {string} [notification.config.chatId] - The chat ID for Telegram notifications.
+ * @returns {Promise} A promise that resolves to true if the notification was sent successfully, otherwise false.
+ */
+
+ async sendWebhookNotification(networkResponse, notification) {
+ const { monitor, status, code } = networkResponse;
+ const { platform } = notification;
+ const { webhookUrl, botToken, chatId } = notification.config;
+
+ // Early return if platform is not supported
+ if (!PLATFORM_TYPES.includes(platform)) {
+ this.logger.warn({
+ message: this.stringService.getWebhookUnsupportedPlatform(platform),
+ service: this.SERVICE_NAME,
+ method: "sendWebhookNotification",
+ details: { platform }
+ });
+ return false;
+ }
+
+ // Early return for telegram if required fields are missing
+ if (platform === "telegram" && (!botToken || !chatId)) {
+ this.logger.warn({
+ message: "Missing required fields for Telegram notification",
+ service: this.SERVICE_NAME,
+ method: "sendWebhookNotification",
+ details: { platform }
+ });
+ return false;
+ }
+
+ let url = webhookUrl;
+ if (platform === "telegram") {
+ url = `${TELEGRAM_API_BASE_URL}${botToken}/sendMessage`;
+ }
+
+ const message = this.formatNotificationMessage(
+ monitor,
+ status,
+ platform,
+ chatId,
+ code, // Pass the code field directly
+ networkResponse.timestamp
+ );
+
+ try {
+ const response = await this.networkService.requestWebhook(platform, url, message);
+ return response.status;
+ } catch (error) {
+ this.logger.error({
+ message: this.stringService.getWebhookSendError(platform),
+ service: this.SERVICE_NAME,
+ method: "sendWebhookNotification",
+ stack: error.stack,
+ });
+ return false;
+ }
+ }
+
+ /**
+ * Sends an email notification for hardware infrastructure alerts
+ *
+ * @async
+ * @function sendHardwareEmail
+ * @param {Object} networkResponse - Response object containing monitor information
+ * @param {string} address - Email address to send the notification to
+ * @param {Array} [alerts=[]] - List of hardware alerts to include in the email
+ * @returns {Promise} - Indicates whether email was sent successfully
+ * @throws {Error}
+ */
+ async sendHardwareEmail(networkResponse, address, alerts = []) {
+ if (alerts.length === 0) return false;
+ const { monitor, status, prevStatus } = networkResponse;
+ const template = "hardwareIncidentTemplate";
+ const context = { monitor: monitor.name, url: monitor.url, alerts };
+ const subject = `Monitor ${monitor.name} infrastructure alerts`;
+ this.emailService.buildAndSendEmail(template, context, address, subject);
+ return true;
+ }
+
+ /**
+ * Sends an email notification about monitor status change
+ *
+ * @async
+ * @function sendEmail
+ * @param {Object} networkResponse - Response object containing monitor status information
+ * @param {string} address - Email address to send the notification to
+ * @returns {Promise} - Indicates email was sent successfully
+ */
+ async sendEmail(networkResponse, address) {
+ const { monitor, status, prevStatus } = networkResponse;
+ const template = prevStatus === false ? "serverIsUpTemplate" : "serverIsDownTemplate";
+ const context = { monitor: monitor.name, url: monitor.url };
+ const subject = `Monitor ${monitor.name} is ${status === true ? "up" : "down"}`;
+ this.emailService.buildAndSendEmail(template, context, address, subject);
+ return true;
+ }
+
+ async handleStatusNotifications(networkResponse) {
+ try {
+ // If status hasn't changed, we're done
+ if (networkResponse.statusChanged === false) return false;
+ // if prevStatus is undefined, monitor is resuming, we're done
+ if (networkResponse.prevStatus === undefined) return false;
+
+ const notifications = await this.db.getNotificationsByMonitorId(
+ networkResponse.monitorId
+ );
+
+ for (const notification of notifications) {
+ if (notification.type === "email") {
+ await this.sendEmail(networkResponse, notification.address);
+ } else if (notification.type === "webhook") {
+ await this.sendWebhookNotification(networkResponse, notification);
+ }
+ // Handle other types of notifications here
+ }
+ return true;
+ } catch (error) {
+ this.logger.error({
+ message: error.message,
+ service: this.SERVICE_NAME,
+ method: "handleNotifications",
+ stack: error.stack,
+ });
+ }
+ }
+ /**
+ * Handles status change notifications for a monitor
+ *
+ * @async
+ * @function handleStatusNotifications
+ * @param {Object} networkResponse - Response object containing monitor status information
+ * @returns {Promise} - Indicates whether notifications were processed
+ * @throws {Error}
+ */
+ async handleHardwareNotifications(networkResponse) {
+ const thresholds = networkResponse?.monitor?.thresholds;
+ if (thresholds === undefined) return false; // No thresholds set, we're done
+
+ // Get thresholds from monitor
+ const {
+ usage_cpu: cpuThreshold = -1,
+ usage_memory: memoryThreshold = -1,
+ usage_disk: diskThreshold = -1,
+ } = thresholds;
+
+ // Get metrics from response
+ const metrics = networkResponse?.payload?.data ?? null;
+ if (metrics === null) return false;
+
+ const {
+ cpu: { usage_percent: cpuUsage = -1 } = {},
+ memory: { usage_percent: memoryUsage = -1 } = {},
+ disk = [],
+ } = metrics;
+
+ const alerts = {
+ cpu: cpuThreshold !== -1 && cpuUsage > cpuThreshold ? true : false,
+ memory: memoryThreshold !== -1 && memoryUsage > memoryThreshold ? true : false,
+ disk: disk.some((d) => diskThreshold !== -1 && d.usage_percent > diskThreshold)
+ ? true
+ : false,
+ };
+
+ const notifications = await this.db.getNotificationsByMonitorId(
+ networkResponse.monitorId
+ );
+ for (const notification of notifications) {
+ const alertsToSend = [];
+ const alertTypes = ["cpu", "memory", "disk"];
+
+ for (const type of alertTypes) {
+ // Iterate over each alert type to see if any need to be decremented
+ if (alerts[type] === true) {
+ notification[`${type}AlertThreshold`]--; // Decrement threshold if an alert is triggered
+
+ if (notification[`${type}AlertThreshold`] <= 0) {
+ // If threshold drops below 0, reset and send notification
+ notification[`${type}AlertThreshold`] = notification.alertThreshold;
+
+ const formatAlert = {
+ cpu: () =>
+ `Your current CPU usage (${(cpuUsage * 100).toFixed(0)}%) is above your threshold (${(cpuThreshold * 100).toFixed(0)}%)`,
+ memory: () =>
+ `Your current memory usage (${(memoryUsage * 100).toFixed(0)}%) is above your threshold (${(memoryThreshold * 100).toFixed(0)}%)`,
+ disk: () =>
+ `Your current disk usage: ${disk
+ .map((d, idx) => `(Disk${idx}: ${(d.usage_percent * 100).toFixed(0)}%)`)
+ .join(
+ ", "
+ )} is above your threshold (${(diskThreshold * 100).toFixed(0)}%)`,
+ };
+ alertsToSend.push(formatAlert[type]());
+ }
+ }
+ }
+
+ await notification.save();
+
+ if (alertsToSend.length === 0) continue; // No alerts to send, we're done
+
+ if (notification.type === "email") {
+ this.sendHardwareEmail(networkResponse, notification.address, alertsToSend);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Handles notifications for different monitor types
+ *
+ * @async
+ * @function handleNotifications
+ * @param {Object} networkResponse - Response object containing monitor information
+ * @returns {Promise} - Indicates whether notifications were processed successfully
+ */
+ async handleNotifications(networkResponse) {
+ try {
+ if (networkResponse.monitor.type === "hardware") {
+ this.handleHardwareNotifications(networkResponse);
+ }
+ this.handleStatusNotifications(networkResponse);
+ return true;
+ } catch (error) {
+ this.logger.error({
+ message: error.message,
+ service: this.SERVICE_NAME,
+ method: "handleNotifications",
+ stack: error.stack,
+ });
+ }
+ }
+}
+
+export default NotificationService;
diff --git a/server/service/redisService.js b/server/service/redisService.js
new file mode 100644
index 000000000..d2d76002c
--- /dev/null
+++ b/server/service/redisService.js
@@ -0,0 +1,72 @@
+class RedisService {
+ static SERVICE_NAME = "RedisService";
+
+ constructor({ logger, IORedis, SettingsService }) {
+ this.logger = logger;
+ this.IORedis = IORedis;
+ this.SettingsService = SettingsService;
+ this.connection = null;
+ }
+
+ static async createInstance({ logger, IORedis, SettingsService }) {
+ const instance = new RedisService({ logger, IORedis, SettingsService });
+ await instance.connect();
+ return instance;
+ }
+
+ async connect() {
+ const settings = this.SettingsService.getSettings();
+ const { redisUrl } = settings;
+ this.connection = new this.IORedis(redisUrl, {
+ maxRetriesPerRequest: null,
+ retryStrategy: (times) => {
+ if (times >= 5) {
+ throw new Error("Failed to connect to Redis");
+ }
+ this.logger.debug({
+ message: "Retrying Redis connection",
+ service: RedisService.SERVICE_NAME,
+ details: { times },
+ });
+ return Math.min(times * 100, 2000);
+ },
+ });
+
+ await new Promise((resolve, reject) => {
+ let errorOccurred = false;
+
+ this.connection.on("ready", () => {
+ if (!errorOccurred) {
+ this.logger.info({
+ message: "Redis connection established",
+ service: RedisService.SERVICE_NAME,
+ });
+ resolve();
+ }
+ });
+
+ this.connection.on("error", (err) => {
+ errorOccurred = true;
+ this.logger.error({
+ message: "Redis connection error",
+ service: RedisService.SERVICE_NAME,
+ error: err,
+ });
+ setTimeout(() => reject(err), 5000);
+ });
+ });
+ }
+ async flushall() {
+ this.logger.debug({
+ message: "Flushing all Redis data",
+ service: RedisService.SERVICE_NAME,
+ });
+ await this.connection.flushall();
+ }
+
+ getConnection() {
+ return this.connection;
+ }
+}
+
+export default RedisService;
diff --git a/Server/service/serviceRegistry.js b/server/service/serviceRegistry.js
old mode 100644
new mode 100755
similarity index 100%
rename from Server/service/serviceRegistry.js
rename to server/service/serviceRegistry.js
diff --git a/server/service/settingsService.js b/server/service/settingsService.js
new file mode 100755
index 000000000..bc314abff
--- /dev/null
+++ b/server/service/settingsService.js
@@ -0,0 +1,80 @@
+const SERVICE_NAME = "SettingsService";
+const envConfig = {
+ nodeEnv: process.env.NODE_ENV,
+ logLevel: process.env.LOG_LEVEL,
+ systemEmailHost: process.env.SYSTEM_EMAIL_HOST,
+ systemEmailPort: process.env.SYSTEM_EMAIL_PORT,
+ systemEmailUser: process.env.SYSTEM_EMAIL_USER,
+ systemEmailAddress: process.env.SYSTEM_EMAIL_ADDRESS,
+ systemEmailPassword: process.env.SYSTEM_EMAIL_PASSWORD,
+ jwtSecret: process.env.JWT_SECRET,
+ jwtTTL: process.env.TOKEN_TTL,
+ clientHost: process.env.CLIENT_HOST,
+ dbConnectionString: process.env.DB_CONNECTION_STRING,
+ redisUrl: process.env.REDIS_URL,
+ callbackUrl: process.env.CALLBACK_URL,
+ port: process.env.PORT,
+ pagespeedApiKey: process.env.PAGESPEED_API_KEY,
+ uprockApiKey: process.env.UPROCK_API_KEY,
+};
+/**
+ * SettingsService
+ *
+ * This service is responsible for loading and managing the application settings.
+ */
+class SettingsService {
+ static SERVICE_NAME = SERVICE_NAME;
+ /**
+ * Constructs a new SettingsService
+ * @constructor
+ * @throws {Error}
+ */ constructor(appSettings) {
+ this.appSettings = appSettings;
+ this.settings = { ...envConfig };
+ }
+ /**
+ * Load settings from env settings
+ * @returns {Object>} The settings.
+ */
+ loadSettings() {
+ return this.settings;
+ }
+ /**
+ * Reload settings by calling loadSettings.
+ * @returns {Promise} The reloaded settings.
+ */
+ reloadSettings() {
+ return this.loadSettings();
+ }
+ /**
+ * Get the current settings.
+ * @returns {Object} The current settings.
+ * @throws Will throw an error if settings have not been loaded.
+ */
+ getSettings() {
+ if (!this.settings) {
+ throw new Error("Settings have not been loaded");
+ }
+ return this.settings;
+ }
+
+ async getDBSettings() {
+ // Remove any old settings
+ await this.appSettings.deleteMany({ version: { $exists: false } });
+
+ let settings = await this.appSettings
+ .findOne({ singleton: true })
+ .select("-__v -_id -createdAt -updatedAt -singleton")
+ .lean();
+ if (settings === null) {
+ await this.appSettings.create({});
+ settings = await this.appSettings
+ .findOne({ singleton: true })
+ .select("-__v -_id -createdAt -updatedAt -singleton")
+ .lean();
+ }
+ return settings;
+ }
+}
+
+export default SettingsService;
diff --git a/server/service/statusService.js b/server/service/statusService.js
new file mode 100755
index 000000000..79db6c96e
--- /dev/null
+++ b/server/service/statusService.js
@@ -0,0 +1,302 @@
+import MonitorStats from "../db/models/MonitorStats.js";
+import { safelyParseFloat } from "../utils/dataUtils.js";
+const SERVICE_NAME = "StatusService";
+
+class StatusService {
+ static SERVICE_NAME = SERVICE_NAME;
+ /**
+ * Creates an instance of StatusService.
+ *
+ * @param {Object} db - The database instance.
+ * @param {Object} logger - The logger instance.
+ */
+ constructor({ db, logger, buffer }) {
+ this.db = db;
+ this.logger = logger;
+ this.buffer = buffer;
+ this.SERVICE_NAME = SERVICE_NAME;
+ }
+
+ async updateRunningStats({ monitor, networkResponse }) {
+ try {
+ const monitorId = monitor._id;
+ const { responseTime, status, upt_burnt } = networkResponse;
+ // Get stats
+ let stats = await MonitorStats.findOne({ monitorId });
+ if (!stats) {
+ stats = new MonitorStats({
+ monitorId,
+ avgResponseTime: 0,
+ totalChecks: 0,
+ totalUpChecks: 0,
+ totalDownChecks: 0,
+ uptimePercentage: 0,
+ lastCheck: null,
+ timeSInceLastCheck: 0,
+ uptBurnt: 0,
+ });
+ }
+
+ // Update stats
+
+ // Last response time
+ stats.lastResponseTime = responseTime;
+
+ // Avg response time:
+ let avgResponseTime = stats.avgResponseTime;
+ if (typeof responseTime !== "undefined" && responseTime !== null) {
+ if (avgResponseTime === 0) {
+ avgResponseTime = responseTime;
+ } else {
+ avgResponseTime =
+ (avgResponseTime * (stats.totalChecks - 1) + responseTime) /
+ stats.totalChecks;
+ }
+ }
+ stats.avgResponseTime = avgResponseTime;
+
+ // Total checks
+ stats.totalChecks++;
+ if (status === true) {
+ stats.totalUpChecks++;
+ // Update the timeSinceLastFailure if needed
+ if (stats.timeOfLastFailure === 0) {
+ stats.timeOfLastFailure = new Date().getTime();
+ }
+ } else {
+ stats.totalDownChecks++;
+ stats.timeOfLastFailure = 0;
+ }
+
+ // Calculate uptime percentage
+ let uptimePercentage;
+ if (stats.totalChecks > 0) {
+ uptimePercentage = stats.totalUpChecks / stats.totalChecks;
+ } else {
+ uptimePercentage = status === true ? 100 : 0;
+ }
+ stats.uptimePercentage = uptimePercentage;
+
+ // latest check
+ stats.lastCheckTimestamp = new Date().getTime();
+
+ // UPT burned
+ if (typeof upt_burnt !== "undefined" && upt_burnt !== null) {
+ const currentUptBurnt = safelyParseFloat(stats.uptBurnt);
+ const newUptBurnt = safelyParseFloat(upt_burnt);
+ stats.uptBurnt = currentUptBurnt + newUptBurnt;
+ }
+ await stats.save();
+ return true;
+ } catch (error) {
+ this.logger.error({
+ service: this.SERVICE_NAME,
+ message: error.message,
+ method: "updateRunningStats",
+ stack: error.stack,
+ });
+ return false;
+ }
+ }
+
+ getStatusString = (status) => {
+ if (status === true) return "up";
+ if (status === false) return "down";
+ return "unknown";
+ };
+ /**
+ * Updates the status of a monitor based on the network response.
+ *
+ * @param {Object} networkResponse - The network response containing monitorId and status.
+ * @param {string} networkResponse.monitorId - The ID of the monitor.
+ * @param {string} networkResponse.status - The new status of the monitor.
+ * @returns {Promise} - A promise that resolves to an object containinfg the monitor, statusChanged flag, and previous status if the status changed, or false if an error occurred.
+ * @returns {Promise} returnObject - The object returned by the function.
+ * @returns {Object} returnObject.monitor - The monitor object.
+ * @returns {boolean} returnObject.statusChanged - Flag indicating if the status has changed.
+ * @returns {boolean} returnObject.prevStatus - The previous status of the monitor
+ */
+ updateStatus = async (networkResponse) => {
+ this.insertCheck(networkResponse);
+ try {
+ const { monitorId, status, code } = networkResponse;
+ const monitor = await this.db.getMonitorById(monitorId);
+
+ // Update running stats
+ this.updateRunningStats({ monitor, networkResponse });
+
+ // No change in monitor status, return early
+ if (monitor.status === status)
+ return {
+ monitor,
+ statusChanged: false,
+ prevStatus: monitor.status,
+ code,
+ timestamp: new Date().getTime(),
+ };
+
+ // Monitor status changed, save prev status and update monitor
+ this.logger.info({
+ service: this.SERVICE_NAME,
+ message: `${monitor.name} went from ${this.getStatusString(
+ monitor.status
+ )} to ${this.getStatusString(status)}`,
+ prevStatus: monitor.status,
+ newStatus: status,
+ });
+
+ const prevStatus = monitor.status;
+ monitor.status = status;
+ await monitor.save();
+
+ return {
+ monitor,
+ statusChanged: true,
+ prevStatus,
+ code,
+ timestamp: new Date().getTime(),
+ };
+ } catch (error) {
+ this.logger.error({
+ service: this.SERVICE_NAME,
+ message: error.message,
+ method: "updateStatus",
+ stack: error.stack,
+ });
+ throw error;
+ }
+ };
+
+ /**
+ * Builds a check object from the network response.
+ *
+ * @param {Object} networkResponse - The network response object.
+ * @param {string} networkResponse.monitorId - The monitor ID.
+ * @param {string} networkResponse.type - The type of the response.
+ * @param {string} networkResponse.status - The status of the response.
+ * @param {number} networkResponse.responseTime - The response time.
+ * @param {number} networkResponse.code - The status code.
+ * @param {string} networkResponse.message - The message.
+ * @param {Object} networkResponse.payload - The payload of the response.
+ * @returns {Object} The check object.
+ */
+ buildCheck = (networkResponse) => {
+ const {
+ monitorId,
+ teamId,
+ type,
+ status,
+ responseTime,
+ code,
+ message,
+ payload,
+ first_byte_took,
+ body_read_took,
+ dns_took,
+ conn_took,
+ connect_took,
+ tls_took,
+ } = networkResponse;
+
+ const check = {
+ monitorId,
+ teamId,
+ status,
+ statusCode: code,
+ responseTime,
+ message,
+ first_byte_took,
+ body_read_took,
+ dns_took,
+ conn_took,
+ connect_took,
+ tls_took,
+ };
+
+ if (type === "distributed_http") {
+ if (typeof payload === "undefined") {
+ return undefined;
+ }
+ check.continent = payload.continent;
+ check.countryCode = payload.country_code;
+ check.city = payload.city;
+ check.location = payload.location;
+ check.uptBurnt = payload.upt_burnt;
+ check.first_byte_took = payload.first_byte_took;
+ check.body_read_took = payload.body_read_took;
+ check.dns_took = payload.dns_took;
+ check.conn_took = payload.conn_took;
+ check.connect_took = payload.connect_took;
+ check.tls_took = payload.tls_took;
+ }
+
+ if (type === "pagespeed") {
+ if (typeof payload === "undefined") {
+ return undefined;
+ }
+ const categories = payload?.lighthouseResult?.categories ?? {};
+ const audits = payload?.lighthouseResult?.audits ?? {};
+ const {
+ "cumulative-layout-shift": cls = 0,
+ "speed-index": si = 0,
+ "first-contentful-paint": fcp = 0,
+ "largest-contentful-paint": lcp = 0,
+ "total-blocking-time": tbt = 0,
+ } = audits;
+ check.accessibility = (categories?.accessibility?.score || 0) * 100;
+ check.bestPractices = (categories?.["best-practices"]?.score || 0) * 100;
+ check.seo = (categories?.seo?.score || 0) * 100;
+ check.performance = (categories?.performance?.score || 0) * 100;
+ check.audits = { cls, si, fcp, lcp, tbt };
+ }
+
+ if (type === "hardware") {
+ const { cpu, memory, disk, host } = payload?.data ?? {};
+ const { errors } = payload?.errors ?? [];
+ check.cpu = cpu ?? {};
+ check.memory = memory ?? {};
+ check.disk = disk ?? {};
+ check.host = host ?? {};
+ check.errors = errors ?? [];
+ }
+ return check;
+ };
+
+ /**
+ * Inserts a check into the database based on the network response.
+ *
+ * @param {Object} networkResponse - The network response object.
+ * @param {string} networkResponse.monitorId - The monitor ID.
+ * @param {string} networkResponse.type - The type of the response.
+ * @param {string} networkResponse.status - The status of the response.
+ * @param {number} networkResponse.responseTime - The response time.
+ * @param {number} networkResponse.code - The status code.
+ * @param {string} networkResponse.message - The message.
+ * @param {Object} networkResponse.payload - The payload of the response.
+ * @returns {Promise} A promise that resolves when the check is inserted.
+ */
+ insertCheck = async (networkResponse) => {
+ try {
+ const check = this.buildCheck(networkResponse);
+ if (typeof check === "undefined") {
+ this.logger.warn({
+ message: "Failed to build check",
+ service: this.SERVICE_NAME,
+ method: "insertCheck",
+ details: networkResponse,
+ });
+ return;
+ }
+ this.buffer.addToBuffer({ check, type: networkResponse.type });
+ } catch (error) {
+ this.logger.error({
+ message: error.message,
+ service: this.SERVICE_NAME,
+ method: "insertCheck",
+ details: `Error inserting check for monitor: ${networkResponse?.monitorId}`,
+ stack: error.stack,
+ });
+ }
+ };
+}
+export default StatusService;
diff --git a/server/service/stringService.js b/server/service/stringService.js
new file mode 100755
index 000000000..b02254255
--- /dev/null
+++ b/server/service/stringService.js
@@ -0,0 +1,437 @@
+class StringService {
+ static SERVICE_NAME = "StringService";
+
+ constructor(translationService) {
+ if (StringService.instance) {
+ return StringService.instance;
+ }
+
+ this.translationService = translationService;
+ this._language = "en"; // default language
+ StringService.instance = this;
+ }
+
+ setLanguage(language) {
+ this._language = language;
+ }
+
+ get language() {
+ return this._language;
+ }
+
+ // Auth Messages
+ get dontHaveAccount() {
+ return this.translationService.getTranslation("dontHaveAccount");
+ }
+
+ get email() {
+ return this.translationService.getTranslation("email");
+ }
+
+ get forgotPassword() {
+ return this.translationService.getTranslation("forgotPassword");
+ }
+
+ get password() {
+ return this.translationService.getTranslation("password");
+ }
+
+ get signUp() {
+ return this.translationService.getTranslation("signUp");
+ }
+
+ get submit() {
+ return this.translationService.getTranslation("submit");
+ }
+
+ get title() {
+ return this.translationService.getTranslation("title");
+ }
+
+ get continue() {
+ return this.translationService.getTranslation("continue");
+ }
+
+ get enterEmail() {
+ return this.translationService.getTranslation("enterEmail");
+ }
+
+ get authLoginTitle() {
+ return this.translationService.getTranslation("authLoginTitle");
+ }
+
+ get authLoginEnterPassword() {
+ return this.translationService.getTranslation("authLoginEnterPassword");
+ }
+
+ get commonPassword() {
+ return this.translationService.getTranslation("commonPassword");
+ }
+
+ get commonBack() {
+ return this.translationService.getTranslation("commonBack");
+ }
+
+ get authForgotPasswordTitle() {
+ return this.translationService.getTranslation("authForgotPasswordTitle");
+ }
+
+ get authForgotPasswordResetPassword() {
+ return this.translationService.getTranslation("authForgotPasswordResetPassword");
+ }
+
+ get createPassword() {
+ return this.translationService.getTranslation("createPassword");
+ }
+
+ get createAPassword() {
+ return this.translationService.getTranslation("createAPassword");
+ }
+
+ get authRegisterAlreadyHaveAccount() {
+ return this.translationService.getTranslation("authRegisterAlreadyHaveAccount");
+ }
+
+ get commonAppName() {
+ return this.translationService.getTranslation("commonAppName");
+ }
+
+ get authLoginEnterEmail() {
+ return this.translationService.getTranslation("authLoginEnterEmail");
+ }
+
+ get authRegisterTitle() {
+ return this.translationService.getTranslation("authRegisterTitle");
+ }
+
+ get monitorGetAll() {
+ return this.translationService.getTranslation("monitorGetAll");
+ }
+
+ get monitorGetById() {
+ return this.translationService.getTranslation("monitorGetById");
+ }
+
+ get monitorGetByIdSuccess() {
+ return this.translationService.getTranslation("monitorGetByIdSuccess");
+ }
+
+ get monitorCreate() {
+ return this.translationService.getTranslation("monitorCreate");
+ }
+
+ get bulkMonitorsCreate() {
+ return this.translationService.getTranslation("bulkMonitorsCreate");
+ }
+
+ get monitorEdit() {
+ return this.translationService.getTranslation("monitorEdit");
+ }
+
+ get monitorDelete() {
+ return this.translationService.getTranslation("monitorDelete");
+ }
+
+ get monitorPause() {
+ return this.translationService.getTranslation("monitorPause");
+ }
+
+ get monitorResume() {
+ return this.translationService.getTranslation("monitorResume");
+ }
+
+ get monitorDemoAdded() {
+ return this.translationService.getTranslation("monitorDemoAdded");
+ }
+
+ get monitorStatsById() {
+ return this.translationService.getTranslation("monitorStatsById");
+ }
+
+ get monitorCertificate() {
+ return this.translationService.getTranslation("monitorCertificate");
+ }
+
+ // Maintenance Window Messages
+ get maintenanceWindowCreate() {
+ return this.translationService.getTranslation("maintenanceWindowCreate");
+ }
+
+ get maintenanceWindowGetById() {
+ return this.translationService.getTranslation("maintenanceWindowGetById");
+ }
+
+ get maintenanceWindowGetByTeam() {
+ return this.translationService.getTranslation("maintenanceWindowGetByTeam");
+ }
+
+ get maintenanceWindowDelete() {
+ return this.translationService.getTranslation("maintenanceWindowDelete");
+ }
+
+ get maintenanceWindowEdit() {
+ return this.translationService.getTranslation("maintenanceWindowEdit");
+ }
+
+ // Webhook Messages
+ get webhookUnsupportedPlatform() {
+ return this.translationService.getTranslation("webhookUnsupportedPlatform");
+ }
+
+ get webhookSendError() {
+ return this.translationService.getTranslation("webhookSendError");
+ }
+
+ get webhookSendSuccess() {
+ return this.translationService.getTranslation("webhookSendSuccess");
+ }
+
+ get telegramRequiresBotTokenAndChatId() {
+ return this.translationService.getTranslation("telegramRequiresBotTokenAndChatId");
+ }
+
+ get webhookUrlRequired() {
+ return this.translationService.getTranslation("webhookUrlRequired");
+ }
+
+ get platformRequired() {
+ return this.translationService.getTranslation("platformRequired");
+ }
+
+ get testNotificationFailed() {
+ return this.translationService.getTranslation("testNotificationFailed");
+ }
+
+ get monitorUpAlert() {
+ return this.translationService.getTranslation("monitorUpAlert");
+ }
+
+ get monitorDownAlert() {
+ return this.translationService.getTranslation("monitorDownAlert");
+ }
+
+ getWebhookUnsupportedPlatform(platform) {
+ return this.translationService
+ .getTranslation("webhookUnsupportedPlatform")
+ .replace("{platform}", platform);
+ }
+
+ getWebhookSendError(platform) {
+ return this.translationService
+ .getTranslation("webhookSendError")
+ .replace("{platform}", platform);
+ }
+
+ getMonitorStatus(name, status, url) {
+ const translationKey = status === true ? "monitorStatusUp" : "monitorStatusDown";
+ return this.translationService
+ .getTranslation(translationKey)
+ .replace("{name}", name)
+ .replace("{url}", url);
+ }
+
+ // Error Messages
+ get unknownError() {
+ return this.translationService.getTranslation("unknownError");
+ }
+
+ get friendlyError() {
+ return this.translationService.getTranslation("friendlyError");
+ }
+
+ get authIncorrectPassword() {
+ return this.translationService.getTranslation("authIncorrectPassword");
+ }
+
+ get unauthorized() {
+ return this.translationService.getTranslation("unauthorized");
+ }
+
+ get authAdminExists() {
+ return this.translationService.getTranslation("authAdminExists");
+ }
+
+ get authInviteNotFound() {
+ return this.translationService.getTranslation("authInviteNotFound");
+ }
+
+ get unknownService() {
+ return this.translationService.getTranslation("unknownService");
+ }
+
+ get noAuthToken() {
+ return this.translationService.getTranslation("noAuthToken");
+ }
+
+ get invalidAuthToken() {
+ return this.translationService.getTranslation("invalidAuthToken");
+ }
+
+ get expiredAuthToken() {
+ return this.translationService.getTranslation("expiredAuthToken");
+ }
+
+ // Queue Messages
+ get queueGetMetrics() {
+ return this.translationService.getTranslation("queueGetMetrics");
+ }
+
+ get queueAddJob() {
+ return this.translationService.getTranslation("queueAddJob");
+ }
+
+ get queueObliterate() {
+ return this.translationService.getTranslation("queueObliterate");
+ }
+
+ // Job Queue Messages
+ get jobQueueDeleteJobSuccess() {
+ return this.translationService.getTranslation("jobQueueDeleteJobSuccess");
+ }
+
+ get jobQueuePauseJob() {
+ return this.translationService.getTranslation("jobQueuePauseJob");
+ }
+
+ get jobQueueResumeJob() {
+ return this.translationService.getTranslation("jobQueueResumeJob");
+ }
+
+ // Status Page Messages
+ get statusPageByUrl() {
+ return this.translationService.getTranslation("statusPageByUrl");
+ }
+
+ get statusPageCreate() {
+ return this.translationService.getTranslation("statusPageCreate");
+ }
+
+ get statusPageDelete() {
+ return this.translationService.getTranslation("statusPageDelete");
+ }
+
+ get statusPageUpdate() {
+ return this.translationService.getTranslation("statusPageUpdate");
+ }
+
+ get statusPageNotFound() {
+ return this.translationService.getTranslation("statusPageNotFound");
+ }
+
+ get statusPageByTeamId() {
+ return this.translationService.getTranslation("statusPageByTeamId");
+ }
+
+ get statusPageUrlNotUnique() {
+ return this.translationService.getTranslation("statusPageUrlNotUnique");
+ }
+
+ // Docker Messages
+ get dockerFail() {
+ return this.translationService.getTranslation("dockerFail");
+ }
+
+ get dockerNotFound() {
+ return this.translationService.getTranslation("dockerNotFound");
+ }
+
+ get dockerSuccess() {
+ return this.translationService.getTranslation("dockerSuccess");
+ }
+
+ // Port Messages
+ get portFail() {
+ return this.translationService.getTranslation("portFail");
+ }
+
+ get portSuccess() {
+ return this.translationService.getTranslation("portSuccess");
+ }
+
+ // Alert Messages
+ get alertCreate() {
+ return this.translationService.getTranslation("alertCreate");
+ }
+
+ get alertGetByUser() {
+ return this.translationService.getTranslation("alertGetByUser");
+ }
+
+ get alertGetByMonitor() {
+ return this.translationService.getTranslation("alertGetByMonitor");
+ }
+
+ get alertGetById() {
+ return this.translationService.getTranslation("alertGetById");
+ }
+
+ get alertEdit() {
+ return this.translationService.getTranslation("alertEdit");
+ }
+
+ get alertDelete() {
+ return this.translationService.getTranslation("alertDelete");
+ }
+
+ getDeletedCount(count) {
+ return this.translationService
+ .getTranslation("deletedCount")
+ .replace("{count}", count);
+ }
+
+ get pingSuccess() {
+ return this.translationService.getTranslation("pingSuccess");
+ }
+
+ get getAppSettings() {
+ return this.translationService.getTranslation("getAppSettings");
+ }
+
+ get httpNetworkError() {
+ return this.translationService.getTranslation("httpNetworkError");
+ }
+
+ get httpNotJson() {
+ return this.translationService.getTranslation("httpNotJson");
+ }
+
+ get httpJsonPathError() {
+ return this.translationService.getTranslation("httpJsonPathError");
+ }
+
+ get httpEmptyResult() {
+ return this.translationService.getTranslation("httpEmptyResult");
+ }
+
+ get httpMatchSuccess() {
+ return this.translationService.getTranslation("httpMatchSuccess");
+ }
+
+ get httpMatchFail() {
+ return this.translationService.getTranslation("httpMatchFail");
+ }
+
+ get updateAppSettings() {
+ return this.translationService.getTranslation("updateAppSettings");
+ }
+
+ get insufficientPermissions() {
+ return this.translationService.getTranslation("insufficientPermissions");
+ }
+
+ getDbFindMonitorById(monitorId) {
+ return this.translationService
+ .getTranslation("dbFindMonitorById")
+ .replace("${monitorId}", monitorId);
+ }
+
+ get dbUserExists() {
+ return this.translationService.getTranslation("dbUserExists");
+ }
+
+ get testEmailSubject() {
+ return this.translationService.getTranslation("testEmailSubject");
+ }
+}
+
+export default StringService;
diff --git a/server/service/translationService.js b/server/service/translationService.js
new file mode 100755
index 000000000..de29b5eb1
--- /dev/null
+++ b/server/service/translationService.js
@@ -0,0 +1,91 @@
+import fs from "fs";
+import path from "path";
+
+class TranslationService {
+ static SERVICE_NAME = "TranslationService";
+
+ constructor(logger) {
+ this.logger = logger;
+ this.translations = {};
+ this._language = "en";
+ this.localesDir = path.join(process.cwd(), "locales");
+ }
+
+ setLanguage(language) {
+ this._language = language;
+ }
+
+ get language() {
+ return this._language;
+ }
+
+ async initialize() {
+ try {
+ await this.loadFromFiles();
+ } catch (error) {
+ this.logger.error({
+ message: error.message,
+ service: "TranslationService",
+ method: "initialize",
+ stack: error.stack,
+ });
+ }
+ }
+
+ async loadFromFiles() {
+ try {
+ if (!fs.existsSync(this.localesDir)) {
+ return false;
+ }
+
+ const files = fs
+ .readdirSync(this.localesDir)
+ .filter((file) => file.endsWith(".json"));
+
+ if (files.length === 0) {
+ return false;
+ }
+
+ for (const file of files) {
+ const language = file.replace(".json", "");
+ const filePath = path.join(this.localesDir, file);
+ const content = fs.readFileSync(filePath, "utf8");
+ this.translations[language] = JSON.parse(content);
+ }
+
+ this.logger.info({
+ message: "Translations loaded from files successfully",
+ service: "TranslationService",
+ method: "loadFromFiles",
+ });
+
+ return true;
+ } catch (error) {
+ this.logger.error({
+ message: error.message,
+ service: "TranslationService",
+ method: "loadFromFiles",
+ stack: error.stack,
+ });
+ return false;
+ }
+ }
+
+ getTranslation(key) {
+ let language = this._language;
+
+ try {
+ return this.translations[language]?.[key] || this.translations["en"]?.[key] || key;
+ } catch (error) {
+ this.logger.error({
+ message: error.message,
+ service: "TranslationService",
+ method: "getTranslation",
+ stack: error.stack,
+ });
+ return key;
+ }
+ }
+}
+
+export default TranslationService;
diff --git a/server/templates/addReview.mjml b/server/templates/addReview.mjml
new file mode 100755
index 000000000..9d00be7d0
--- /dev/null
+++ b/server/templates/addReview.mjml
@@ -0,0 +1,63 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Message from Checkmate Service
+
+
+
+
+
+
+ Hello {{name}}!
+
+ We hope you’re finding Checkmate helpful in monitoring your infrastructure.
+ Your support means a lot to us, and we truly appreciate having you as
+ part of our community.
+
+
+ If you’re happy with Checkmate, we’d love to hear about your experience!
+ Leaving a review on G2 helps others discover Checkmate and supports our
+ ongoing improvements.
+
+ G2 Link: TBD
+
+ Thank you for taking the time to share your thoughts - we greatly appreciate
+ it!
+
+ Checkmate Team
+
+
+
+
+
+ This email was sent by Checkmate.
+
+
+
+
+
diff --git a/Server/templates/employeeActivation.mjml b/server/templates/employeeActivation.mjml
old mode 100644
new mode 100755
similarity index 92%
rename from Server/templates/employeeActivation.mjml
rename to server/templates/employeeActivation.mjml
index 34d5ea7c4..3e35db6e8
--- a/Server/templates/employeeActivation.mjml
+++ b/server/templates/employeeActivation.mjml
@@ -30,9 +30,7 @@
Hello {{name}}!
-
- One of the admins created an account for you on the Checkmate server.
-
+ One of the admins created an account for you on the Checkmate server.
You can go ahead and create your account using this link.
{{link}}
Thank you.
diff --git a/server/templates/hardwareIncident.mjml b/server/templates/hardwareIncident.mjml
new file mode 100755
index 000000000..19fb589fc
--- /dev/null
+++ b/server/templates/hardwareIncident.mjml
@@ -0,0 +1,69 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Message from BlueWave Infrastructure Monitoring
+
+
+
+
+ Infrastructure Alerts
+
+
+
+
+
+
+
+ Hello {{name}}!
+ {{monitor}} at {{url}} has the following infrastructure alerts:
+ {{#each alerts}}
+ • {{this}}
+ {{/each}}
+
+
+
+
+ View Infrastructure Details
+
+ This email was sent by BlueWave Infrastructure Monitoring.
+
+
+
+
+
diff --git a/Server/templates/noIncidentsThisWeek.mjml b/server/templates/noIncidentsThisWeek.mjml
old mode 100644
new mode 100755
similarity index 100%
rename from Server/templates/noIncidentsThisWeek.mjml
rename to server/templates/noIncidentsThisWeek.mjml
diff --git a/Server/templates/passwordReset.mjml b/server/templates/passwordReset.mjml
old mode 100644
new mode 100755
similarity index 100%
rename from Server/templates/passwordReset.mjml
rename to server/templates/passwordReset.mjml
diff --git a/server/templates/serverIsDown.mjml b/server/templates/serverIsDown.mjml
new file mode 100755
index 000000000..b75d970e6
--- /dev/null
+++ b/server/templates/serverIsDown.mjml
@@ -0,0 +1,71 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Message from Checkmate Service
+
+
+
+
+ {{monitor}} is down
+
+
+
+
+
+
+
+ Hello {{name}}!
+
+ We detected an incident on one of your monitors. Your service is currently
+ down. We'll send a message to you once it is up again.
+
+ Monitor name: {{monitor}}
+ URL: {{url}}
+
+
+
+
+ View incident details
+
+ This email was sent by Checkmate.
+
+
+
+
+
diff --git a/server/templates/serverIsUp.mjml b/server/templates/serverIsUp.mjml
new file mode 100755
index 000000000..beb34481d
--- /dev/null
+++ b/server/templates/serverIsUp.mjml
@@ -0,0 +1,68 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Message from Checkmate Service
+
+
+
+
+ {{monitor}} is up
+
+
+
+
+
+
+
+ Hello {{name}}!
+ Your latest incident is resolved and your monitored service is up again.
+ Monitor name: {{monitor}}
+ URL: {{url}}
+
+
+
+
+ View incident details
+
+ This email was sent by Checkmate.
+
+
+
+
+
diff --git a/server/templates/testEmailTemplate.mjml b/server/templates/testEmailTemplate.mjml
new file mode 100644
index 000000000..e9fd3221e
--- /dev/null
+++ b/server/templates/testEmailTemplate.mjml
@@ -0,0 +1,17 @@
+
+
+
+
+
+ Hello!
+
+
+ This is a test email from the Monitoring System.
+
+
+ If you're receiving this, your email configuration is working correctly.
+
+
+
+
+
diff --git a/Server/templates/welcomeEmail.mjml b/server/templates/welcomeEmail.mjml
old mode 100644
new mode 100755
similarity index 89%
rename from Server/templates/welcomeEmail.mjml
rename to server/templates/welcomeEmail.mjml
index af1bfc190..663518ec2
--- a/Server/templates/welcomeEmail.mjml
+++ b/server/templates/welcomeEmail.mjml
@@ -32,12 +32,12 @@
Hello {{name}}!
- Thank you for trying out Checkmate! We developed it with great care to
- meet our own needs, and we're excited to share it with you.
+ Thank you for trying out Checkmate! We developed it with great care to meet
+ our own needs, and we're excited to share it with you.
- Checkmate is an automated way of checking whether a service such as a
- website or an application is available or not.
+ Checkmate is an automated way of checking whether a service such as a website
+ or an application is available or not.
We hope you find our service as valuable as we do.
Thank you.
diff --git a/Server/tests/controllers/authController.test.js b/server/tests/controllers/authController.test.js
old mode 100644
new mode 100755
similarity index 91%
rename from Server/tests/controllers/authController.test.js
rename to server/tests/controllers/authController.test.js
index 3f45d1c42..2990afe22
--- a/Server/tests/controllers/authController.test.js
+++ b/server/tests/controllers/authController.test.js
@@ -2,7 +2,6 @@ import {
issueToken,
registerUser,
loginUser,
- refreshAuthToken,
editUser,
checkSuperadminExists,
requestRecovery,
@@ -14,18 +13,17 @@ import {
import jwt from "jsonwebtoken";
import { errorMessages, successMessages } from "../../utils/messages.js";
import sinon from "sinon";
-import { getTokenFromHeaders, tokenType } from "../../utils/utils.js";
+import { tokenType } from "../../utils/utils.js";
import logger from "../../utils/logger.js";
-import e from "cors";
-describe("Auth Controller - issueToken", function() {
+describe("Auth Controller - issueToken", function () {
let stub;
- afterEach(function() {
+ afterEach(function () {
sinon.restore(); // Restore stubs after each test
});
- it("should reject with an error if jwt.sign fails", function() {
+ it("should reject with an error if jwt.sign fails", function () {
const error = new Error("jwt.sign error");
stub = sinon.stub(jwt, "sign").throws(error);
const payload = { id: "123" };
@@ -35,7 +33,7 @@ describe("Auth Controller - issueToken", function() {
);
});
- it("should return a token if jwt.sign is successful and appSettings.jwtTTL is not defined", function() {
+ it("should return a token if jwt.sign is successful and appSettings.jwtTTL is not defined", function () {
const payload = { id: "123" };
const appSettings = { jwtSecret: "my_secret" };
const expectedToken = "mockToken";
@@ -45,7 +43,7 @@ describe("Auth Controller - issueToken", function() {
expect(token).to.equal(expectedToken);
});
- it("should return a token if jwt.sign is successful and appSettings.jwtTTL is defined", function() {
+ it("should return a token if jwt.sign is successful and appSettings.jwtTTL is defined", function () {
const payload = { id: "123" };
const appSettings = { jwtSecret: "my_secret", jwtTTL: "1s" };
const expectedToken = "mockToken";
@@ -55,7 +53,7 @@ describe("Auth Controller - issueToken", function() {
expect(token).to.equal(expectedToken);
});
- it("should return a refresh token if jwt.sign is successful and appSettings.refreshTokenTTL is not defined", function() {
+ it("should return a refresh token if jwt.sign is successful and appSettings.refreshTokenTTL is not defined", function () {
const payload = {};
const appSettings = { refreshTokenSecret: "my_refresh_secret" };
const expectedToken = "mockRefreshToken";
@@ -65,7 +63,7 @@ describe("Auth Controller - issueToken", function() {
expect(token).to.equal(expectedToken);
});
- it("should return a refresh token if jwt.sign is successful and appSettings.refreshTokenTTL is defined", function() {
+ it("should return a refresh token if jwt.sign is successful and appSettings.refreshTokenTTL is defined", function () {
const payload = {};
const appSettings = {
refreshTokenSecret: "my_refresh_secret",
@@ -79,10 +77,10 @@ describe("Auth Controller - issueToken", function() {
});
});
-describe("Auth Controller - registerUser", function() {
+describe("Auth Controller - registerUser", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
body: {
firstName: "firstname",
@@ -118,25 +116,25 @@ describe("Auth Controller - registerUser", function() {
sinon.stub(logger, "error");
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with an error if body validation fails", async function() {
+ it("should reject with an error if body validation fails", async function () {
req.body = {};
await registerUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if checkSuperadmin fails", async function() {
+ it("should reject with an error if checkSuperadmin fails", async function () {
req.db.checkSuperadmin.throws(new Error("checkSuperadmin error"));
await registerUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("checkSuperadmin error");
});
- it("should reject with an error if getInviteTokenAndDelete fails", async function() {
+ it("should reject with an error if getInviteTokenAndDelete fails", async function () {
req.db.checkSuperadmin.returns(true);
req.db.getInviteTokenAndDelete.throws(new Error("getInviteTokenAndDelete error"));
await registerUser(req, res, next);
@@ -144,7 +142,7 @@ describe("Auth Controller - registerUser", function() {
expect(next.firstCall.args[0].message).to.equal("getInviteTokenAndDelete error");
});
- it("should reject with an error if updateAppSettings fails", async function() {
+ it("should reject with an error if updateAppSettings fails", async function () {
req.db.checkSuperadmin.returns(false);
req.db.updateAppSettings.throws(new Error("updateAppSettings error"));
await registerUser(req, res, next);
@@ -152,7 +150,7 @@ describe("Auth Controller - registerUser", function() {
expect(next.firstCall.args[0].message).to.equal("updateAppSettings error");
});
- it("should reject with an error if insertUser fails", async function() {
+ it("should reject with an error if insertUser fails", async function () {
req.db.checkSuperadmin.resolves(false);
req.db.updateAppSettings.resolves();
req.db.insertUser.rejects(new Error("insertUser error"));
@@ -161,7 +159,7 @@ describe("Auth Controller - registerUser", function() {
expect(next.firstCall.args[0].message).to.equal("insertUser error");
});
- it("should reject with an error if settingsService.getSettings fails", async function() {
+ it("should reject with an error if settingsService.getSettings fails", async function () {
req.db.checkSuperadmin.resolves(false);
req.db.updateAppSettings.resolves();
req.db.insertUser.resolves({ _id: "123" });
@@ -173,7 +171,7 @@ describe("Auth Controller - registerUser", function() {
expect(next.firstCall.args[0].message).to.equal("settingsService.getSettings error");
});
- it("should log an error if emailService.buildAndSendEmail fails", async function() {
+ it("should log an error if emailService.buildAndSendEmail fails", async function () {
req.db.checkSuperadmin.resolves(false);
req.db.updateAppSettings.resolves();
req.db.insertUser.returns({ _id: "123" });
@@ -187,7 +185,7 @@ describe("Auth Controller - registerUser", function() {
expect(logger.error.firstCall.args[0].message).to.equal("emailService error");
});
- it("should return a success message and data if all operations are successful", async function() {
+ it("should return a success message and data if all operations are successful", async function () {
const user = { _id: "123" };
req.db.checkSuperadmin.resolves(false);
req.db.updateAppSettings.resolves();
@@ -209,7 +207,7 @@ describe("Auth Controller - registerUser", function() {
expect(next.notCalled).to.be.true;
});
- it("should return a success message and data if all operations are successful and superAdmin true", async function() {
+ it("should return a success message and data if all operations are successful and superAdmin true", async function () {
const user = { _id: "123" };
req.db.checkSuperadmin.resolves(true);
req.db.updateAppSettings.resolves();
@@ -232,10 +230,10 @@ describe("Auth Controller - registerUser", function() {
});
});
-describe("Auth Controller - loginUser", function() {
+describe("Auth Controller - loginUser", function () {
let req, res, next, user;
- beforeEach(function() {
+ beforeEach(function () {
req = {
body: { email: "test@example.com", password: "Password123!" },
db: {
@@ -261,21 +259,21 @@ describe("Auth Controller - loginUser", function() {
};
});
- it("should reject with an error if validation fails", async function() {
+ it("should reject with an error if validation fails", async function () {
req.body = {};
await loginUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if getUserByEmail fails", async function() {
+ it("should reject with an error if getUserByEmail fails", async function () {
req.db.getUserByEmail.rejects(new Error("getUserByEmail error"));
await loginUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getUserByEmail error");
});
- it("should login user successfully", async function() {
+ it("should login user successfully", async function () {
req.db.getUserByEmail.resolves(user);
user.comparePassword.resolves(true);
await loginUser(req, res, next);
@@ -297,7 +295,7 @@ describe("Auth Controller - loginUser", function() {
expect(next.notCalled).to.be.true;
});
- it("should reject a user with an incorrect password", async function() {
+ it("should reject a user with an incorrect password", async function () {
req.body = {
email: "test@test.com",
password: "Password123!",
@@ -312,10 +310,10 @@ describe("Auth Controller - loginUser", function() {
});
});
-describe("Auth Controller - refreshAuthToken", function() {
+describe("Auth Controller - refreshAuthToken", function () {
let req, res, next, issueTokenStub;
- beforeEach(function() {
+ beforeEach(function () {
req = {
headers: {
"x-refresh-token": "valid_refresh_token",
@@ -339,11 +337,11 @@ describe("Auth Controller - refreshAuthToken", function() {
sinon.replace({ issueToken }, "issueToken", issueTokenStub);
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject if no refresh token is provided", async function() {
+ it("should reject if no refresh token is provided", async function () {
delete req.headers["x-refresh-token"];
await refreshAuthToken(req, res, next);
@@ -352,7 +350,7 @@ describe("Auth Controller - refreshAuthToken", function() {
expect(next.firstCall.args[0].status).to.equal(401);
});
- it("should reject if the refresh token is invalid", async function() {
+ it("should reject if the refresh token is invalid", async function () {
jwt.verify.yields(new Error("invalid token"));
await refreshAuthToken(req, res, next);
@@ -361,7 +359,7 @@ describe("Auth Controller - refreshAuthToken", function() {
expect(next.firstCall.args[0].status).to.equal(401);
});
- it("should reject if the refresh token is expired", async function() {
+ it("should reject if the refresh token is expired", async function () {
const error = new Error("Token expired");
error.name = "TokenExpiredError";
jwt.verify.yields(error);
@@ -371,7 +369,7 @@ describe("Auth Controller - refreshAuthToken", function() {
expect(next.firstCall.args[0].status).to.equal(401);
});
- it("should reject if settingsService.getSettings fails", async function() {
+ it("should reject if settingsService.getSettings fails", async function () {
req.settingsService.getSettings.rejects(
new Error("settingsService.getSettings error")
);
@@ -381,7 +379,7 @@ describe("Auth Controller - refreshAuthToken", function() {
expect(next.firstCall.args[0].message).to.equal("settingsService.getSettings error");
});
- it("should generate a new auth token if the refresh token is valid", async function() {
+ it("should generate a new auth token if the refresh token is valid", async function () {
const decodedPayload = { expiresIn: "60" };
jwt.verify.callsFake(() => {
return decodedPayload;
@@ -403,10 +401,10 @@ describe("Auth Controller - refreshAuthToken", function() {
});
});
-describe("Auth Controller - editUser", function() {
+describe("Auth Controller - editUser", function () {
let req, res, next, stub, user;
- beforeEach(function() {
+ beforeEach(function () {
req = {
params: { userId: "123" },
body: { password: "Password1!", newPassword: "Password2!" },
@@ -428,40 +426,40 @@ describe("Auth Controller - editUser", function() {
stub = sinon.stub(jwt, "verify").returns({ email: "test@example.com" });
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
stub.restore();
});
- it("should reject with an error if param validation fails", async function() {
+ it("should reject with an error if param validation fails", async function () {
req.params = {};
await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if body validation fails", async function() {
+ it("should reject with an error if body validation fails", async function () {
req.body = { invalid: 1 };
await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if param.userId !== req.user._id", async function() {
+ it("should reject with an error if param.userId !== req.user._id", async function () {
req.params = { userId: "456" };
await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(401);
});
- it("should reject with an error if !req.body.password and getUserByEmail fails", async function() {
+ it("should reject with an error if !req.body.password and getUserByEmail fails", async function () {
req.db.getUserByEmail.rejects(new Error("getUserByEmail error"));
await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getUserByEmail error");
});
- it("should reject with an error if user.comparePassword fails", async function() {
+ it("should reject with an error if user.comparePassword fails", async function () {
req.db.getUserByEmail.returns({
comparePassword: sinon.stub().rejects(new Error("Bad Password Match")),
});
@@ -470,7 +468,7 @@ describe("Auth Controller - editUser", function() {
expect(next.firstCall.args[0].message).to.equal("Bad Password Match");
});
- it("should reject with an error if user.comparePassword returns false", async function() {
+ it("should reject with an error if user.comparePassword returns false", async function () {
req.db.getUserByEmail.returns({
comparePassword: sinon.stub().returns(false),
});
@@ -482,7 +480,7 @@ describe("Auth Controller - editUser", function() {
);
});
- it("should edit a user if it receives a proper request", async function() {
+ it("should edit a user if it receives a proper request", async function () {
const user = {
comparePassword: sinon.stub().resolves(true),
};
@@ -504,7 +502,7 @@ describe("Auth Controller - editUser", function() {
expect(next.notCalled).to.be.true;
});
- it("should edit a user if it receives a proper request and both password fields are undefined", async function() {
+ it("should edit a user if it receives a proper request and both password fields are undefined", async function () {
req.body.password = undefined;
req.body.newPassword = undefined;
req.db.getUserByEmail.resolves(user);
@@ -522,7 +520,7 @@ describe("Auth Controller - editUser", function() {
expect(next.notCalled).to.be.true;
});
- it("should reject an edit request if password format is incorrect", async function() {
+ it("should reject an edit request if password format is incorrect", async function () {
req.body = { password: "bad_password", newPassword: "bad_password" };
const user = {
comparePassword: sinon.stub().resolves(true),
@@ -536,10 +534,10 @@ describe("Auth Controller - editUser", function() {
});
});
-describe("Auth Controller - checkSuperadminExists", function() {
+describe("Auth Controller - checkSuperadminExists", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
db: {
checkSuperadmin: sinon.stub(),
@@ -552,14 +550,14 @@ describe("Auth Controller - checkSuperadminExists", function() {
next = sinon.stub();
});
- it("should reject with an error if checkSuperadmin fails", async function() {
+ it("should reject with an error if checkSuperadmin fails", async function () {
req.db.checkSuperadmin.rejects(new Error("checkSuperadmin error"));
await checkSuperadminExists(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("checkSuperadmin error");
});
- it("should return true if a superadmin exists", async function() {
+ it("should return true if a superadmin exists", async function () {
req.db.checkSuperadmin.resolves(true);
await checkSuperadminExists(req, res, next);
expect(res.status.calledWith(200)).to.be.true;
@@ -573,7 +571,7 @@ describe("Auth Controller - checkSuperadminExists", function() {
expect(next.notCalled).to.be.true;
});
- it("should return false if a superadmin does not exist", async function() {
+ it("should return false if a superadmin does not exist", async function () {
req.db.checkSuperadmin.resolves(false);
await checkSuperadminExists(req, res, next);
expect(res.status.calledWith(200)).to.be.true;
@@ -588,10 +586,10 @@ describe("Auth Controller - checkSuperadminExists", function() {
});
});
-describe("Auth Controller - requestRecovery", function() {
+describe("Auth Controller - requestRecovery", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
body: { email: "test@test.com" },
db: {
@@ -612,21 +610,21 @@ describe("Auth Controller - requestRecovery", function() {
next = sinon.stub();
});
- it("should reject with an error if validation fails", async function() {
+ it("should reject with an error if validation fails", async function () {
req.body = {};
await requestRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if getUserByEmail fails", async function() {
+ it("should reject with an error if getUserByEmail fails", async function () {
req.db.getUserByEmail.rejects(new Error("getUserByEmail error"));
await requestRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getUserByEmail error");
});
- it("should throw an error if the user is not found", async function() {
+ it("should throw an error if the user is not found", async function () {
req.db.getUserByEmail.resolves(null);
await requestRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
@@ -635,14 +633,14 @@ describe("Auth Controller - requestRecovery", function() {
// );
});
- it("should throw an error if the email is not provided", async function() {
+ it("should throw an error if the email is not provided", async function () {
req.body = {};
await requestRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should return a success message if the email is provided", async function() {
+ it("should return a success message if the email is provided", async function () {
const user = { firstName: "John" };
const recoveryToken = { token: "recovery-token" };
const msgId = "message-id";
@@ -676,10 +674,10 @@ describe("Auth Controller - requestRecovery", function() {
});
});
-describe("Auth Controller - validateRecovery", function() {
+describe("Auth Controller - validateRecovery", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
body: { recoveryToken: "recovery-token" },
db: {
@@ -693,21 +691,21 @@ describe("Auth Controller - validateRecovery", function() {
next = sinon.stub();
});
- it("should reject with an error if validation fails", async function() {
+ it("should reject with an error if validation fails", async function () {
req.body = {};
await validateRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if validateRecoveryToken fails", async function() {
+ it("should reject with an error if validateRecoveryToken fails", async function () {
req.db.validateRecoveryToken.rejects(new Error("validateRecoveryToken error"));
await validateRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("validateRecoveryToken error");
});
- it("should return a success message if the token is valid", async function() {
+ it("should return a success message if the token is valid", async function () {
req.db.validateRecoveryToken.resolves();
await validateRecovery(req, res, next);
expect(res.status.calledOnceWith(200)).to.be.true;
@@ -721,10 +719,10 @@ describe("Auth Controller - validateRecovery", function() {
});
});
-describe("Auth Controller - resetPassword", function() {
+describe("Auth Controller - resetPassword", function () {
let req, res, next, newPasswordValidation, handleValidationError, handleError;
- beforeEach(function() {
+ beforeEach(function () {
req = {
body: {
recoveryToken: "recovery-token",
@@ -749,14 +747,14 @@ describe("Auth Controller - resetPassword", function() {
handleError = sinon.stub();
});
- it("should reject with an error if validation fails", async function() {
+ it("should reject with an error if validation fails", async function () {
req.body = { password: "bad_password" };
await resetPassword(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if resetPassword fails", async function() {
+ it("should reject with an error if resetPassword fails", async function () {
const error = new Error("resetPassword error");
newPasswordValidation.validateAsync.resolves();
req.db.resetPassword.rejects(error);
@@ -765,7 +763,7 @@ describe("Auth Controller - resetPassword", function() {
expect(next.firstCall.args[0].message).to.equal("resetPassword error");
});
- it("should reset password successfully", async function() {
+ it("should reset password successfully", async function () {
const user = { _doc: {} };
const appSettings = { jwtSecret: "my_secret" };
const token = "token";
@@ -790,10 +788,10 @@ describe("Auth Controller - resetPassword", function() {
});
});
-describe("Auth Controller - deleteUser", function() {
+describe("Auth Controller - deleteUser", function () {
let req, res, next, handleError;
- beforeEach(function() {
+ beforeEach(function () {
req = {
headers: {
authorization: "Bearer token",
@@ -825,11 +823,11 @@ describe("Auth Controller - deleteUser", function() {
handleError = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should throw an error if user is not found", async function() {
+ it("should throw an error if user is not found", async function () {
jwt.decode.returns({ email: "test@example.com" });
req.db.getUserByEmail.throws(new Error(errorMessages.DB_USER_NOT_FOUND));
@@ -842,7 +840,7 @@ describe("Auth Controller - deleteUser", function() {
expect(res.json.notCalled).to.be.true;
});
- it("should delete user and associated data if user is superadmin", async function() {
+ it("should delete user and associated data if user is superadmin", async function () {
const user = {
_id: "user_id",
email: "test@example.com",
@@ -882,7 +880,7 @@ describe("Auth Controller - deleteUser", function() {
expect(next.notCalled).to.be.true;
});
- it("should delete user if user is not superadmin", async function() {
+ it("should delete user if user is not superadmin", async function () {
const user = {
_id: "user_id",
email: "test@example.com",
@@ -912,7 +910,7 @@ describe("Auth Controller - deleteUser", function() {
expect(next.notCalled).to.be.true;
});
- it("should handle errors", async function() {
+ it("should handle errors", async function () {
const error = new Error("Something went wrong");
const SERVICE_NAME = "AuthController";
jwt.decode.returns({ email: "test@example.com" });
@@ -925,10 +923,10 @@ describe("Auth Controller - deleteUser", function() {
});
});
-describe("Auth Controller - getAllUsers", function() {
+describe("Auth Controller - getAllUsers", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
db: {
getAllUsers: sinon.stub(),
@@ -941,11 +939,11 @@ describe("Auth Controller - getAllUsers", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore(); // Restore the original methods after each test
});
- it("should return 200 and all users", async function() {
+ it("should return 200 and all users", async function () {
const allUsers = [{ id: 1, name: "John Doe" }];
req.db.getAllUsers.resolves(allUsers);
@@ -963,7 +961,7 @@ describe("Auth Controller - getAllUsers", function() {
expect(next.notCalled).to.be.true;
});
- it("should call next with error when an exception occurs", async function() {
+ it("should call next with error when an exception occurs", async function () {
const error = new Error("Something went wrong");
req.db.getAllUsers.rejects(error);
await getAllUsers(req, res, next);
diff --git a/Server/tests/controllers/checkController.test.js b/server/tests/controllers/checkController.test.js
old mode 100644
new mode 100755
similarity index 87%
rename from Server/tests/controllers/checkController.test.js
rename to server/tests/controllers/checkController.test.js
index 0c00b9487..322e6c8ca
--- a/Server/tests/controllers/checkController.test.js
+++ b/server/tests/controllers/checkController.test.js
@@ -9,10 +9,10 @@ import {
import jwt from "jsonwebtoken";
import { errorMessages, successMessages } from "../../utils/messages.js";
import sinon from "sinon";
-describe("Check Controller - createCheck", function() {
+describe("Check Controller - createCheck", function () {
let req, res, next, handleError;
- beforeEach(function() {
+ beforeEach(function () {
req = {
params: {},
body: {},
@@ -28,17 +28,17 @@ describe("Check Controller - createCheck", function() {
handleError = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore(); // Restore the original methods after each test
});
- it("should reject with a validation if params are invalid", async function() {
+ it("should reject with a validation if params are invalid", async function () {
await createCheck(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with a validation error if body is invalid", async function() {
+ it("should reject with a validation error if body is invalid", async function () {
req.params = {
monitorId: "monitorId",
};
@@ -47,7 +47,7 @@ describe("Check Controller - createCheck", function() {
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should call next with error if data retrieval fails", async function() {
+ it("should call next with error if data retrieval fails", async function () {
req.params = {
monitorId: "monitorId",
};
@@ -63,7 +63,7 @@ describe("Check Controller - createCheck", function() {
expect(next.firstCall.args[0]).to.be.an("error");
});
- it("should return a success message if check is created", async function() {
+ it("should return a success message if check is created", async function () {
req.params = {
monitorId: "monitorId",
};
@@ -88,10 +88,10 @@ describe("Check Controller - createCheck", function() {
});
});
-describe("Check Controller - getChecks", function() {
+describe("Check Controller - getChecks", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
params: {},
query: {},
@@ -107,17 +107,17 @@ describe("Check Controller - getChecks", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with a validation error if params are invalid", async function() {
+ it("should reject with a validation error if params are invalid", async function () {
await getChecks(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should return a success message if checks are found", async function() {
+ it("should return a success message if checks are found", async function () {
req.params = {
monitorId: "monitorId",
};
@@ -135,7 +135,7 @@ describe("Check Controller - getChecks", function() {
expect(next.notCalled).to.be.true;
});
- it("should call next with error if data retrieval fails", async function() {
+ it("should call next with error if data retrieval fails", async function () {
req.params = {
monitorId: "monitorId",
};
@@ -145,10 +145,10 @@ describe("Check Controller - getChecks", function() {
});
});
-describe("Check Controller - getTeamChecks", function() {
+describe("Check Controller - getTeamChecks", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
params: {},
query: {},
@@ -163,17 +163,17 @@ describe("Check Controller - getTeamChecks", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with a validation error if params are invalid", async function() {
+ it("should reject with a validation error if params are invalid", async function () {
await getTeamChecks(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should return 200 and check data on successful validation and data retrieval", async function() {
+ it("should return 200 and check data on successful validation and data retrieval", async function () {
req.params = { teamId: "1" };
const checkData = [{ id: 1, name: "Check 1" }];
req.db.getTeamChecks.resolves(checkData);
@@ -190,7 +190,7 @@ describe("Check Controller - getTeamChecks", function() {
).to.be.true;
});
- it("should call next with error if data retrieval fails", async function() {
+ it("should call next with error if data retrieval fails", async function () {
req.params = { teamId: "1" };
req.db.getTeamChecks.rejects(new Error("Retrieval Error"));
await getTeamChecks(req, res, next);
@@ -201,10 +201,10 @@ describe("Check Controller - getTeamChecks", function() {
});
});
-describe("Check Controller - deleteChecks", function() {
+describe("Check Controller - deleteChecks", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
params: {},
db: {
@@ -218,17 +218,17 @@ describe("Check Controller - deleteChecks", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with an error if param validation fails", async function() {
+ it("should reject with an error if param validation fails", async function () {
await deleteChecks(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should call next with error if data retrieval fails", async function() {
+ it("should call next with error if data retrieval fails", async function () {
req.params = { monitorId: "1" };
req.db.deleteChecks.rejects(new Error("Deletion Error"));
await deleteChecks(req, res, next);
@@ -238,7 +238,7 @@ describe("Check Controller - deleteChecks", function() {
expect(res.json.notCalled).to.be.true;
});
- it("should delete checks successfully", async function() {
+ it("should delete checks successfully", async function () {
req.params = { monitorId: "123" };
req.db.deleteChecks.resolves(1);
await deleteChecks(req, res, next);
@@ -254,10 +254,10 @@ describe("Check Controller - deleteChecks", function() {
});
});
-describe("Check Controller - deleteChecksByTeamId", function() {
+describe("Check Controller - deleteChecksByTeamId", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
params: {},
db: {
@@ -271,17 +271,17 @@ describe("Check Controller - deleteChecksByTeamId", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with an error if param validation fails", async function() {
+ it("should reject with an error if param validation fails", async function () {
await deleteChecksByTeamId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should call next with error if data retrieval fails", async function() {
+ it("should call next with error if data retrieval fails", async function () {
req.params = { teamId: "1" };
req.db.deleteChecksByTeamId.rejects(new Error("Deletion Error"));
await deleteChecksByTeamId(req, res, next);
@@ -291,7 +291,7 @@ describe("Check Controller - deleteChecksByTeamId", function() {
expect(res.json.notCalled).to.be.true;
});
- it("should delete checks successfully", async function() {
+ it("should delete checks successfully", async function () {
req.params = { teamId: "123" };
req.db.deleteChecksByTeamId.resolves(1);
await deleteChecksByTeamId(req, res, next);
@@ -307,10 +307,10 @@ describe("Check Controller - deleteChecksByTeamId", function() {
});
});
-describe("Check Controller - updateCheckTTL", function() {
+describe("Check Controller - updateCheckTTL", function () {
let stub, req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" };
});
@@ -332,18 +332,18 @@ describe("Check Controller - updateCheckTTL", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
stub.restore();
});
- it("should reject if body validation fails", async function() {
+ it("should reject if body validation fails", async function () {
await updateChecksTTL(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should throw a JwtError if verification fails", async function() {
+ it("should throw a JwtError if verification fails", async function () {
stub.restore();
req.body = {
ttl: 1,
@@ -352,7 +352,7 @@ describe("Check Controller - updateCheckTTL", function() {
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
});
- it("should call next with error if data retrieval fails", async function() {
+ it("should call next with error if data retrieval fails", async function () {
req.body = {
ttl: 1,
};
@@ -361,7 +361,7 @@ describe("Check Controller - updateCheckTTL", function() {
expect(next.firstCall.args[0]).to.be.an("error");
});
- it("should update TTL successfully", async function() {
+ it("should update TTL successfully", async function () {
req.body = {
ttl: 1,
};
diff --git a/Server/tests/controllers/controllerUtils.test.js b/server/tests/controllers/controllerUtils.test.js
old mode 100644
new mode 100755
similarity index 87%
rename from Server/tests/controllers/controllerUtils.test.js
rename to server/tests/controllers/controllerUtils.test.js
index cb298e8a1..d594e932d
--- a/Server/tests/controllers/controllerUtils.test.js
+++ b/server/tests/controllers/controllerUtils.test.js
@@ -10,22 +10,22 @@ import sslChecker from "ssl-checker";
import { afterEach } from "node:test";
import exp from "constants";
-describe("controllerUtils - handleValidationError", function() {
- it("should set status to 422", function() {
+describe("controllerUtils - handleValidationError", function () {
+ it("should set status to 422", function () {
const error = {};
const serviceName = "TestService";
const result = handleValidationError(error, serviceName);
expect(result.status).to.equal(422);
});
- it("should set service to the provided serviceName", function() {
+ it("should set service to the provided serviceName", function () {
const error = {};
const serviceName = "TestService";
const result = handleValidationError(error, serviceName);
expect(result.service).to.equal(serviceName);
});
- it("should set message to error.details[0].message if present", function() {
+ it("should set message to error.details[0].message if present", function () {
const error = {
details: [{ message: "Detail message" }],
};
@@ -34,7 +34,7 @@ describe("controllerUtils - handleValidationError", function() {
expect(result.message).to.equal("Detail message");
});
- it("should set message to error.message if error.details is not present", function() {
+ it("should set message to error.message if error.details is not present", function () {
const error = {
message: "Error message",
};
@@ -43,7 +43,7 @@ describe("controllerUtils - handleValidationError", function() {
expect(result.message).to.equal("Error message");
});
- it('should set message to "Validation Error" if neither error.details nor error.message is present', function() {
+ it('should set message to "Validation Error" if neither error.details nor error.message is present', function () {
const error = {};
const serviceName = "TestService";
const result = handleValidationError(error, serviceName);
@@ -51,8 +51,8 @@ describe("controllerUtils - handleValidationError", function() {
});
});
-describe("controllerUtils - handleError", function() {
- it("should set stats to the provided status if error.code is undefined", function() {
+describe("controllerUtils - handleError", function () {
+ it("should set stats to the provided status if error.code is undefined", function () {
const error = {};
const serviceName = "TestService";
const method = "testMethod";
@@ -61,7 +61,7 @@ describe("controllerUtils - handleError", function() {
expect(result.status).to.equal(status);
});
- it("should not overwrite error.code if it is already defined", function() {
+ it("should not overwrite error.code if it is already defined", function () {
const error = { status: 404 };
const serviceName = "TestService";
const method = "testMethod";
@@ -70,7 +70,7 @@ describe("controllerUtils - handleError", function() {
expect(result.status).to.equal(404);
});
- it("should set service to the provided serviceName if error.service is undefined", function() {
+ it("should set service to the provided serviceName if error.service is undefined", function () {
const error = {};
const serviceName = "TestService";
const method = "testMethod";
@@ -78,7 +78,7 @@ describe("controllerUtils - handleError", function() {
expect(result.service).to.equal(serviceName);
});
- it("should not overwrite error.service if it is already defined", function() {
+ it("should not overwrite error.service if it is already defined", function () {
const error = { service: "ExistingService" };
const serviceName = "TestService";
const method = "testMethod";
@@ -86,7 +86,7 @@ describe("controllerUtils - handleError", function() {
expect(result.service).to.equal("ExistingService");
});
- it("should set method to the provided method if error.method is undefined", function() {
+ it("should set method to the provided method if error.method is undefined", function () {
const error = {};
const serviceName = "TestService";
const method = "testMethod";
@@ -94,7 +94,7 @@ describe("controllerUtils - handleError", function() {
expect(result.method).to.equal(method);
});
- it("should not overwrite error.method if it is already defined", function() {
+ it("should not overwrite error.method if it is already defined", function () {
const error = { method: "existingMethod" };
const serviceName = "TestService";
const method = "testMethod";
@@ -102,7 +102,7 @@ describe("controllerUtils - handleError", function() {
expect(result.method).to.equal("existingMethod");
});
- it("should set code to 500 if error.code is undefined and no code is provided", function() {
+ it("should set code to 500 if error.code is undefined and no code is provided", function () {
const error = {};
const serviceName = "TestService";
const method = "testMethod";
@@ -111,10 +111,10 @@ describe("controllerUtils - handleError", function() {
});
});
-describe("controllerUtils - fetchMonitorCertificate", function() {
+describe("controllerUtils - fetchMonitorCertificate", function () {
let sslChecker, monitor;
- beforeEach(function() {
+ beforeEach(function () {
monitor = {
url: "https://www.google.com",
};
@@ -125,7 +125,7 @@ describe("controllerUtils - fetchMonitorCertificate", function() {
sinon.restore();
});
- it("should reject with an error if a URL does not parse", async function() {
+ it("should reject with an error if a URL does not parse", async function () {
monitor.url = "invalidurl";
try {
await fetchMonitorCertificate(sslChecker, monitor);
@@ -135,7 +135,7 @@ describe("controllerUtils - fetchMonitorCertificate", function() {
}
});
- it("should reject with an error if sslChecker throws an error", async function() {
+ it("should reject with an error if sslChecker throws an error", async function () {
sslChecker.rejects(new Error("Test error"));
try {
await fetchMonitorCertificate(sslChecker, monitor);
@@ -145,13 +145,13 @@ describe("controllerUtils - fetchMonitorCertificate", function() {
}
});
- it("should return a certificate if sslChecker resolves", async function() {
+ it("should return a certificate if sslChecker resolves", async function () {
sslChecker.resolves({ validTo: "2022-01-01" });
const result = await fetchMonitorCertificate(sslChecker, monitor);
expect(result).to.deep.equal({ validTo: "2022-01-01" });
});
- it("should throw an error if a ssl-checker returns null", async function() {
+ it("should throw an error if a ssl-checker returns null", async function () {
sslChecker.returns(null);
await fetchMonitorCertificate(sslChecker, monitor).catch((error) => {
expect(error).to.be.an("error");
diff --git a/Server/tests/controllers/inviteController.test.js b/server/tests/controllers/inviteController.test.js
old mode 100644
new mode 100755
similarity index 91%
rename from Server/tests/controllers/inviteController.test.js
rename to server/tests/controllers/inviteController.test.js
index 389c4f06d..3311f715e
--- a/Server/tests/controllers/inviteController.test.js
+++ b/server/tests/controllers/inviteController.test.js
@@ -5,10 +5,10 @@ import {
import jwt from "jsonwebtoken";
import sinon from "sinon";
import joi from "joi";
-describe("inviteController - issueInvitation", function() {
+describe("inviteController - issueInvitation", function () {
let req, res, next, stub;
- beforeEach(function() {
+ beforeEach(function () {
req = {
headers: { authorization: "Bearer token" },
body: {
@@ -27,11 +27,11 @@ describe("inviteController - issueInvitation", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with an error if role validation fails", async function() {
+ it("should reject with an error if role validation fails", async function () {
stub = sinon.stub(jwt, "decode").callsFake(() => {
return { role: ["bad_role"], firstname: "first_name", teamId: "1" };
});
@@ -42,7 +42,7 @@ describe("inviteController - issueInvitation", function() {
stub.restore();
});
- it("should reject with an error if body validation fails", async function() {
+ it("should reject with an error if body validation fails", async function () {
stub = sinon.stub(jwt, "decode").callsFake(() => {
return { role: ["admin"], firstname: "first_name", teamId: "1" };
});
@@ -53,7 +53,7 @@ describe("inviteController - issueInvitation", function() {
stub.restore();
});
- it("should reject with an error if DB operations fail", async function() {
+ it("should reject with an error if DB operations fail", async function () {
stub = sinon.stub(jwt, "decode").callsFake(() => {
return { role: ["admin"], firstname: "first_name", teamId: "1" };
});
@@ -64,7 +64,7 @@ describe("inviteController - issueInvitation", function() {
stub.restore();
});
- it("should send an invite successfully", async function() {
+ it("should send an invite successfully", async function () {
const token = "token";
const decodedToken = {
role: "admin",
@@ -92,7 +92,7 @@ describe("inviteController - issueInvitation", function() {
stub.restore();
});
- it("should send an email successfully", async function() {
+ it("should send an email successfully", async function () {
const token = "token";
const decodedToken = {
role: "admin",
@@ -125,7 +125,7 @@ describe("inviteController - issueInvitation", function() {
stub.restore();
});
- it("should continue executing if sending an email fails", async function() {
+ it("should continue executing if sending an email fails", async function () {
const token = "token";
req.emailService.buildAndSendEmail.rejects(new Error("Email error"));
const decodedToken = {
@@ -154,10 +154,10 @@ describe("inviteController - issueInvitation", function() {
});
});
-describe("inviteController - inviteVerifyController", function() {
+describe("inviteController - inviteVerifyController", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
body: { token: "token" },
db: {
@@ -171,25 +171,25 @@ describe("inviteController - inviteVerifyController", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with an error if body validation fails", async function() {
+ it("should reject with an error if body validation fails", async function () {
req.body = {};
await inviteVerifyController(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if DB operations fail", async function() {
+ it("should reject with an error if DB operations fail", async function () {
req.db.getInviteToken.throws(new Error("DB error"));
await inviteVerifyController(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should return 200 and invite data when validation and invite retrieval are successful", async function() {
+ it("should return 200 and invite data when validation and invite retrieval are successful", async function () {
req.db.getInviteToken.resolves({ invite: "data" });
await inviteVerifyController(req, res, next);
expect(res.status.calledWith(200)).to.be.true;
diff --git a/Server/tests/controllers/maintenanceWindowController.test.js b/server/tests/controllers/maintenanceWindowController.test.js
old mode 100644
new mode 100755
similarity index 89%
rename from Server/tests/controllers/maintenanceWindowController.test.js
rename to server/tests/controllers/maintenanceWindowController.test.js
index 974bc07be..0ea07b389
--- a/Server/tests/controllers/maintenanceWindowController.test.js
+++ b/server/tests/controllers/maintenanceWindowController.test.js
@@ -11,10 +11,10 @@ import jwt from "jsonwebtoken";
import { successMessages } from "../../utils/messages.js";
import sinon from "sinon";
-describe("maintenanceWindowController - createMaintenanceWindows", function() {
+describe("maintenanceWindowController - createMaintenanceWindows", function () {
let req, res, next, stub;
- beforeEach(function() {
+ beforeEach(function () {
req = {
body: {
monitors: ["66ff52e7c5911c61698ac724"],
@@ -41,11 +41,11 @@ describe("maintenanceWindowController - createMaintenanceWindows", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with an error if body validation fails", async function() {
+ it("should reject with an error if body validation fails", async function () {
stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" };
});
@@ -56,14 +56,14 @@ describe("maintenanceWindowController - createMaintenanceWindows", function() {
stub.restore();
});
- it("should reject with an error if jwt.verify fails", async function() {
+ it("should reject with an error if jwt.verify fails", async function () {
stub = sinon.stub(jwt, "verify").throws(new jwt.JsonWebTokenError());
await createMaintenanceWindows(req, res, next);
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
stub.restore();
});
- it("should reject with an error DB operations fail", async function() {
+ it("should reject with an error DB operations fail", async function () {
stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" };
});
@@ -74,7 +74,7 @@ describe("maintenanceWindowController - createMaintenanceWindows", function() {
stub.restore();
});
- it("should return success message if all operations are successful", async function() {
+ it("should return success message if all operations are successful", async function () {
stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" };
});
@@ -89,7 +89,7 @@ describe("maintenanceWindowController - createMaintenanceWindows", function() {
stub.restore();
});
- it("should return success message if all operations are successful with active set to undefined", async function() {
+ it("should return success message if all operations are successful with active set to undefined", async function () {
req.body.active = undefined;
stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" };
@@ -106,10 +106,10 @@ describe("maintenanceWindowController - createMaintenanceWindows", function() {
});
});
-describe("maintenanceWindowController - getMaintenanceWindowById", function() {
+describe("maintenanceWindowController - getMaintenanceWindowById", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
body: {},
params: {
@@ -132,21 +132,21 @@ describe("maintenanceWindowController - getMaintenanceWindowById", function() {
next = sinon.stub();
});
- it("should reject if param validation fails", async function() {
+ it("should reject if param validation fails", async function () {
req.params = {};
await getMaintenanceWindowById(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject if DB operations fail", async function() {
+ it("should reject if DB operations fail", async function () {
req.db.getMaintenanceWindowById.throws(new Error("DB error"));
await getMaintenanceWindowById(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should return success message with data if all operations are successful", async function() {
+ it("should return success message with data if all operations are successful", async function () {
req.db.getMaintenanceWindowById.returns({ id: "123" });
await getMaintenanceWindowById(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200);
@@ -160,10 +160,10 @@ describe("maintenanceWindowController - getMaintenanceWindowById", function() {
});
});
-describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function() {
+describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function () {
let req, res, next, stub;
- beforeEach(function() {
+ beforeEach(function () {
req = {
body: {},
params: {},
@@ -185,7 +185,7 @@ describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function
next = sinon.stub();
});
- it("should reject if query validation fails", async function() {
+ it("should reject if query validation fails", async function () {
req.query = {
invalid: 1,
};
@@ -194,14 +194,14 @@ describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject if jwt.verify fails", async function() {
+ it("should reject if jwt.verify fails", async function () {
stub = sinon.stub(jwt, "verify").throws(new jwt.JsonWebTokenError());
await getMaintenanceWindowsByTeamId(req, res, next);
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
stub.restore();
});
- it("should reject with an error if DB operations fail", async function() {
+ it("should reject with an error if DB operations fail", async function () {
stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" };
});
@@ -212,7 +212,7 @@ describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function
stub.restore();
});
- it("should return success message with data if all operations are successful", async function() {
+ it("should return success message with data if all operations are successful", async function () {
stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" };
});
@@ -230,10 +230,10 @@ describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function
});
});
-describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", function() {
+describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
body: {},
params: {
@@ -257,25 +257,25 @@ describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", funct
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject if param validation fails", async function() {
+ it("should reject if param validation fails", async function () {
req.params = {};
await getMaintenanceWindowsByMonitorId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if DB operations fail", async function() {
+ it("should reject with an error if DB operations fail", async function () {
req.db.getMaintenanceWindowsByMonitorId.throws(new Error("DB error"));
await getMaintenanceWindowsByMonitorId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should return success message with data if all operations are successful", async function() {
+ it("should return success message with data if all operations are successful", async function () {
const data = [{ monitorId: "123" }];
req.db.getMaintenanceWindowsByMonitorId.returns(data);
await getMaintenanceWindowsByMonitorId(req, res, next);
@@ -291,10 +291,10 @@ describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", funct
});
});
-describe("maintenanceWindowController - deleteMaintenanceWindow", function() {
+describe("maintenanceWindowController - deleteMaintenanceWindow", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
body: {},
params: {
@@ -318,25 +318,25 @@ describe("maintenanceWindowController - deleteMaintenanceWindow", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject if param validation fails", async function() {
+ it("should reject if param validation fails", async function () {
req.params = {};
await deleteMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if DB operations fail", async function() {
+ it("should reject with an error if DB operations fail", async function () {
req.db.deleteMaintenanceWindowById.throws(new Error("DB error"));
await deleteMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should return success message if all operations are successful", async function() {
+ it("should return success message if all operations are successful", async function () {
await deleteMaintenanceWindow(req, res, next);
expect(req.db.deleteMaintenanceWindowById.calledOnceWith(req.params.id));
expect(res.status.firstCall.args[0]).to.equal(200);
@@ -349,10 +349,10 @@ describe("maintenanceWindowController - deleteMaintenanceWindow", function() {
});
});
-describe("maintenanceWindowController - editMaintenanceWindow", function() {
+describe("maintenanceWindowController - editMaintenanceWindow", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
body: {
active: true,
@@ -379,32 +379,32 @@ describe("maintenanceWindowController - editMaintenanceWindow", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject if param validation fails", async function() {
+ it("should reject if param validation fails", async function () {
req.params = {};
await editMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject if body validation fails", async function() {
+ it("should reject if body validation fails", async function () {
req.body = { invalid: 1 };
await editMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if DB operations fail", async function() {
+ it("should reject with an error if DB operations fail", async function () {
req.db.editMaintenanceWindowById.throws(new Error("DB error"));
await editMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should return success message with data if all operations are successful", async function() {
+ it("should return success message with data if all operations are successful", async function () {
const data = { id: "123" };
req.db.editMaintenanceWindowById.returns(data);
diff --git a/Server/tests/controllers/monitorController.test.js b/server/tests/controllers/monitorController.test.js
old mode 100644
new mode 100755
similarity index 91%
rename from Server/tests/controllers/monitorController.test.js
rename to server/tests/controllers/monitorController.test.js
index 33440d897..5aa68b514
--- a/Server/tests/controllers/monitorController.test.js
+++ b/server/tests/controllers/monitorController.test.js
@@ -21,10 +21,10 @@ import logger from "../../utils/logger.js";
import axios from "axios";
const SERVICE_NAME = "monitorController";
-describe("Monitor Controller - getAllMonitors", function() {
+describe("Monitor Controller - getAllMonitors", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
params: {},
query: {},
@@ -40,18 +40,18 @@ describe("Monitor Controller - getAllMonitors", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with an error if DB operations fail", async function() {
+ it("should reject with an error if DB operations fail", async function () {
req.db.getAllMonitors.throws(new Error("DB error"));
await getAllMonitors(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should return success message and data if all operations succeed", async function() {
+ it("should return success message and data if all operations succeed", async function () {
const data = [{ monitor: "data" }];
req.db.getAllMonitors.returns(data);
await getAllMonitors(req, res, next);
@@ -65,10 +65,10 @@ describe("Monitor Controller - getAllMonitors", function() {
).to.be.true;
});
});
-describe("Monitor Controller - getAllMonitorsWithUptimeStats", function() {
+describe("Monitor Controller - getAllMonitorsWithUptimeStats", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
params: {},
query: {},
@@ -84,18 +84,18 @@ describe("Monitor Controller - getAllMonitorsWithUptimeStats", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with an error if DB operations fail", async function() {
+ it("should reject with an error if DB operations fail", async function () {
req.db.getAllMonitorsWithUptimeStats.throws(new Error("DB error"));
await getAllMonitorsWithUptimeStats(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should return success message and data if all operations succeed", async function() {
+ it("should return success message and data if all operations succeed", async function () {
const data = [{ monitor: "data" }];
req.db.getAllMonitorsWithUptimeStats.returns(data);
await getAllMonitorsWithUptimeStats(req, res, next);
@@ -110,10 +110,10 @@ describe("Monitor Controller - getAllMonitorsWithUptimeStats", function() {
});
});
-describe("Monitor Controller - getMonitorStatsById", function() {
+describe("Monitor Controller - getMonitorStatsById", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
params: {
monitorId: "123",
@@ -131,32 +131,32 @@ describe("Monitor Controller - getMonitorStatsById", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with an error if param validation fails", async function() {
+ it("should reject with an error if param validation fails", async function () {
req.params = {};
await getMonitorStatsById(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if query validation fails", async function() {
+ it("should reject with an error if query validation fails", async function () {
req.query = { invalid: 1 };
await getMonitorStatsById(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if DB operations fail", async function() {
+ it("should reject with an error if DB operations fail", async function () {
req.db.getMonitorStatsById.throws(new Error("DB error"));
await getMonitorStatsById(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should return success message and data if all operations succeed", async function() {
+ it("should return success message and data if all operations succeed", async function () {
const data = [{ monitorStats: "data" }];
req.db.getMonitorStatsById.returns(data);
await getMonitorStatsById(req, res, next);
@@ -171,10 +171,10 @@ describe("Monitor Controller - getMonitorStatsById", function() {
});
});
-describe("Monitor Controller - getMonitorCertificate", function() {
+describe("Monitor Controller - getMonitorCertificate", function () {
let req, res, next, fetchMonitorCertificate;
- beforeEach(function() {
+ beforeEach(function () {
req = {
params: {
monitorId: "123",
@@ -193,25 +193,25 @@ describe("Monitor Controller - getMonitorCertificate", function() {
fetchMonitorCertificate = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with an error if param validation fails", async function() {
+ it("should reject with an error if param validation fails", async function () {
req.params = {};
await getMonitorCertificate(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if getMonitorById operation fails", async function() {
+ it("should reject with an error if getMonitorById operation fails", async function () {
req.db.getMonitorById.throws(new Error("DB error"));
await getMonitorCertificate(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should return success message and data if all operations succeed with a valid cert", async function() {
+ it("should return success message and data if all operations succeed with a valid cert", async function () {
req.db.getMonitorById.returns({ url: "https://www.google.com" });
const data = { certificate: "cert", validTo: "2024/08/08" };
fetchMonitorCertificate.returns(data);
@@ -226,7 +226,7 @@ describe("Monitor Controller - getMonitorCertificate", function() {
).to.be.true;
});
- it("should return an error if fetchMonitorCertificate fails", async function() {
+ it("should return an error if fetchMonitorCertificate fails", async function () {
req.db.getMonitorById.returns({ url: "https://www.google.com" });
fetchMonitorCertificate.throws(new Error("Certificate error"));
await getMonitorCertificate(req, res, next, fetchMonitorCertificate);
@@ -235,10 +235,10 @@ describe("Monitor Controller - getMonitorCertificate", function() {
});
});
-describe("Monitor Controller - getMonitorById", function() {
+describe("Monitor Controller - getMonitorById", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
params: {
monitorId: "123",
@@ -256,32 +256,32 @@ describe("Monitor Controller - getMonitorById", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with an error if param validation fails", async function() {
+ it("should reject with an error if param validation fails", async function () {
req.params = {};
await getMonitorById(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if query param validation fails", async function() {
+ it("should reject with an error if query param validation fails", async function () {
req.query = { invalid: 1 };
await getMonitorById(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if DB operations fail", async function() {
+ it("should reject with an error if DB operations fail", async function () {
req.db.getMonitorById.throws(new Error("DB error"));
await getMonitorById(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should return 404 if a monitor is not found", async function() {
+ it("should return 404 if a monitor is not found", async function () {
const error = new Error("Monitor not found");
error.status = 404;
req.db.getMonitorById.throws(error);
@@ -290,7 +290,7 @@ describe("Monitor Controller - getMonitorById", function() {
expect(next.firstCall.args[0].status).to.equal(404);
});
- it("should return success message and data if all operations succeed", async function() {
+ it("should return success message and data if all operations succeed", async function () {
const data = { monitor: "data" };
req.db.getMonitorById.returns(data);
await getMonitorById(req, res, next);
@@ -305,10 +305,10 @@ describe("Monitor Controller - getMonitorById", function() {
});
});
-describe("Monitor Controller - getMonitorsAndSummaryByTeamId", function() {
+describe("Monitor Controller - getMonitorsAndSummaryByTeamId", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
params: {
teamId: "123",
@@ -326,32 +326,32 @@ describe("Monitor Controller - getMonitorsAndSummaryByTeamId", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with an error if param validation fails", async function() {
+ it("should reject with an error if param validation fails", async function () {
req.params = {};
await getMonitorsAndSummaryByTeamId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if query validation fails", async function() {
+ it("should reject with an error if query validation fails", async function () {
req.query = { invalid: 1 };
await getMonitorsAndSummaryByTeamId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if DB operations fail", async function() {
+ it("should reject with an error if DB operations fail", async function () {
req.db.getMonitorsAndSummaryByTeamId.throws(new Error("DB error"));
await getMonitorsAndSummaryByTeamId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should return success message and data if all operations succeed", async function() {
+ it("should return success message and data if all operations succeed", async function () {
const data = { monitors: "data", summary: "data" };
req.db.getMonitorsAndSummaryByTeamId.returns(data);
await getMonitorsAndSummaryByTeamId(req, res, next);
@@ -366,10 +366,10 @@ describe("Monitor Controller - getMonitorsAndSummaryByTeamId", function() {
});
});
-describe("Monitor Controller - getMonitorsByTeamId", function() {
+describe("Monitor Controller - getMonitorsByTeamId", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
params: {
teamId: "123",
@@ -387,32 +387,32 @@ describe("Monitor Controller - getMonitorsByTeamId", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with an error if param validation fails", async function() {
+ it("should reject with an error if param validation fails", async function () {
req.params = {};
await getMonitorsByTeamId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if query validation fails", async function() {
+ it("should reject with an error if query validation fails", async function () {
req.query = { invalid: 1 };
await getMonitorsByTeamId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if DB operations fail", async function() {
+ it("should reject with an error if DB operations fail", async function () {
req.db.getMonitorsByTeamId.throws(new Error("DB error"));
await getMonitorsByTeamId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should return success message and data if all operations succeed", async function() {
+ it("should return success message and data if all operations succeed", async function () {
const data = { monitors: "data" };
req.db.getMonitorsByTeamId.returns(data);
await getMonitorsByTeamId(req, res, next);
@@ -427,10 +427,10 @@ describe("Monitor Controller - getMonitorsByTeamId", function() {
});
});
-describe("Monitor Controller - createMonitor", function() {
+describe("Monitor Controller - createMonitor", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
params: {},
query: {},
@@ -458,25 +458,25 @@ describe("Monitor Controller - createMonitor", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with an error if body validation fails", async function() {
+ it("should reject with an error if body validation fails", async function () {
req.body = {};
await createMonitor(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if DB createMonitor operation fail", async function() {
+ it("should reject with an error if DB createMonitor operation fail", async function () {
req.db.createMonitor.throws(new Error("DB error"));
await createMonitor(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should reject with an error if DB createNotification operation fail", async function() {
+ it("should reject with an error if DB createNotification operation fail", async function () {
req.db.createNotification.throws(new Error("DB error"));
req.db.createMonitor.returns({ _id: "123" });
await createMonitor(req, res, next);
@@ -484,7 +484,7 @@ describe("Monitor Controller - createMonitor", function() {
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should reject with an error if monitor.save operation fail", async function() {
+ it("should reject with an error if monitor.save operation fail", async function () {
req.db.createMonitor.returns({
_id: "123",
save: sinon.stub().throws(new Error("Monitor save error")),
@@ -494,7 +494,7 @@ describe("Monitor Controller - createMonitor", function() {
expect(next.firstCall.args[0].message).to.equal("Monitor save error");
});
- it("should throw an error if addJob operation fails", async function() {
+ it("should throw an error if addJob operation fails", async function () {
req.db.createMonitor.returns({ _id: "123", save: sinon.stub() });
req.jobQueue.addJob.throws(new Error("Job error"));
await createMonitor(req, res, next);
@@ -502,7 +502,7 @@ describe("Monitor Controller - createMonitor", function() {
expect(next.firstCall.args[0].message).to.equal("Job error");
});
- it("should return success message and data if all operations succeed", async function() {
+ it("should return success message and data if all operations succeed", async function () {
const monitor = { _id: "123", save: sinon.stub() };
req.db.createMonitor.returns(monitor);
await createMonitor(req, res, next);
@@ -517,21 +517,21 @@ describe("Monitor Controller - createMonitor", function() {
});
});
-describe("Monitor Controller - checkEndpointResolution", function() {
+describe("Monitor Controller - checkEndpointResolution", function () {
let req, res, next, axiosGetStub;
- beforeEach(function() {
+ beforeEach(function () {
req = { query: { monitorURL: "https://example.com" } };
res = { status: sinon.stub().returnsThis(), json: sinon.stub() };
next = sinon.stub();
axiosGetStub = sinon.stub(axios, "get");
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should resolve the URL successfully", async function() {
+ it("should resolve the URL successfully", async function () {
axiosGetStub.resolves({ status: 200, statusText: "OK" });
await checkEndpointResolution(req, res, next);
expect(res.status.calledWith(200)).to.be.true;
@@ -546,7 +546,7 @@ describe("Monitor Controller - checkEndpointResolution", function() {
expect(next.called).to.be.false;
});
- it("should return an error if endpoint resolution fails", async function() {
+ it("should return an error if endpoint resolution fails", async function () {
const axiosError = new Error("resolution failed");
axiosError.code = "ENOTFOUND";
axiosGetStub.rejects(axiosError);
@@ -559,7 +559,7 @@ describe("Monitor Controller - checkEndpointResolution", function() {
expect(errorPassedToNext.status).to.equal(500);
});
- it("should reject with an error if query validation fails", async function() {
+ it("should reject with an error if query validation fails", async function () {
req.query.monitorURL = "invalid-url";
await checkEndpointResolution(req, res, next);
expect(next.calledOnce).to.be.true;
@@ -570,10 +570,10 @@ describe("Monitor Controller - checkEndpointResolution", function() {
});
});
-describe("Monitor Controller - deleteMonitor", function() {
+describe("Monitor Controller - deleteMonitor", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
params: {
monitorId: "123",
@@ -598,25 +598,25 @@ describe("Monitor Controller - deleteMonitor", function() {
sinon.stub(logger, "error");
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with an error if param validation fails", async function() {
+ it("should reject with an error if param validation fails", async function () {
req.params = {};
await deleteMonitor(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if DB deleteMonitor operation fail", async function() {
+ it("should reject with an error if DB deleteMonitor operation fail", async function () {
req.db.deleteMonitor.throws(new Error("DB error"));
await deleteMonitor(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should log an error if deleteJob throws an error", async function() {
+ it("should log an error if deleteJob throws an error", async function () {
const error = new Error("Job error");
const monitor = { name: "test_monitor", _id: "123" };
req.db.deleteMonitor.returns(monitor);
@@ -628,7 +628,7 @@ describe("Monitor Controller - deleteMonitor", function() {
);
});
- it("should log an error if deleteChecks throws an error", async function() {
+ it("should log an error if deleteChecks throws an error", async function () {
const error = new Error("Checks error");
const monitor = { name: "test_monitor", _id: "123" };
req.db.deleteMonitor.returns(monitor);
@@ -640,7 +640,7 @@ describe("Monitor Controller - deleteMonitor", function() {
);
});
- it("should log an error if deletePageSpeedChecksByMonitorId throws an error", async function() {
+ it("should log an error if deletePageSpeedChecksByMonitorId throws an error", async function () {
const error = new Error("PageSpeed error");
const monitor = { name: "test_monitor", _id: "123" };
req.db.deleteMonitor.returns(monitor);
@@ -652,7 +652,7 @@ describe("Monitor Controller - deleteMonitor", function() {
);
});
- it("should log an error if deleteNotificationsByMonitorId throws an error", async function() {
+ it("should log an error if deleteNotificationsByMonitorId throws an error", async function () {
const error = new Error("Notifications error");
const monitor = { name: "test_monitor", _id: "123" };
req.db.deleteMonitor.returns(monitor);
@@ -664,7 +664,7 @@ describe("Monitor Controller - deleteMonitor", function() {
);
});
- it("should return success message if all operations succeed", async function() {
+ it("should return success message if all operations succeed", async function () {
const monitor = { name: "test_monitor", _id: "123" };
req.db.deleteMonitor.returns(monitor);
await deleteMonitor(req, res, next);
@@ -678,10 +678,10 @@ describe("Monitor Controller - deleteMonitor", function() {
});
});
-describe("Monitor Controller - deleteAllMonitors", function() {
+describe("Monitor Controller - deleteAllMonitors", function () {
let req, res, next, stub;
- beforeEach(function() {
+ beforeEach(function () {
stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" };
});
@@ -715,12 +715,12 @@ describe("Monitor Controller - deleteAllMonitors", function() {
sinon.stub(logger, "error");
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
stub.restore();
});
- it("should reject with an error if getTokenFromHeaders throws an error", async function() {
+ it("should reject with an error if getTokenFromHeaders throws an error", async function () {
req.headers = {};
await deleteAllMonitors(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
@@ -728,14 +728,14 @@ describe("Monitor Controller - deleteAllMonitors", function() {
expect(next.firstCall.args[0].status).to.equal(500);
});
- it("should reject with an error if token validation fails", async function() {
+ it("should reject with an error if token validation fails", async function () {
stub.restore();
req.settingsService.getSettings.returns({ jwtSecret: "my_secret" });
await deleteAllMonitors(req, res, next);
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
});
- it("should reject with an error if DB deleteAllMonitors operation fail", async function() {
+ it("should reject with an error if DB deleteAllMonitors operation fail", async function () {
req.settingsService.getSettings.returns({ jwtSecret: "my_secret" });
req.db.deleteAllMonitors.throws(new Error("DB error"));
await deleteAllMonitors(req, res, next);
@@ -743,7 +743,7 @@ describe("Monitor Controller - deleteAllMonitors", function() {
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should log an error if deleteChecks throws an error", async function() {
+ it("should log an error if deleteChecks throws an error", async function () {
const monitors = [{ name: "test_monitor", _id: "123" }];
req.settingsService.getSettings.returns({ jwtSecret: "my_secret" });
req.db.deleteAllMonitors.returns({ monitors, deletedCount: 1 });
@@ -756,7 +756,7 @@ describe("Monitor Controller - deleteAllMonitors", function() {
);
});
- it("should log an error if deletePageSpeedChecksByMonitorId throws an error", async function() {
+ it("should log an error if deletePageSpeedChecksByMonitorId throws an error", async function () {
const monitors = [{ name: "test_monitor", _id: "123" }];
req.settingsService.getSettings.returns({ jwtSecret: "my_secret" });
req.db.deleteAllMonitors.returns({ monitors, deletedCount: 1 });
@@ -769,7 +769,7 @@ describe("Monitor Controller - deleteAllMonitors", function() {
);
});
- it("should log an error if deleteNotificationsByMonitorId throws an error", async function() {
+ it("should log an error if deleteNotificationsByMonitorId throws an error", async function () {
const monitors = [{ name: "test_monitor", _id: "123" }];
req.settingsService.getSettings.returns({ jwtSecret: "my_secret" });
req.db.deleteAllMonitors.returns({ monitors, deletedCount: 1 });
@@ -782,7 +782,7 @@ describe("Monitor Controller - deleteAllMonitors", function() {
);
});
- it("should return success message if all operations succeed", async function() {
+ it("should return success message if all operations succeed", async function () {
req.settingsService.getSettings.returns({ jwtSecret: "my_secret" });
req.db.deleteAllMonitors.returns({
monitors: [{ name: "test_monitor", _id: "123" }],
@@ -799,10 +799,10 @@ describe("Monitor Controller - deleteAllMonitors", function() {
});
});
-describe("Monitor Controller - editMonitor", function() {
+describe("Monitor Controller - editMonitor", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
headers: {},
params: {
@@ -833,32 +833,32 @@ describe("Monitor Controller - editMonitor", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with an error if param validation fails", async function() {
+ it("should reject with an error if param validation fails", async function () {
req.params = {};
await editMonitor(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if body validation fails", async function() {
+ it("should reject with an error if body validation fails", async function () {
req.body = { invalid: 1 };
await editMonitor(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if getMonitorById operation fails", async function() {
+ it("should reject with an error if getMonitorById operation fails", async function () {
req.db.getMonitorById.throws(new Error("DB error"));
await editMonitor(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should reject with an error if editMonitor operation fails", async function() {
+ it("should reject with an error if editMonitor operation fails", async function () {
req.db.getMonitorById.returns({ teamId: "123" });
req.db.editMonitor.throws(new Error("DB error"));
await editMonitor(req, res, next);
@@ -866,7 +866,7 @@ describe("Monitor Controller - editMonitor", function() {
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should reject with an error if deleteNotificationsByMonitorId operation fails", async function() {
+ it("should reject with an error if deleteNotificationsByMonitorId operation fails", async function () {
req.db.getMonitorById.returns({ teamId: "123" });
req.db.editMonitor.returns({ _id: "123" });
req.db.deleteNotificationsByMonitorId.throws(new Error("DB error"));
@@ -875,7 +875,7 @@ describe("Monitor Controller - editMonitor", function() {
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should reject with an error if createNotification operation fails", async function() {
+ it("should reject with an error if createNotification operation fails", async function () {
req.db.getMonitorById.returns({ teamId: "123" });
req.db.editMonitor.returns({ _id: "123" });
req.db.createNotification.throws(new Error("DB error"));
@@ -884,7 +884,7 @@ describe("Monitor Controller - editMonitor", function() {
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should reject with an error if deleteJob operation fails", async function() {
+ it("should reject with an error if deleteJob operation fails", async function () {
req.db.getMonitorById.returns({ teamId: "123" });
req.db.editMonitor.returns({ _id: "123" });
req.jobQueue.deleteJob.throws(new Error("Job error"));
@@ -893,7 +893,7 @@ describe("Monitor Controller - editMonitor", function() {
expect(next.firstCall.args[0].message).to.equal("Job error");
});
- it("should reject with an error if addJob operation fails", async function() {
+ it("should reject with an error if addJob operation fails", async function () {
req.db.getMonitorById.returns({ teamId: "123" });
req.db.editMonitor.returns({ _id: "123" });
req.jobQueue.addJob.throws(new Error("Add Job error"));
@@ -902,7 +902,7 @@ describe("Monitor Controller - editMonitor", function() {
expect(next.firstCall.args[0].message).to.equal("Add Job error");
});
- it("should return success message with data if all operations succeed", async function() {
+ it("should return success message with data if all operations succeed", async function () {
const monitor = { _id: "123" };
req.db.getMonitorById.returns({ teamId: "123" });
req.db.editMonitor.returns(monitor);
@@ -918,10 +918,10 @@ describe("Monitor Controller - editMonitor", function() {
});
});
-describe("Monitor Controller - pauseMonitor", function() {
+describe("Monitor Controller - pauseMonitor", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
headers: {},
params: {
@@ -947,25 +947,25 @@ describe("Monitor Controller - pauseMonitor", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should reject with an error if param validation fails", async function() {
+ it("should reject with an error if param validation fails", async function () {
req.params = {};
await pauseMonitor(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if getMonitorById operation fails", async function() {
+ it("should reject with an error if getMonitorById operation fails", async function () {
req.db.getMonitorById.throws(new Error("DB error"));
await pauseMonitor(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should reject with an error if deleteJob operation fails", async function() {
+ it("should reject with an error if deleteJob operation fails", async function () {
const monitor = { _id: req.params.monitorId, isActive: true };
req.db.getMonitorById.returns(monitor);
req.jobQueue.deleteJob.throws(new Error("Delete Job error"));
@@ -974,7 +974,7 @@ describe("Monitor Controller - pauseMonitor", function() {
expect(next.firstCall.args[0].message).to.equal("Delete Job error");
});
- it("should reject with an error if addJob operation fails", async function() {
+ it("should reject with an error if addJob operation fails", async function () {
const monitor = { _id: req.params.monitorId, isActive: false };
req.db.getMonitorById.returns(monitor);
req.jobQueue.addJob.throws(new Error("Add Job error"));
@@ -983,7 +983,7 @@ describe("Monitor Controller - pauseMonitor", function() {
expect(next.firstCall.args[0].message).to.equal("Add Job error");
});
- it("should reject with an error if monitor.save operation fails", async function() {
+ it("should reject with an error if monitor.save operation fails", async function () {
const monitor = {
_id: req.params.monitorId,
active: false,
@@ -995,7 +995,7 @@ describe("Monitor Controller - pauseMonitor", function() {
expect(next.firstCall.args[0].message).to.equal("Save error");
});
- it("should return success pause message with data if all operations succeed with inactive monitor", async function() {
+ it("should return success pause message with data if all operations succeed with inactive monitor", async function () {
const monitor = {
_id: req.params.monitorId,
isActive: false,
@@ -1013,7 +1013,7 @@ describe("Monitor Controller - pauseMonitor", function() {
).to.be.true;
});
- it("should return success resume message with data if all operations succeed with active monitor", async function() {
+ it("should return success resume message with data if all operations succeed with active monitor", async function () {
const monitor = {
_id: req.params.monitorId,
isActive: true,
@@ -1032,10 +1032,10 @@ describe("Monitor Controller - pauseMonitor", function() {
});
});
-describe("Monitor Controller - addDemoMonitors", function() {
+describe("Monitor Controller - addDemoMonitors", function () {
let req, res, next, stub;
- beforeEach(function() {
+ beforeEach(function () {
stub = sinon.stub(jwt, "verify").callsFake(() => {
return { _id: "123", teamId: "123" };
});
@@ -1063,12 +1063,12 @@ describe("Monitor Controller - addDemoMonitors", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
stub.restore();
});
- it("should reject with an error if getTokenFromHeaders fails", async function() {
+ it("should reject with an error if getTokenFromHeaders fails", async function () {
req.headers = {};
await addDemoMonitors(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
@@ -1076,21 +1076,21 @@ describe("Monitor Controller - addDemoMonitors", function() {
expect(next.firstCall.args[0].status).to.equal(500);
});
- it("should reject with an error if getting settings fails", async function() {
+ it("should reject with an error if getting settings fails", async function () {
req.settingsService.getSettings.throws(new Error("Settings error"));
await addDemoMonitors(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("Settings error");
});
- it("should reject with an error if JWT validation fails", async function() {
+ it("should reject with an error if JWT validation fails", async function () {
stub.restore();
req.settingsService.getSettings.returns({ jwtSecret: "my_secret" });
await addDemoMonitors(req, res, next);
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
});
- it("should reject with an error if addDemoMonitors operation fails", async function() {
+ it("should reject with an error if addDemoMonitors operation fails", async function () {
req.settingsService.getSettings.returns({ jwtSecret: "my_secret" });
req.db.addDemoMonitors.throws(new Error("DB error"));
await addDemoMonitors(req, res, next);
@@ -1098,7 +1098,7 @@ describe("Monitor Controller - addDemoMonitors", function() {
expect(next.firstCall.args[0].message).to.equal("DB error");
});
- it("should reject with an error if addJob operation fails", async function() {
+ it("should reject with an error if addJob operation fails", async function () {
req.settingsService.getSettings.returns({ jwtSecret: "my_secret" });
req.db.addDemoMonitors.returns([{ _id: "123" }]);
req.jobQueue.addJob.throws(new Error("Add Job error"));
@@ -1107,7 +1107,7 @@ describe("Monitor Controller - addDemoMonitors", function() {
expect(next.firstCall.args[0].message).to.equal("Add Job error");
});
- it("should return success message with data if all operations succeed", async function() {
+ it("should return success message with data if all operations succeed", async function () {
const monitors = [{ _id: "123" }];
req.settingsService.getSettings.returns({ jwtSecret: "my_secret" });
req.db.addDemoMonitors.returns(monitors);
diff --git a/Server/tests/controllers/queueController.test.js b/server/tests/controllers/queueController.test.js
old mode 100644
new mode 100755
similarity index 88%
rename from Server/tests/controllers/queueController.test.js
rename to server/tests/controllers/queueController.test.js
index b04504186..72450a0bd
--- a/Server/tests/controllers/queueController.test.js
+++ b/server/tests/controllers/queueController.test.js
@@ -8,10 +8,10 @@ import {
import { successMessages } from "../../utils/messages.js";
import sinon from "sinon";
-describe("Queue Controller - getMetrics", function() {
+describe("Queue Controller - getMetrics", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
headers: {},
params: {},
@@ -32,14 +32,14 @@ describe("Queue Controller - getMetrics", function() {
sinon.restore();
});
- it("should throw an error if getMetrics throws an error", async function() {
+ it("should throw an error if getMetrics throws an error", async function () {
req.jobQueue.getMetrics.throws(new Error("getMetrics error"));
await getMetrics(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getMetrics error");
});
- it("should return a success message and data if getMetrics is successful", async function() {
+ it("should return a success message and data if getMetrics is successful", async function () {
const data = { data: "metrics" };
req.jobQueue.getMetrics.returns(data);
await getMetrics(req, res, next);
@@ -52,10 +52,10 @@ describe("Queue Controller - getMetrics", function() {
});
});
-describe("Queue Controller - getJobs", function() {
+describe("Queue Controller - getJobs", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
headers: {},
params: {},
@@ -76,14 +76,14 @@ describe("Queue Controller - getJobs", function() {
sinon.restore();
});
- it("should reject with an error if getJobs throws an error", async function() {
+ it("should reject with an error if getJobs throws an error", async function () {
req.jobQueue.getJobStats.throws(new Error("getJobs error"));
await getJobs(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getJobs error");
});
- it("should return a success message and data if getJobs is successful", async function() {
+ it("should return a success message and data if getJobs is successful", async function () {
const data = { data: "jobs" };
req.jobQueue.getJobStats.returns(data);
await getJobs(req, res, next);
@@ -96,10 +96,10 @@ describe("Queue Controller - getJobs", function() {
});
});
-describe("Queue Controller - addJob", function() {
+describe("Queue Controller - addJob", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
headers: {},
params: {},
@@ -120,14 +120,14 @@ describe("Queue Controller - addJob", function() {
sinon.restore();
});
- it("should reject with an error if addJob throws an error", async function() {
+ it("should reject with an error if addJob throws an error", async function () {
req.jobQueue.addJob.throws(new Error("addJob error"));
await addJob(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("addJob error");
});
- it("should return a success message if addJob is successful", async function() {
+ it("should return a success message if addJob is successful", async function () {
req.jobQueue.addJob.resolves();
await addJob(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200);
@@ -138,10 +138,10 @@ describe("Queue Controller - addJob", function() {
});
});
-describe("Queue Controller - obliterateQueue", function() {
+describe("Queue Controller - obliterateQueue", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
headers: {},
params: {},
@@ -162,14 +162,14 @@ describe("Queue Controller - obliterateQueue", function() {
sinon.restore();
});
- it("should reject with an error if obliterateQueue throws an error", async function() {
+ it("should reject with an error if obliterateQueue throws an error", async function () {
req.jobQueue.obliterate.throws(new Error("obliterateQueue error"));
await obliterateQueue(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("obliterateQueue error");
});
- it("should return a success message if obliterateQueue is successful", async function() {
+ it("should return a success message if obliterateQueue is successful", async function () {
req.jobQueue.obliterate.resolves();
await obliterateQueue(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200);
diff --git a/Server/tests/controllers/settingsController.test.js b/server/tests/controllers/settingsController.test.js
old mode 100644
new mode 100755
similarity index 89%
rename from Server/tests/controllers/settingsController.test.js
rename to server/tests/controllers/settingsController.test.js
index 665a13938..0f8e628af
--- a/Server/tests/controllers/settingsController.test.js
+++ b/server/tests/controllers/settingsController.test.js
@@ -7,10 +7,10 @@ import {
import { successMessages } from "../../utils/messages.js";
import sinon from "sinon";
-describe("Settings Controller - getAppSettings", function() {
+describe("Settings Controller - getAppSettings", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
headers: {},
params: {},
@@ -31,14 +31,14 @@ describe("Settings Controller - getAppSettings", function() {
sinon.restore();
});
- it("should throw an error if getSettings throws an error", async function() {
+ it("should throw an error if getSettings throws an error", async function () {
req.settingsService.getSettings.throws(new Error("getSettings error"));
await getAppSettings(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getSettings error");
});
- it("should return a success message and data if getSettings is successful", async function() {
+ it("should return a success message and data if getSettings is successful", async function () {
const data = { data: "settings" };
req.settingsService.getSettings.returns(data);
await getAppSettings(req, res, next);
@@ -51,10 +51,10 @@ describe("Settings Controller - getAppSettings", function() {
});
});
-describe("Settings Controller - updateAppSettings", function() {
+describe("Settings Controller - updateAppSettings", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
headers: {},
params: {},
@@ -77,28 +77,28 @@ describe("Settings Controller - updateAppSettings", function() {
sinon.restore();
});
- it("should reject with an error if body validation fails", async function() {
+ it("should reject with an error if body validation fails", async function () {
req.body = { invalid: 1 };
await updateAppSettings(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
- it("should reject with an error if updateAppSettings throws an error", async function() {
+ it("should reject with an error if updateAppSettings throws an error", async function () {
req.db.updateAppSettings.throws(new Error("updateAppSettings error"));
await updateAppSettings(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("updateAppSettings error");
});
- it("should reject with an error if reloadSettings throws an error", async function() {
+ it("should reject with an error if reloadSettings throws an error", async function () {
req.settingsService.reloadSettings.throws(new Error("reloadSettings error"));
await updateAppSettings(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("reloadSettings error");
});
- it("should return a success message and data if updateAppSettings is successful", async function() {
+ it("should return a success message and data if updateAppSettings is successful", async function () {
const data = { data: "settings" };
req.settingsService.reloadSettings.returns(data);
await updateAppSettings(req, res, next);
diff --git a/Server/tests/controllers/statusPageController.test.js b/server/tests/controllers/statusPageController.test.js
old mode 100644
new mode 100755
similarity index 80%
rename from Server/tests/controllers/statusPageController.test.js
rename to server/tests/controllers/statusPageController.test.js
index e1371194d..3247ca975
--- a/Server/tests/controllers/statusPageController.test.js
+++ b/server/tests/controllers/statusPageController.test.js
@@ -4,10 +4,10 @@ import {
getStatusPageByUrl,
} from "../../controllers/statusPageController.js";
-describe("statusPageController", function() {
+describe("statusPageController", function () {
let req, res, next;
- beforeEach(function() {
+ beforeEach(function () {
req = {
params: {},
body: {},
@@ -23,12 +23,12 @@ describe("statusPageController", function() {
next = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- describe("createStatusPage", function() {
- beforeEach(function() {
+ describe("createStatusPage", function () {
+ beforeEach(function () {
req.body = {
companyName: "Test Company",
url: "123456",
@@ -39,11 +39,11 @@ describe("statusPageController", function() {
};
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should handle a validation error", async function() {
+ it("should handle a validation error", async function () {
req.body = {
// Invalid data that will trigger validation error
companyName: "",
@@ -61,7 +61,7 @@ describe("statusPageController", function() {
}
});
- it("should handle a db error", async function() {
+ it("should handle a db error", async function () {
const err = new Error("DB error");
req.db.createStatusPage.throws(err);
@@ -72,25 +72,25 @@ describe("statusPageController", function() {
}
});
- it("should insert a properly formatted status page", async function() {
+ it("should insert a properly formatted status page", async function () {
const result = await createStatusPage(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200);
expect(res.json.firstCall.args[0].success).to.be.true;
});
});
- describe("getStatusPageByUrl", function() {
- beforeEach(function() {
+ describe("getStatusPageByUrl", function () {
+ beforeEach(function () {
req.params = {
url: "123456",
};
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should handle a validation error", async function() {
+ it("should handle a validation error", async function () {
req.params = {
url: "",
};
@@ -103,7 +103,7 @@ describe("statusPageController", function() {
}
});
- it("should handle a DB error", async function() {
+ it("should handle a DB error", async function () {
const err = new Error("DB error");
req.db.getStatusPageByUrl.throws(err);
@@ -114,7 +114,7 @@ describe("statusPageController", function() {
}
});
- it("should return a status page", async function() {
+ it("should return a status page", async function () {
const statusPage = {
_id: "123456",
companyName: "Test Company",
diff --git a/Server/tests/db/checkModule.test.js b/server/tests/db/checkModule.test.js
old mode 100644
new mode 100755
similarity index 84%
rename from Server/tests/db/checkModule.test.js
rename to server/tests/db/checkModule.test.js
index 986fa1457..7ef2f5b77
--- a/Server/tests/db/checkModule.test.js
+++ b/server/tests/db/checkModule.test.js
@@ -13,8 +13,8 @@ import Monitor from "../../db/models/Monitor.js";
import User from "../../db/models/User.js";
import logger from "../../utils/logger.js";
-describe("checkModule", function() {
- describe("createCheck", function() {
+describe("checkModule", function () {
+ describe("createCheck", function () {
let checkCountDocumentsStub, checkSaveStub, monitorFindByIdStub, monitorSaveStub;
const mockMonitor = {
_id: "123",
@@ -24,24 +24,24 @@ describe("checkModule", function() {
};
const mockCheck = { active: true };
- beforeEach(function() {
+ beforeEach(function () {
checkSaveStub = sinon.stub(Check.prototype, "save");
checkCountDocumentsStub = sinon.stub(Check, "countDocuments");
monitorFindByIdStub = sinon.stub(Monitor, "findById");
monitorSaveStub = sinon.stub(Monitor.prototype, "save");
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should return undefined early if no monitor is found", async function() {
+ it("should return undefined early if no monitor is found", async function () {
monitorFindByIdStub.returns(null);
const check = await createCheck({ monitorId: "123" });
expect(check).to.be.undefined;
});
- it("should return a check", async function() {
+ it("should return a check", async function () {
monitorFindByIdStub.returns(mockMonitor);
checkSaveStub.returns(mockCheck);
monitorSaveStub.returns(mockMonitor);
@@ -49,7 +49,7 @@ describe("checkModule", function() {
expect(check).to.deep.equal(mockCheck);
});
- it("should return a check if status is down", async function() {
+ it("should return a check if status is down", async function () {
mockMonitor.status = false;
monitorFindByIdStub.returns(mockMonitor);
checkSaveStub.returns(mockCheck);
@@ -58,7 +58,7 @@ describe("checkModule", function() {
expect(check).to.deep.equal(mockCheck);
});
- it("should return a check if uptimePercentage is undefined", async function() {
+ it("should return a check if uptimePercentage is undefined", async function () {
mockMonitor.uptimePercentage = undefined;
monitorFindByIdStub.returns(mockMonitor);
checkSaveStub.returns(mockCheck);
@@ -67,7 +67,7 @@ describe("checkModule", function() {
expect(check).to.deep.equal(mockCheck);
});
- it("should return a check if uptimePercentage is undefined and status is down", async function() {
+ it("should return a check if uptimePercentage is undefined and status is down", async function () {
mockMonitor.uptimePercentage = undefined;
monitorFindByIdStub.returns(mockMonitor);
checkSaveStub.returns(mockCheck);
@@ -76,7 +76,7 @@ describe("checkModule", function() {
expect(check).to.deep.equal(mockCheck);
});
- it("should monitor save error", async function() {
+ it("should monitor save error", async function () {
const err = new Error("Save Error");
monitorSaveStub.throws(err);
try {
@@ -86,7 +86,7 @@ describe("checkModule", function() {
}
});
- it("should handle errors", async function() {
+ it("should handle errors", async function () {
const err = new Error("DB Error");
checkCountDocumentsStub.throws(err);
try {
@@ -97,18 +97,18 @@ describe("checkModule", function() {
});
});
- describe("getChecksCount", function() {
+ describe("getChecksCount", function () {
let checkCountDocumentStub;
- beforeEach(function() {
+ beforeEach(function () {
checkCountDocumentStub = sinon.stub(Check, "countDocuments");
});
- afterEach(function() {
+ afterEach(function () {
checkCountDocumentStub.restore();
});
- it("should return count with basic monitorId query", async function() {
+ it("should return count with basic monitorId query", async function () {
const req = {
params: { monitorId: "test123" },
query: {},
@@ -124,7 +124,7 @@ describe("checkModule", function() {
});
});
- it("should include dateRange in query when provided", async function() {
+ it("should include dateRange in query when provided", async function () {
const req = {
params: { monitorId: "test123" },
query: { dateRange: "day" },
@@ -138,7 +138,7 @@ describe("checkModule", function() {
expect(checkCountDocumentStub.firstCall.args[0].createdAt).to.have.property("$gte");
});
- it('should handle "all" filter correctly', async function() {
+ it('should handle "all" filter correctly', async function () {
const req = {
params: { monitorId: "test123" },
query: { filter: "all" },
@@ -154,7 +154,7 @@ describe("checkModule", function() {
});
});
- it('should handle "down" filter correctly', async function() {
+ it('should handle "down" filter correctly', async function () {
const req = {
params: { monitorId: "test123" },
query: { filter: "down" },
@@ -170,7 +170,7 @@ describe("checkModule", function() {
});
});
- it('should handle "resolve" filter correctly', async function() {
+ it('should handle "resolve" filter correctly', async function () {
const req = {
params: { monitorId: "test123" },
query: { filter: "resolve" },
@@ -187,7 +187,7 @@ describe("checkModule", function() {
});
});
- it("should handle unknown filter correctly", async function() {
+ it("should handle unknown filter correctly", async function () {
const req = {
params: { monitorId: "test123" },
query: { filter: "unknown" },
@@ -203,7 +203,7 @@ describe("checkModule", function() {
});
});
- it("should combine dateRange and filter in query", async function() {
+ it("should combine dateRange and filter in query", async function () {
const req = {
params: { monitorId: "test123" },
query: {
@@ -224,10 +224,10 @@ describe("checkModule", function() {
});
});
- describe("getChecks", function() {
+ describe("getChecks", function () {
let checkFindStub, monitorFindStub;
- beforeEach(function() {
+ beforeEach(function () {
checkFindStub = sinon.stub(Check, "find").returns({
skip: sinon.stub().returns({
limit: sinon.stub().returns({
@@ -237,11 +237,11 @@ describe("checkModule", function() {
});
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should return checks with basic monitorId query", async function() {
+ it("should return checks with basic monitorId query", async function () {
const req = {
params: { monitorId: "test123" },
query: {},
@@ -252,7 +252,7 @@ describe("checkModule", function() {
expect(result).to.deep.equal([{ id: 1 }, { id: 2 }]);
});
- it("should return checks with limit query", async function() {
+ it("should return checks with limit query", async function () {
const req = {
params: { monitorId: "test123" },
query: { limit: 10 },
@@ -263,7 +263,7 @@ describe("checkModule", function() {
expect(result).to.deep.equal([{ id: 1 }, { id: 2 }]);
});
- it("should handle pagination correctly", async function() {
+ it("should handle pagination correctly", async function () {
const req = {
params: { monitorId: "test123" },
query: {
@@ -277,7 +277,7 @@ describe("checkModule", function() {
expect(result).to.deep.equal([{ id: 1 }, { id: 2 }]);
});
- it("should handle dateRange filter", async function() {
+ it("should handle dateRange filter", async function () {
const req = {
params: { monitorId: "test123" },
query: { dateRange: "week" },
@@ -287,7 +287,7 @@ describe("checkModule", function() {
expect(result).to.deep.equal([{ id: 1 }, { id: 2 }]);
});
- it('should handle "all" filter', async function() {
+ it('should handle "all" filter', async function () {
const req = {
params: { monitorId: "test123" },
query: { filter: "all" },
@@ -298,7 +298,7 @@ describe("checkModule", function() {
expect(result).to.deep.equal([{ id: 1 }, { id: 2 }]);
});
- it('should handle "down" filter', async function() {
+ it('should handle "down" filter', async function () {
const req = {
params: { monitorId: "test123" },
query: { filter: "down" },
@@ -309,7 +309,7 @@ describe("checkModule", function() {
expect(result).to.deep.equal([{ id: 1 }, { id: 2 }]);
});
- it('should handle "resolve" filter', async function() {
+ it('should handle "resolve" filter', async function () {
const req = {
params: { monitorId: "test123" },
query: { filter: "resolve" },
@@ -320,7 +320,7 @@ describe("checkModule", function() {
expect(result).to.deep.equal([{ id: 1 }, { id: 2 }]);
});
- it('should handle "unknown" filter', async function() {
+ it('should handle "unknown" filter', async function () {
const req = {
params: { monitorId: "test123" },
query: { filter: "unknown" },
@@ -331,7 +331,7 @@ describe("checkModule", function() {
expect(result).to.deep.equal([{ id: 1 }, { id: 2 }]);
});
- it("should handle ascending sort order", async function() {
+ it("should handle ascending sort order", async function () {
const req = {
params: { monitorId: "test123" },
query: { sortOrder: "asc" },
@@ -342,7 +342,7 @@ describe("checkModule", function() {
expect(result).to.deep.equal([{ id: 1 }, { id: 2 }]);
});
- it("should handle error case", async function() {
+ it("should handle error case", async function () {
const req = {
params: { monitorId: "test123" },
query: {},
@@ -360,11 +360,11 @@ describe("checkModule", function() {
});
});
- describe("getTeamChecks", function() {
+ describe("getTeamChecks", function () {
let checkFindStub, checkCountDocumentsStub, monitorFindStub;
const mockMonitors = [{ _id: "123" }];
- beforeEach(function() {
+ beforeEach(function () {
monitorFindStub = sinon.stub(Monitor, "find").returns({
select: sinon.stub().returns(mockMonitors),
});
@@ -380,11 +380,11 @@ describe("checkModule", function() {
});
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should return checks with basic monitorId query", async function() {
+ it("should return checks with basic monitorId query", async function () {
const req = {
params: { teamId: "test123" },
query: {},
@@ -394,7 +394,7 @@ describe("checkModule", function() {
expect(result).to.deep.equal({ checksCount: 2, checks: [{ id: 1 }, { id: 2 }] });
});
- it("should handle pagination correctly", async function() {
+ it("should handle pagination correctly", async function () {
const req = {
params: { monitorId: "test123" },
query: { limit: 1, page: 2, rowsPerPage: 10 },
@@ -404,7 +404,7 @@ describe("checkModule", function() {
expect(result).to.deep.equal({ checksCount: 2, checks: [{ id: 1 }, { id: 2 }] });
});
- it("should handle dateRange filter", async function() {
+ it("should handle dateRange filter", async function () {
const req = {
params: { monitorId: "test123" },
query: { dateRange: "week" },
@@ -413,7 +413,7 @@ describe("checkModule", function() {
expect(result).to.deep.equal({ checksCount: 2, checks: [{ id: 1 }, { id: 2 }] });
});
- it('should handle "all" filter', async function() {
+ it('should handle "all" filter', async function () {
const req = {
params: { monitorId: "test123" },
query: { filter: "all" },
@@ -424,7 +424,7 @@ describe("checkModule", function() {
expect(result).to.deep.equal({ checksCount: 2, checks: [{ id: 1 }, { id: 2 }] });
});
- it('should handle "down" filter', async function() {
+ it('should handle "down" filter', async function () {
const req = {
params: { monitorId: "test123" },
query: { filter: "down" },
@@ -435,7 +435,7 @@ describe("checkModule", function() {
expect(result).to.deep.equal({ checksCount: 2, checks: [{ id: 1 }, { id: 2 }] });
});
- it('should handle "resolve" filter', async function() {
+ it('should handle "resolve" filter', async function () {
const req = {
params: { monitorId: "test123" },
query: { filter: "resolve" },
@@ -446,7 +446,7 @@ describe("checkModule", function() {
expect(result).to.deep.equal({ checksCount: 2, checks: [{ id: 1 }, { id: 2 }] });
});
- it('should handle "unknown" filter', async function() {
+ it('should handle "unknown" filter', async function () {
const req = {
params: { monitorId: "test123" },
query: { filter: "unknown" },
@@ -457,7 +457,7 @@ describe("checkModule", function() {
expect(result).to.deep.equal({ checksCount: 2, checks: [{ id: 1 }, { id: 2 }] });
});
- it("should handle ascending sort order", async function() {
+ it("should handle ascending sort order", async function () {
const req = {
params: { monitorId: "test123" },
query: { sortOrder: "asc" },
@@ -468,7 +468,7 @@ describe("checkModule", function() {
expect(result).to.deep.equal({ checksCount: 2, checks: [{ id: 1 }, { id: 2 }] });
});
- it("should handle error case", async function() {
+ it("should handle error case", async function () {
const req = {
params: { monitorId: "test123" },
query: {},
@@ -486,23 +486,23 @@ describe("checkModule", function() {
});
});
- describe("deleteChecks", function() {
+ describe("deleteChecks", function () {
let checkDeleteManyStub;
- beforeEach(function() {
+ beforeEach(function () {
checkDeleteManyStub = sinon.stub(Check, "deleteMany").resolves({ deletedCount: 1 });
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should return a value if a check is deleted", async function() {
+ it("should return a value if a check is deleted", async function () {
const result = await deleteChecks("123");
expect(result).to.equal(1);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
checkDeleteManyStub.throws(new Error("Database error"));
try {
await deleteChecks("123");
@@ -513,26 +513,26 @@ describe("checkModule", function() {
});
});
- describe("deleteChecksByTeamId", function() {
+ describe("deleteChecksByTeamId", function () {
let mockMonitors = [{ _id: 123, save: () => this }];
let monitorFindStub, monitorSaveStub, checkDeleteManyStub;
- beforeEach(function() {
+ beforeEach(function () {
monitorSaveStub = sinon.stub(Monitor.prototype, "save");
monitorFindStub = sinon.stub(Monitor, "find").returns(mockMonitors);
checkDeleteManyStub = sinon.stub(Check, "deleteMany").resolves({ deletedCount: 1 });
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should return a deleted count", async function() {
+ it("should return a deleted count", async function () {
const result = await deleteChecksByTeamId("123");
expect(result).to.equal(1);
});
- it("should handle errors", async function() {
+ it("should handle errors", async function () {
const err = new Error("DB Error");
monitorFindStub.throws(err);
try {
@@ -543,26 +543,26 @@ describe("checkModule", function() {
});
});
- describe("updateChecksTTL", function() {
+ describe("updateChecksTTL", function () {
let userUpdateManyStub;
let loggerStub;
- beforeEach(function() {
+ beforeEach(function () {
loggerStub = sinon.stub(logger, "error");
userUpdateManyStub = sinon.stub(User, "updateMany");
Check.collection = { dropIndex: sinon.stub(), createIndex: sinon.stub() };
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should return undefined", async function() {
+ it("should return undefined", async function () {
const result = await updateChecksTTL("123", 10);
expect(result).to.be.undefined;
});
- it("should log an error if dropIndex throws an error", async function() {
+ it("should log an error if dropIndex throws an error", async function () {
const err = new Error("Drop Index Error");
Check.collection.dropIndex.throws(err);
await updateChecksTTL("123", 10);
@@ -570,7 +570,7 @@ describe("checkModule", function() {
expect(loggerStub.firstCall.args[0].message).to.equal(err.message);
});
- it("should throw an error if createIndex throws an error", async function() {
+ it("should throw an error if createIndex throws an error", async function () {
const err = new Error("Create Index Error");
Check.collection.createIndex.throws(err);
try {
@@ -580,7 +580,7 @@ describe("checkModule", function() {
}
});
- it("should throw an error if User.updateMany throws an error", async function() {
+ it("should throw an error if User.updateMany throws an error", async function () {
const err = new Error("Update Many Error");
userUpdateManyStub.throws(err);
try {
diff --git a/Server/tests/db/hardwareCheckModule.test.js b/server/tests/db/hardwareCheckModule.test.js
old mode 100644
new mode 100755
similarity index 90%
rename from Server/tests/db/hardwareCheckModule.test.js
rename to server/tests/db/hardwareCheckModule.test.js
index c0a642b6b..566c45a8e
--- a/Server/tests/db/hardwareCheckModule.test.js
+++ b/server/tests/db/hardwareCheckModule.test.js
@@ -51,25 +51,25 @@ const mockMonitor = {
save: () => this,
};
-describe("HardwareCheckModule", function() {
+describe("HardwareCheckModule", function () {
let hardwareCheckSaveStub,
hardwareCheckCountDocumentsStub,
monitorFindByIdStub,
loggerStub;
- beforeEach(function() {
+ beforeEach(function () {
loggerStub = sinon.stub(logger, "error");
hardwareCheckSaveStub = sinon.stub(HardwareCheck.prototype, "save");
monitorFindByIdStub = sinon.stub(Monitor, "findById");
hardwareCheckCountDocumentsStub = sinon.stub(HardwareCheck, "countDocuments");
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- describe("createHardwareCheck", function() {
- it("should return a hardware check", async function() {
+ describe("createHardwareCheck", function () {
+ it("should return a hardware check", async function () {
hardwareCheckSaveStub.resolves(mockHardwareCheck);
monitorFindByIdStub.resolves(mockMonitor);
hardwareCheckCountDocumentsStub.resolves(1);
@@ -78,7 +78,7 @@ describe("HardwareCheckModule", function() {
expect(hardwareCheck).to.deep.equal(mockHardwareCheck);
});
- it("should return a hardware check for a check with status false", async function() {
+ it("should return a hardware check for a check with status false", async function () {
hardwareCheckSaveStub.resolves(mockHardwareCheck);
monitorFindByIdStub.resolves(mockMonitor);
hardwareCheckCountDocumentsStub.resolves(1);
@@ -87,7 +87,7 @@ describe("HardwareCheckModule", function() {
expect(hardwareCheck).to.deep.equal(mockHardwareCheck);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
monitorFindByIdStub.resolves(mockMonitor);
hardwareCheckSaveStub.rejects(err);
@@ -99,14 +99,14 @@ describe("HardwareCheckModule", function() {
}
});
- it("should log an error if a monitor is not found", async function() {
+ it("should log an error if a monitor is not found", async function () {
monitorFindByIdStub.resolves(null);
const res = await createHardwareCheck({});
expect(loggerStub.calledOnce).to.be.true;
expect(res).to.be.null;
});
- it("should handle a monitor with undefined uptimePercentage", async function() {
+ it("should handle a monitor with undefined uptimePercentage", async function () {
monitorFindByIdStub.resolves({ ...mockMonitor, uptimePercentage: undefined });
hardwareCheckSaveStub.resolves(mockHardwareCheck);
hardwareCheckCountDocumentsStub.resolves(1);
@@ -114,7 +114,7 @@ describe("HardwareCheckModule", function() {
expect(res).to.exist;
});
- it("should handle a monitor with undefined uptimePercentage and true status", async function() {
+ it("should handle a monitor with undefined uptimePercentage and true status", async function () {
monitorFindByIdStub.resolves({
...mockMonitor,
uptimePercentage: undefined,
@@ -125,7 +125,7 @@ describe("HardwareCheckModule", function() {
expect(res).to.exist;
});
- it("should handle a monitor with undefined uptimePercentage and false status", async function() {
+ it("should handle a monitor with undefined uptimePercentage and false status", async function () {
monitorFindByIdStub.resolves({
...mockMonitor,
uptimePercentage: undefined,
diff --git a/Server/tests/db/inviteModule.test.js b/server/tests/db/inviteModule.test.js
old mode 100644
new mode 100755
similarity index 79%
rename from Server/tests/db/inviteModule.test.js
rename to server/tests/db/inviteModule.test.js
index 164840826..9b3aab9cc
--- a/Server/tests/db/inviteModule.test.js
+++ b/server/tests/db/inviteModule.test.js
@@ -7,7 +7,7 @@ import {
} from "../../db/mongo/modules/inviteModule.js";
import { errorMessages } from "../../utils/messages.js";
-describe("Invite Module", function() {
+describe("Invite Module", function () {
const mockUserData = {
email: "test@test.com",
teamId: "123",
@@ -20,19 +20,19 @@ describe("Invite Module", function() {
inviteTokenFindOneStub,
inviteTokenFindOneAndDeleteStub;
- beforeEach(function() {
+ beforeEach(function () {
inviteTokenDeleteManyStub = sinon.stub(InviteToken, "deleteMany");
inviteTokenSaveStub = sinon.stub(InviteToken.prototype, "save");
inviteTokenFindOneStub = sinon.stub(InviteToken, "findOne");
inviteTokenFindOneAndDeleteStub = sinon.stub(InviteToken, "findOneAndDelete");
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- describe("requestInviteToken", function() {
- it("should return a new invite token", async function() {
+ describe("requestInviteToken", function () {
+ it("should return a new invite token", async function () {
inviteTokenDeleteManyStub.resolves();
inviteTokenSaveStub.resolves();
const inviteToken = await requestInviteToken(mockUserData);
@@ -41,7 +41,7 @@ describe("Invite Module", function() {
expect(inviteToken.token).to.exist;
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
inviteTokenDeleteManyStub.rejects(err);
try {
@@ -52,14 +52,14 @@ describe("Invite Module", function() {
});
});
- describe("getInviteToken", function() {
- it("should return an invite token", async function() {
+ describe("getInviteToken", function () {
+ it("should return an invite token", async function () {
inviteTokenFindOneStub.resolves(mockInviteToken);
const inviteToken = await getInviteToken(mockUserData.token);
expect(inviteToken).to.deep.equal(mockInviteToken);
});
- it("should handle a token not found", async function() {
+ it("should handle a token not found", async function () {
inviteTokenFindOneStub.resolves(null);
try {
await getInviteToken(mockUserData.token);
@@ -68,7 +68,7 @@ describe("Invite Module", function() {
}
});
- it("should handle DB errors", async function() {
+ it("should handle DB errors", async function () {
const err = new Error("test error");
inviteTokenFindOneStub.rejects(err);
try {
@@ -80,14 +80,14 @@ describe("Invite Module", function() {
});
});
- describe("getInviteTokenAndDelete", function() {
- it("should return a deleted invite", async function() {
+ describe("getInviteTokenAndDelete", function () {
+ it("should return a deleted invite", async function () {
inviteTokenFindOneAndDeleteStub.resolves(mockInviteToken);
const deletedInvite = await getInviteTokenAndDelete(mockUserData.token);
expect(deletedInvite).to.deep.equal(mockInviteToken);
});
- it("should handle a token not found", async function() {
+ it("should handle a token not found", async function () {
inviteTokenFindOneAndDeleteStub.resolves(null);
try {
await getInviteTokenAndDelete(mockUserData.token);
@@ -96,7 +96,7 @@ describe("Invite Module", function() {
}
});
- it("should handle DB errors", async function() {
+ it("should handle DB errors", async function () {
const err = new Error("test error");
inviteTokenFindOneAndDeleteStub.rejects(err);
try {
diff --git a/Server/tests/db/maintenanceWindowModule.test.js b/server/tests/db/maintenanceWindowModule.test.js
old mode 100644
new mode 100755
similarity index 84%
rename from Server/tests/db/maintenanceWindowModule.test.js
rename to server/tests/db/maintenanceWindowModule.test.js
index d0abc7fa7..842c283c8
--- a/Server/tests/db/maintenanceWindowModule.test.js
+++ b/server/tests/db/maintenanceWindowModule.test.js
@@ -11,7 +11,7 @@ import {
editMaintenanceWindowById,
} from "../../db/mongo/modules/maintenanceWindowModule.js";
-describe("MaintenanceWindow Module", function() {
+describe("MaintenanceWindow Module", function () {
const mockMaintenanceWindow = {
monitorId: "123",
active: true,
@@ -29,7 +29,7 @@ describe("MaintenanceWindow Module", function() {
maintenanceWindowDeleteManyStub,
maintenanceWindowFindByIdAndUpdateStub;
- beforeEach(function() {
+ beforeEach(function () {
maintenanceWindowSaveStub = sinon.stub(MaintenanceWindow.prototype, "save");
maintenanceWindowFindByIdStub = sinon.stub(MaintenanceWindow, "findById");
maintenanceWindowCountDocumentsStub = sinon.stub(MaintenanceWindow, "countDocuments");
@@ -51,18 +51,18 @@ describe("MaintenanceWindow Module", function() {
);
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- describe("createMaintenanceWindow", function() {
- it("should save a new maintenance window", async function() {
+ describe("createMaintenanceWindow", function () {
+ it("should save a new maintenance window", async function () {
maintenanceWindowSaveStub.resolves(mockMaintenanceWindow);
const result = await createMaintenanceWindow(mockMaintenanceWindow);
expect(result).to.deep.equal(mockMaintenanceWindow);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
maintenanceWindowSaveStub.rejects(err);
try {
@@ -73,14 +73,14 @@ describe("MaintenanceWindow Module", function() {
});
});
- describe("getMaintenanceWindowById", function() {
- it("should return a maintenance window", async function() {
+ describe("getMaintenanceWindowById", function () {
+ it("should return a maintenance window", async function () {
maintenanceWindowFindByIdStub.resolves(mockMaintenanceWindow);
const result = await getMaintenanceWindowById(mockMaintenanceWindow.id);
expect(result).to.deep.equal(mockMaintenanceWindow);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
maintenanceWindowFindByIdStub.rejects(err);
try {
@@ -91,10 +91,10 @@ describe("MaintenanceWindow Module", function() {
});
});
- describe("getMaintenanceWindowsByTeamId", function() {
+ describe("getMaintenanceWindowsByTeamId", function () {
let query;
- beforeEach(function() {
+ beforeEach(function () {
query = {
active: true,
page: 1,
@@ -104,11 +104,11 @@ describe("MaintenanceWindow Module", function() {
};
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should return a list of maintenance windows and count", async function() {
+ it("should return a list of maintenance windows and count", async function () {
maintenanceWindowCountDocumentsStub.resolves(1);
const result = await getMaintenanceWindowsByTeamId(
mockMaintenanceWindow.teamId,
@@ -120,7 +120,7 @@ describe("MaintenanceWindow Module", function() {
});
});
- it("should return a list of maintenance windows and count with empty query", async function() {
+ it("should return a list of maintenance windows and count with empty query", async function () {
query = undefined;
maintenanceWindowCountDocumentsStub.resolves(1);
const result = await getMaintenanceWindowsByTeamId(
@@ -133,7 +133,7 @@ describe("MaintenanceWindow Module", function() {
});
});
- it("should return a list of maintenance windows and count with no pagination provided", async function() {
+ it("should return a list of maintenance windows and count with no pagination provided", async function () {
query.page = undefined;
query.rowsPerPage = undefined;
maintenanceWindowCountDocumentsStub.resolves(1);
@@ -147,7 +147,7 @@ describe("MaintenanceWindow Module", function() {
});
});
- it("should return a list of maintenance windows and count with field and desc order", async function() {
+ it("should return a list of maintenance windows and count with field and desc order", async function () {
query.order = "desc";
maintenanceWindowCountDocumentsStub.resolves(1);
const result = await getMaintenanceWindowsByTeamId(
@@ -160,7 +160,7 @@ describe("MaintenanceWindow Module", function() {
});
});
- it("should return a list of maintenance windows and count no field", async function() {
+ it("should return a list of maintenance windows and count no field", async function () {
query.field = undefined;
maintenanceWindowCountDocumentsStub.resolves(1);
const result = await getMaintenanceWindowsByTeamId(
@@ -173,7 +173,7 @@ describe("MaintenanceWindow Module", function() {
});
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
maintenanceWindowCountDocumentsStub.rejects(err);
try {
@@ -184,8 +184,8 @@ describe("MaintenanceWindow Module", function() {
});
});
- describe("getMaintenanceWindowsByMonitorId", function() {
- it("should return a list of maintenance windows", async function() {
+ describe("getMaintenanceWindowsByMonitorId", function () {
+ it("should return a list of maintenance windows", async function () {
maintenanceWindowFindStub.resolves(mockMaintenanceWindows);
const result = await getMaintenanceWindowsByMonitorId(
mockMaintenanceWindow.monitorId
@@ -193,7 +193,7 @@ describe("MaintenanceWindow Module", function() {
expect(result).to.deep.equal(mockMaintenanceWindows);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
maintenanceWindowFindStub.rejects(err);
try {
@@ -204,14 +204,14 @@ describe("MaintenanceWindow Module", function() {
});
});
- describe("deleteMaintenanceWindowById", function() {
- it("should delete a maintenance window", async function() {
+ describe("deleteMaintenanceWindowById", function () {
+ it("should delete a maintenance window", async function () {
maintenanceWindowFindByIdAndDeleteStub.resolves(mockMaintenanceWindow);
const result = await deleteMaintenanceWindowById(mockMaintenanceWindow.id);
expect(result).to.deep.equal(mockMaintenanceWindow);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
maintenanceWindowFindByIdAndDeleteStub.rejects(err);
try {
@@ -222,8 +222,8 @@ describe("MaintenanceWindow Module", function() {
});
});
- describe("deleteMaintenanceWindowByMonitorId", function() {
- it("should return the number of documents deleted", async function() {
+ describe("deleteMaintenanceWindowByMonitorId", function () {
+ it("should return the number of documents deleted", async function () {
maintenanceWindowDeleteManyStub.resolves({ deletedCount: 1 });
const result = await deleteMaintenanceWindowByMonitorId(
mockMaintenanceWindow.monitorId
@@ -231,7 +231,7 @@ describe("MaintenanceWindow Module", function() {
expect(result).to.deep.equal({ deletedCount: 1 });
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
maintenanceWindowDeleteManyStub.rejects(err);
try {
@@ -242,14 +242,14 @@ describe("MaintenanceWindow Module", function() {
});
});
- describe("deleteMaintenanceWindowByUserId", function() {
- it("should return the number of documents deleted", async function() {
+ describe("deleteMaintenanceWindowByUserId", function () {
+ it("should return the number of documents deleted", async function () {
maintenanceWindowDeleteManyStub.resolves({ deletedCount: 1 });
const result = await deleteMaintenanceWindowByUserId(mockMaintenanceWindow.userId);
expect(result).to.deep.equal({ deletedCount: 1 });
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
maintenanceWindowDeleteManyStub.rejects(err);
try {
@@ -260,8 +260,8 @@ describe("MaintenanceWindow Module", function() {
});
});
- describe("editMaintenanceWindowById", function() {
- it("should return the updated maintenance window", async function() {
+ describe("editMaintenanceWindowById", function () {
+ it("should return the updated maintenance window", async function () {
maintenanceWindowFindByIdAndUpdateStub.resolves(mockMaintenanceWindow);
const result = await editMaintenanceWindowById(
mockMaintenanceWindow.id,
@@ -270,7 +270,7 @@ describe("MaintenanceWindow Module", function() {
expect(result).to.deep.equal(mockMaintenanceWindow);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
maintenanceWindowFindByIdAndUpdateStub.rejects(err);
try {
diff --git a/Server/tests/db/monitorModule.test.js b/server/tests/db/monitorModule.test.js
old mode 100644
new mode 100755
similarity index 89%
rename from Server/tests/db/monitorModule.test.js
rename to server/tests/db/monitorModule.test.js
index 50782494a..3d9bb5324
--- a/Server/tests/db/monitorModule.test.js
+++ b/server/tests/db/monitorModule.test.js
@@ -31,7 +31,7 @@ import {
calculateGroupStats,
} from "../../db/mongo/modules/monitorModule.js";
-describe("monitorModule", function() {
+describe("monitorModule", function () {
let monitorFindStub,
monitorFindByIdStub,
monitorFindByIdAndUpdateStub,
@@ -43,7 +43,7 @@ describe("monitorModule", function() {
pageSpeedCheckFindStub,
hardwareCheckFindStub;
- beforeEach(function() {
+ beforeEach(function () {
monitorFindStub = sinon.stub(Monitor, "find");
monitorFindByIdStub = sinon.stub(Monitor, "findById");
monitorFindByIdAndUpdateStub = sinon.stub(Monitor, "findByIdAndUpdate");
@@ -63,12 +63,12 @@ describe("monitorModule", function() {
});
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- describe("getAllMonitors", function() {
- it("should return all monitors", async function() {
+ describe("getAllMonitors", function () {
+ it("should return all monitors", async function () {
const mockMonitors = [
{ _id: "1", name: "Monitor 1", url: "test1.com" },
{ _id: "2", name: "Monitor 2", url: "test2.com" },
@@ -81,13 +81,13 @@ describe("monitorModule", function() {
expect(monitorFindStub.firstCall.args).to.deep.equal([]);
});
- it("should handle empty results", async function() {
+ it("should handle empty results", async function () {
monitorFindStub.returns([]);
const result = await getAllMonitors();
expect(result).to.be.an("array").that.is.empty;
});
- it("should throw error when database fails", async function() {
+ it("should throw error when database fails", async function () {
// Arrange
const error = new Error("Database error");
error.service = "MonitorModule";
@@ -105,8 +105,8 @@ describe("monitorModule", function() {
});
});
- describe("getAllMonitorsWithUptimeStats", function() {
- it("should return monitors with uptime stats for different time periods", async function() {
+ describe("getAllMonitorsWithUptimeStats", function () {
+ it("should return monitors with uptime stats for different time periods", async function () {
// Mock data
const mockMonitors = [
{
@@ -152,7 +152,7 @@ describe("monitorModule", function() {
expect(monitor["90"]).to.equal(75);
});
- it("should return monitors with stats for pagespeed type", async function() {
+ it("should return monitors with stats for pagespeed type", async function () {
// Mock data
const mockMonitors = [
{
@@ -198,7 +198,7 @@ describe("monitorModule", function() {
expect(monitor["90"]).to.equal(75);
});
- it("should return monitors with stats for hardware type", async function() {
+ it("should return monitors with stats for hardware type", async function () {
// Mock data
const mockMonitors = [
{
@@ -244,7 +244,7 @@ describe("monitorModule", function() {
expect(monitor["90"]).to.equal(75);
});
- it("should handle errors appropriately", async function() {
+ it("should handle errors appropriately", async function () {
// Setup stub to throw error
monitorFindStub.rejects(new Error("Database error"));
@@ -258,7 +258,7 @@ describe("monitorModule", function() {
}
});
- it("should handle empty monitor list", async function() {
+ it("should handle empty monitor list", async function () {
monitorFindStub.resolves([]);
const result = await getAllMonitorsWithUptimeStats();
@@ -267,7 +267,7 @@ describe("monitorModule", function() {
expect(result).to.have.lengthOf(0);
});
- it("should handle monitor with no checks", async function() {
+ it("should handle monitor with no checks", async function () {
const mockMonitors = [
{
_id: "monitor1",
@@ -292,28 +292,28 @@ describe("monitorModule", function() {
});
});
- describe("calculateUptimeDuration", function() {
+ describe("calculateUptimeDuration", function () {
let clock;
const NOW = new Date("2024-01-01T12:00:00Z").getTime();
- beforeEach(function() {
+ beforeEach(function () {
// Fix the current time
clock = sinon.useFakeTimers(NOW);
});
- afterEach(function() {
+ afterEach(function () {
clock.restore();
});
- it("should return 0 when checks array is empty", function() {
+ it("should return 0 when checks array is empty", function () {
expect(calculateUptimeDuration([])).to.equal(0);
});
- it("should return 0 when checks array is null", function() {
+ it("should return 0 when checks array is null", function () {
expect(calculateUptimeDuration(null)).to.equal(0);
});
- it("should calculate uptime from last down check to most recent check", function() {
+ it("should calculate uptime from last down check to most recent check", function () {
const checks = [
{ status: true, createdAt: "2024-01-01T11:00:00Z" }, // Most recent
{ status: true, createdAt: "2024-01-01T10:00:00Z" },
@@ -325,7 +325,7 @@ describe("monitorModule", function() {
expect(calculateUptimeDuration(checks)).to.equal(7200000);
});
- it("should calculate uptime from first check when no down checks exist", function() {
+ it("should calculate uptime from first check when no down checks exist", function () {
const checks = [
{ status: true, createdAt: "2024-01-01T11:00:00Z" },
{ status: true, createdAt: "2024-01-01T10:00:00Z" },
@@ -337,28 +337,28 @@ describe("monitorModule", function() {
});
});
- describe("getLastChecked", function() {
+ describe("getLastChecked", function () {
let clock;
const NOW = new Date("2024-01-01T12:00:00Z").getTime();
- beforeEach(function() {
+ beforeEach(function () {
// Fix the current time
clock = sinon.useFakeTimers(NOW);
});
- afterEach(function() {
+ afterEach(function () {
clock.restore();
});
- it("should return 0 when checks array is empty", function() {
+ it("should return 0 when checks array is empty", function () {
expect(getLastChecked([])).to.equal(0);
});
- it("should return 0 when checks array is null", function() {
+ it("should return 0 when checks array is null", function () {
expect(getLastChecked(null)).to.equal(0);
});
- it("should return time difference between now and most recent check", function() {
+ it("should return time difference between now and most recent check", function () {
const checks = [
{ createdAt: "2024-01-01T11:30:00Z" }, // 30 minutes ago
{ createdAt: "2024-01-01T11:00:00Z" },
@@ -369,7 +369,7 @@ describe("monitorModule", function() {
expect(getLastChecked(checks)).to.equal(1800000);
});
- it("should handle checks from different days", function() {
+ it("should handle checks from different days", function () {
const checks = [
{ createdAt: "2023-12-31T12:00:00Z" }, // 24 hours ago
{ createdAt: "2023-12-30T12:00:00Z" },
@@ -380,16 +380,16 @@ describe("monitorModule", function() {
});
});
- describe("getLatestResponseTime", function() {
- it("should return 0 when checks array is empty", function() {
+ describe("getLatestResponseTime", function () {
+ it("should return 0 when checks array is empty", function () {
expect(getLatestResponseTime([])).to.equal(0);
});
- it("should return 0 when checks array is null", function() {
+ it("should return 0 when checks array is null", function () {
expect(getLatestResponseTime(null)).to.equal(0);
});
- it("should return response time from most recent check", function() {
+ it("should return response time from most recent check", function () {
const checks = [
{ responseTime: 150, createdAt: "2024-01-01T11:30:00Z" }, // Most recent
{ responseTime: 200, createdAt: "2024-01-01T11:00:00Z" },
@@ -399,7 +399,7 @@ describe("monitorModule", function() {
expect(getLatestResponseTime(checks)).to.equal(150);
});
- it("should handle missing responseTime in checks", function() {
+ it("should handle missing responseTime in checks", function () {
const checks = [
{ createdAt: "2024-01-01T11:30:00Z" },
{ responseTime: 200, createdAt: "2024-01-01T11:00:00Z" },
@@ -409,16 +409,16 @@ describe("monitorModule", function() {
});
});
- describe("getAverageResponseTime", function() {
- it("should return 0 when checks array is empty", function() {
+ describe("getAverageResponseTime", function () {
+ it("should return 0 when checks array is empty", function () {
expect(getAverageResponseTime([])).to.equal(0);
});
- it("should return 0 when checks array is null", function() {
+ it("should return 0 when checks array is null", function () {
expect(getAverageResponseTime(null)).to.equal(0);
});
- it("should calculate average response time from all checks", function() {
+ it("should calculate average response time from all checks", function () {
const checks = [
{ responseTime: 100, createdAt: "2024-01-01T11:30:00Z" },
{ responseTime: 200, createdAt: "2024-01-01T11:00:00Z" },
@@ -429,7 +429,7 @@ describe("monitorModule", function() {
expect(getAverageResponseTime(checks)).to.equal(200);
});
- it("should handle missing responseTime in some checks", function() {
+ it("should handle missing responseTime in some checks", function () {
const checks = [
{ responseTime: 100, createdAt: "2024-01-01T11:30:00Z" },
{ createdAt: "2024-01-01T11:00:00Z" },
@@ -440,7 +440,7 @@ describe("monitorModule", function() {
expect(getAverageResponseTime(checks)).to.equal(200);
});
- it("should return 0 when no checks have responseTime", function() {
+ it("should return 0 when no checks have responseTime", function () {
const checks = [
{ createdAt: "2024-01-01T11:30:00Z" },
{ createdAt: "2024-01-01T11:00:00Z" },
@@ -450,26 +450,26 @@ describe("monitorModule", function() {
});
});
- describe("getUptimePercentage", function() {
- it("should return 0 when checks array is empty", function() {
+ describe("getUptimePercentage", function () {
+ it("should return 0 when checks array is empty", function () {
expect(getUptimePercentage([])).to.equal(0);
});
- it("should return 0 when checks array is null", function() {
+ it("should return 0 when checks array is null", function () {
expect(getUptimePercentage(null)).to.equal(0);
});
- it("should return 100 when all checks are up", function() {
+ it("should return 100 when all checks are up", function () {
const checks = [{ status: true }, { status: true }, { status: true }];
expect(getUptimePercentage(checks)).to.equal(100);
});
- it("should return 0 when all checks are down", function() {
+ it("should return 0 when all checks are down", function () {
const checks = [{ status: false }, { status: false }, { status: false }];
expect(getUptimePercentage(checks)).to.equal(0);
});
- it("should calculate correct percentage for mixed status checks", function() {
+ it("should calculate correct percentage for mixed status checks", function () {
const checks = [
{ status: true },
{ status: false },
@@ -480,33 +480,33 @@ describe("monitorModule", function() {
expect(getUptimePercentage(checks)).to.equal(75);
});
- it("should handle undefined status values", function() {
+ it("should handle undefined status values", function () {
const checks = [{ status: true }, { status: undefined }, { status: true }];
// 2 up out of 3 total ≈ 66.67%
expect(getUptimePercentage(checks)).to.equal((2 / 3) * 100);
});
});
- describe("getIncidents", function() {
- it("should return 0 when checks array is empty", function() {
+ describe("getIncidents", function () {
+ it("should return 0 when checks array is empty", function () {
expect(getIncidents([])).to.equal(0);
});
- it("should return 0 when checks array is null", function() {
+ it("should return 0 when checks array is null", function () {
expect(getIncidents(null)).to.equal(0);
});
- it("should return 0 when all checks are up", function() {
+ it("should return 0 when all checks are up", function () {
const checks = [{ status: true }, { status: true }, { status: true }];
expect(getIncidents(checks)).to.equal(0);
});
- it("should count all incidents when all checks are down", function() {
+ it("should count all incidents when all checks are down", function () {
const checks = [{ status: false }, { status: false }, { status: false }];
expect(getIncidents(checks)).to.equal(3);
});
- it("should count correct number of incidents for mixed status checks", function() {
+ it("should count correct number of incidents for mixed status checks", function () {
const checks = [
{ status: true },
{ status: false },
@@ -517,7 +517,7 @@ describe("monitorModule", function() {
expect(getIncidents(checks)).to.equal(2);
});
- it("should handle undefined status values", function() {
+ it("should handle undefined status values", function () {
const checks = [
{ status: true },
{ status: undefined },
@@ -529,10 +529,10 @@ describe("monitorModule", function() {
});
});
- describe("getMonitorChecks", function() {
+ describe("getMonitorChecks", function () {
let mockModel;
- beforeEach(function() {
+ beforeEach(function () {
// Create a mock model with chainable methods
const mockChecks = [
{ monitorId: "123", createdAt: new Date("2024-01-01") },
@@ -546,11 +546,11 @@ describe("monitorModule", function() {
};
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should return all checks and date-ranged checks", async function() {
+ it("should return all checks and date-ranged checks", async function () {
// Arrange
const monitorId = "123";
const dateRange = {
@@ -579,7 +579,7 @@ describe("monitorModule", function() {
});
});
- it("should handle empty results", async function() {
+ it("should handle empty results", async function () {
// Arrange
const emptyModel = {
find: sinon.stub().returns({
@@ -603,7 +603,7 @@ describe("monitorModule", function() {
expect(result.checksForDateRange).to.be.an("array").that.is.empty;
});
- it("should maintain sort order", async function() {
+ it("should maintain sort order", async function () {
// Arrange
const sortedChecks = [
{ monitorId: "123", createdAt: new Date("2024-01-02") },
@@ -637,39 +637,39 @@ describe("monitorModule", function() {
});
});
- describe("processChecksForDisplay", function() {
+ describe("processChecksForDisplay", function () {
let normalizeStub;
- beforeEach(function() {
+ beforeEach(function () {
normalizeStub = sinon.stub();
});
- it("should return original checks when numToDisplay is not provided", function() {
+ it("should return original checks when numToDisplay is not provided", function () {
const checks = [1, 2, 3, 4, 5];
const result = processChecksForDisplay(normalizeStub, checks);
expect(result).to.deep.equal(checks);
});
- it("should return original checks when numToDisplay is greater than checks length", function() {
+ it("should return original checks when numToDisplay is greater than checks length", function () {
const checks = [1, 2, 3];
const result = processChecksForDisplay(normalizeStub, checks, 5);
expect(result).to.deep.equal(checks);
});
- it("should filter checks based on numToDisplay", function() {
+ it("should filter checks based on numToDisplay", function () {
const checks = [1, 2, 3, 4, 5, 6];
const result = processChecksForDisplay(normalizeStub, checks, 3);
// Should return [1, 3, 5] as n = ceil(6/3) = 2
expect(result).to.deep.equal([1, 3, 5]);
});
- it("should handle empty checks array", function() {
+ it("should handle empty checks array", function () {
const checks = [];
const result = processChecksForDisplay(normalizeStub, checks, 3);
expect(result).to.be.an("array").that.is.empty;
});
- it("should call normalizeData when normalize is true", function() {
+ it("should call normalizeData when normalize is true", function () {
const checks = [1, 2, 3];
normalizeStub.returns([10, 20, 30]);
@@ -679,7 +679,7 @@ describe("monitorModule", function() {
expect(result).to.deep.equal([10, 20, 30]);
});
- it("should handle both filtering and normalization", function() {
+ it("should handle both filtering and normalization", function () {
const checks = [1, 2, 3, 4, 5, 6];
normalizeStub.returns([10, 30, 50]);
@@ -690,7 +690,7 @@ describe("monitorModule", function() {
});
});
- describe("groupChecksByTime", function() {
+ describe("groupChecksByTime", function () {
const mockChecks = [
{ createdAt: "2024-01-15T10:30:45Z" },
{ createdAt: "2024-01-15T10:45:15Z" },
@@ -698,7 +698,7 @@ describe("monitorModule", function() {
{ createdAt: "2024-01-16T10:30:00Z" },
];
- it("should group checks by hour when dateRange is 'day'", function() {
+ it("should group checks by hour when dateRange is 'day'", function () {
const result = groupChecksByTime(mockChecks, "day");
// Get timestamps for 10:00 and 11:00 on Jan 15
@@ -713,7 +713,7 @@ describe("monitorModule", function() {
expect(result[time3].checks).to.have.lengthOf(1);
});
- it("should group checks by day when dateRange is not 'day'", function() {
+ it("should group checks by day when dateRange is not 'day'", function () {
const result = groupChecksByTime(mockChecks, "week");
expect(Object.keys(result)).to.have.lengthOf(2);
@@ -721,12 +721,12 @@ describe("monitorModule", function() {
expect(result["2024-01-16"].checks).to.have.lengthOf(1);
});
- it("should handle empty checks array", function() {
+ it("should handle empty checks array", function () {
const result = groupChecksByTime([], "day");
expect(result).to.deep.equal({});
});
- it("should handle single check", function() {
+ it("should handle single check", function () {
const singleCheck = [{ createdAt: "2024-01-15T10:30:45Z" }];
const result = groupChecksByTime(singleCheck, "day");
@@ -735,7 +735,7 @@ describe("monitorModule", function() {
expect(result[expectedTime].checks).to.have.lengthOf(1);
});
- it("should skip invalid dates and process valid ones", function() {
+ it("should skip invalid dates and process valid ones", function () {
const checksWithInvalidDate = [
{ createdAt: "invalid-date" },
{ createdAt: "2024-01-15T10:30:45Z" },
@@ -752,7 +752,7 @@ describe("monitorModule", function() {
expect(result[expectedTime].checks[0].createdAt).to.equal("2024-01-15T10:30:45Z");
});
- it("should handle checks in same time group", function() {
+ it("should handle checks in same time group", function () {
const checksInSameHour = [
{ createdAt: "2024-01-15T10:15:00Z" },
{ createdAt: "2024-01-15T10:45:00Z" },
@@ -766,16 +766,16 @@ describe("monitorModule", function() {
});
});
- describe("calculateGroupStats", function() {
+ describe("calculateGroupStats", function () {
// Mock getUptimePercentage function
let uptimePercentageStub;
- beforeEach(function() {
+ beforeEach(function () {
uptimePercentageStub = sinon.stub();
uptimePercentageStub.returns(95); // Default return value
});
- it("should calculate stats correctly for a group of checks", function() {
+ it("should calculate stats correctly for a group of checks", function () {
const mockGroup = {
time: "2024-01-15",
checks: [
@@ -796,7 +796,7 @@ describe("monitorModule", function() {
});
});
- it("should handle empty checks array", function() {
+ it("should handle empty checks array", function () {
const mockGroup = {
time: "2024-01-15",
checks: [],
@@ -813,7 +813,7 @@ describe("monitorModule", function() {
});
});
- it("should handle missing responseTime values", function() {
+ it("should handle missing responseTime values", function () {
const mockGroup = {
time: "2024-01-15",
checks: [
@@ -834,7 +834,7 @@ describe("monitorModule", function() {
});
});
- it("should handle all checks with status false", function() {
+ it("should handle all checks with status false", function () {
const mockGroup = {
time: "2024-01-15",
checks: [
@@ -855,7 +855,7 @@ describe("monitorModule", function() {
});
});
- it("should handle all checks with status true", function() {
+ it("should handle all checks with status true", function () {
const mockGroup = {
time: "2024-01-15",
checks: [
@@ -877,7 +877,7 @@ describe("monitorModule", function() {
});
});
- describe("getMonitorStatsById", function() {
+ describe("getMonitorStatsById", function () {
const now = new Date();
const oneHourAgo = new Date(now - 3600000);
const twoHoursAgo = new Date(now - 7200000);
@@ -974,18 +974,18 @@ describe("monitorModule", function() {
},
};
- beforeEach(function() {
+ beforeEach(function () {
checkFindStub.returns({
sort: () => checkDocs,
});
monitorFindByIdStub.returns(mockMonitor);
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should return monitor stats with calculated values, sort order desc", async function() {
+ it("should return monitor stats with calculated values, sort order desc", async function () {
req.query.sortOrder = "desc";
const result = await getMonitorStatsById(req);
expect(result).to.include.keys([
@@ -1009,7 +1009,7 @@ describe("monitorModule", function() {
expect(result.aggregateData).to.be.an("array");
});
- it("should return monitor stats with calculated values, ping type", async function() {
+ it("should return monitor stats with calculated values, ping type", async function () {
monitorFindByIdStub.returns(mockMonitorPing);
req.query.sortOrder = "desc";
const result = await getMonitorStatsById(req);
@@ -1034,7 +1034,7 @@ describe("monitorModule", function() {
expect(result.aggregateData).to.be.an("array");
});
- it("should return monitor stats with calculated values, docker type", async function() {
+ it("should return monitor stats with calculated values, docker type", async function () {
monitorFindByIdStub.returns(mockMonitorDocker);
req.query.sortOrder = "desc";
const result = await getMonitorStatsById(req);
@@ -1059,7 +1059,7 @@ describe("monitorModule", function() {
expect(result.aggregateData).to.be.an("array");
});
- it("should return monitor stats with calculated values", async function() {
+ it("should return monitor stats with calculated values", async function () {
req.query.sortOrder = "asc";
const result = await getMonitorStatsById(req);
expect(result).to.include.keys([
@@ -1083,7 +1083,7 @@ describe("monitorModule", function() {
expect(result.aggregateData).to.be.an("array");
});
- it("should throw error when monitor is not found", async function() {
+ it("should throw error when monitor is not found", async function () {
monitorFindByIdStub.returns(Promise.resolve(null));
const req = {
@@ -1101,21 +1101,21 @@ describe("monitorModule", function() {
});
});
- describe("getMonitorById", function() {
+ describe("getMonitorById", function () {
let notificationFindStub;
let monitorSaveStub;
- beforeEach(function() {
+ beforeEach(function () {
// Create stubs
notificationFindStub = sinon.stub(Notification, "find");
monitorSaveStub = sinon.stub().resolves();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should return monitor with notifications when found", async function() {
+ it("should return monitor with notifications when found", async function () {
// Arrange
const monitorId = "123";
const mockMonitor = {
@@ -1139,7 +1139,7 @@ describe("monitorModule", function() {
expect(monitorSaveStub.calledOnce).to.be.true;
});
- it("should throw 404 error when monitor not found", async function() {
+ it("should throw 404 error when monitor not found", async function () {
// Arrange
const monitorId = "nonexistent";
monitorFindByIdStub.resolves(null);
@@ -1156,7 +1156,7 @@ describe("monitorModule", function() {
}
});
- it("should handle database errors properly", async function() {
+ it("should handle database errors properly", async function () {
// Arrange
const monitorId = "123";
const dbError = new Error("Database connection failed");
@@ -1173,7 +1173,7 @@ describe("monitorModule", function() {
}
});
- it("should handle notification fetch errors", async function() {
+ it("should handle notification fetch errors", async function () {
// Arrange
const monitorId = "123";
const mockMonitor = {
@@ -1197,7 +1197,7 @@ describe("monitorModule", function() {
}
});
- it("should handle monitor save errors", async function() {
+ it("should handle monitor save errors", async function () {
// Arrange
const monitorId = "123";
const mockMonitor = {
@@ -1222,8 +1222,8 @@ describe("monitorModule", function() {
});
});
- describe("getMonitorsAndSummaryByTeamId", function() {
- it("should return monitors and correct summary counts", async function() {
+ describe("getMonitorsAndSummaryByTeamId", function () {
+ it("should return monitors and correct summary counts", async function () {
// Arrange
const teamId = "team123";
const type = "http";
@@ -1249,7 +1249,7 @@ describe("monitorModule", function() {
expect(monitorFindStub.calledOnceWith({ teamId, type })).to.be.true;
});
- it("should return empty results for non-existent team", async function() {
+ it("should return empty results for non-existent team", async function () {
// Arrange
monitorFindStub.resolves([]);
@@ -1266,7 +1266,7 @@ describe("monitorModule", function() {
});
});
- it("should handle database errors", async function() {
+ it("should handle database errors", async function () {
// Arrange
const error = new Error("Database error");
error.service = "MonitorModule";
@@ -1285,8 +1285,8 @@ describe("monitorModule", function() {
});
});
- describe("getMonitorsByTeamId", function() {
- beforeEach(function() {
+ describe("getMonitorsByTeamId", function () {
+ beforeEach(function () {
// Chain stubs for Monitor.find().skip().limit().sort()
// Stub for CHECK_MODEL_LOOKUP model find
@@ -1297,11 +1297,11 @@ describe("monitorModule", function() {
});
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should return monitors with basic query parameters", async function() {
+ it("should return monitors with basic query parameters", async function () {
const mockMonitors = [
{ _id: "1", type: "http", toObject: () => ({ _id: "1", type: "http" }) },
{ _id: "2", type: "ping", toObject: () => ({ _id: "2", type: "ping" }) },
@@ -1334,7 +1334,7 @@ describe("monitorModule", function() {
expect(result).to.have.property("monitorCount", 2);
});
- it("should return monitors with basic query parameters", async function() {
+ it("should return monitors with basic query parameters", async function () {
const mockMonitors = [
{ _id: "1", type: "http", toObject: () => ({ _id: "1", type: "http" }) },
{ _id: "2", type: "ping", toObject: () => ({ _id: "2", type: "ping" }) },
@@ -1367,7 +1367,7 @@ describe("monitorModule", function() {
expect(result).to.have.property("monitorCount", 2);
});
- it("should handle type filter with array input", async function() {
+ it("should handle type filter with array input", async function () {
const req = {
params: { teamId: "team123" },
query: {
@@ -1392,7 +1392,7 @@ describe("monitorModule", function() {
});
});
- it("should handle text search filter", async function() {
+ it("should handle text search filter", async function () {
const req = {
params: { teamId: "team123" },
query: {
@@ -1420,7 +1420,7 @@ describe("monitorModule", function() {
});
});
- it("should handle pagination parameters", async function() {
+ it("should handle pagination parameters", async function () {
const req = {
params: { teamId: "team123" },
query: {
@@ -1445,7 +1445,7 @@ describe("monitorModule", function() {
});
});
- it("should handle sorting parameters", async function() {
+ it("should handle sorting parameters", async function () {
const req = {
params: { teamId: "team123" },
query: {
@@ -1472,7 +1472,7 @@ describe("monitorModule", function() {
});
});
- it("should return early when limit is -1", async function() {
+ it("should return early when limit is -1", async function () {
// Arrange
const req = {
params: { teamId: "team123" },
@@ -1506,7 +1506,7 @@ describe("monitorModule", function() {
});
});
- it("should normalize checks when normalize parameter is provided", async function() {
+ it("should normalize checks when normalize parameter is provided", async function () {
const req = {
params: { teamId: "team123" },
query: { normalize: "true" },
@@ -1531,7 +1531,7 @@ describe("monitorModule", function() {
expect(result.monitors).to.have.lengthOf(2);
});
- it("should handle database errors", async function() {
+ it("should handle database errors", async function () {
const req = {
params: { teamId: "team123" },
query: {},
@@ -1557,8 +1557,8 @@ describe("monitorModule", function() {
});
});
- describe("createMonitor", function() {
- it("should create a monitor without notifications", async function() {
+ describe("createMonitor", function () {
+ it("should create a monitor without notifications", async function () {
let monitorSaveStub = sinon.stub(Monitor.prototype, "save").resolves();
const req = {
@@ -1583,7 +1583,7 @@ describe("monitorModule", function() {
expect(result.url).to.equal(expectedMonitor.url);
});
- it("should handle database errors", async function() {
+ it("should handle database errors", async function () {
const req = {
body: {
name: "Test Monitor",
@@ -1600,8 +1600,8 @@ describe("monitorModule", function() {
});
});
- describe("deleteMonitor", function() {
- it("should delete a monitor successfully", async function() {
+ describe("deleteMonitor", function () {
+ it("should delete a monitor successfully", async function () {
const monitorId = "123456789";
const mockMonitor = {
_id: monitorId,
@@ -1621,7 +1621,7 @@ describe("monitorModule", function() {
sinon.assert.calledWith(monitorFindByIdAndDeleteStub, monitorId);
});
- it("should throw error when monitor not found", async function() {
+ it("should throw error when monitor not found", async function () {
const monitorId = "nonexistent123";
const req = {
params: { monitorId },
@@ -1639,7 +1639,7 @@ describe("monitorModule", function() {
}
});
- it("should handle database errors", async function() {
+ it("should handle database errors", async function () {
const monitorId = "123456789";
const req = {
params: { monitorId },
@@ -1659,8 +1659,8 @@ describe("monitorModule", function() {
});
});
- describe("deleteAllMonitors", function() {
- it("should delete all monitors for a team successfully", async function() {
+ describe("deleteAllMonitors", function () {
+ it("should delete all monitors for a team successfully", async function () {
const teamId = "team123";
const mockMonitors = [
{ _id: "1", name: "Monitor 1", teamId },
@@ -1680,7 +1680,7 @@ describe("monitorModule", function() {
sinon.assert.calledWith(monitorDeleteManyStub, { teamId });
});
- it("should return empty array when no monitors found", async function() {
+ it("should return empty array when no monitors found", async function () {
const teamId = "emptyTeam";
monitorFindStub.resolves([]);
@@ -1696,7 +1696,7 @@ describe("monitorModule", function() {
sinon.assert.calledWith(monitorDeleteManyStub, { teamId });
});
- it("should handle database errors", async function() {
+ it("should handle database errors", async function () {
const teamId = "team123";
const dbError = new Error("Database connection error");
monitorFindStub.rejects(dbError);
@@ -1710,7 +1710,7 @@ describe("monitorModule", function() {
}
});
- it("should handle deleteMany errors", async function() {
+ it("should handle deleteMany errors", async function () {
const teamId = "team123";
monitorFindStub.resolves([{ _id: "1", name: "Monitor 1" }]);
monitorDeleteManyStub.rejects(new Error("Delete operation failed"));
@@ -1725,14 +1725,14 @@ describe("monitorModule", function() {
});
});
- describe("deleteMonitorsByUserId", function() {
- beforeEach(function() {});
+ describe("deleteMonitorsByUserId", function () {
+ beforeEach(function () {});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should delete all monitors for a user successfully", async function() {
+ it("should delete all monitors for a user successfully", async function () {
// Arrange
const userId = "user123";
const mockResult = {
@@ -1750,7 +1750,7 @@ describe("monitorModule", function() {
sinon.assert.calledWith(monitorDeleteManyStub, { userId: userId });
});
- it("should return zero deletedCount when no monitors found", async function() {
+ it("should return zero deletedCount when no monitors found", async function () {
// Arrange
const userId = "nonexistentUser";
const mockResult = {
@@ -1768,7 +1768,7 @@ describe("monitorModule", function() {
sinon.assert.calledWith(monitorDeleteManyStub, { userId: userId });
});
- it("should handle database errors", async function() {
+ it("should handle database errors", async function () {
// Arrange
const userId = "user123";
const dbError = new Error("Database connection error");
@@ -1786,8 +1786,8 @@ describe("monitorModule", function() {
});
});
- describe("editMonitor", function() {
- it("should edit a monitor successfully", async function() {
+ describe("editMonitor", function () {
+ it("should edit a monitor successfully", async function () {
// Arrange
const candidateId = "monitor123";
const candidateMonitor = {
@@ -1826,7 +1826,7 @@ describe("monitorModule", function() {
);
});
- it("should return null when monitor not found", async function() {
+ it("should return null when monitor not found", async function () {
// Arrange
const candidateId = "nonexistent123";
const candidateMonitor = {
@@ -1848,7 +1848,7 @@ describe("monitorModule", function() {
);
});
- it("should remove notifications from update data", async function() {
+ it("should remove notifications from update data", async function () {
// Arrange
const candidateId = "monitor123";
const candidateMonitor = {
@@ -1880,7 +1880,7 @@ describe("monitorModule", function() {
);
});
- it("should handle database errors", async function() {
+ it("should handle database errors", async function () {
// Arrange
const candidateId = "monitor123";
const candidateMonitor = {
@@ -1902,8 +1902,8 @@ describe("monitorModule", function() {
});
});
- describe("addDemoMonitors", function() {
- it("should add demo monitors successfully", async function() {
+ describe("addDemoMonitors", function () {
+ it("should add demo monitors successfully", async function () {
// Arrange
const userId = "user123";
const teamId = "team123";
@@ -1912,7 +1912,7 @@ describe("monitorModule", function() {
expect(result).to.deep.equal([{ _id: "123" }]);
});
- it("should handle database errors", async function() {
+ it("should handle database errors", async function () {
const userId = "user123";
const teamId = "team123";
diff --git a/Server/tests/db/notificationModule.test.js b/server/tests/db/notificationModule.test.js
old mode 100644
new mode 100755
similarity index 81%
rename from Server/tests/db/notificationModule.test.js
rename to server/tests/db/notificationModule.test.js
index 5c77018c2..3128130f8
--- a/Server/tests/db/notificationModule.test.js
+++ b/server/tests/db/notificationModule.test.js
@@ -6,32 +6,32 @@ import {
deleteNotificationsByMonitorId,
} from "../../db/mongo/modules/notificationModule.js";
-describe("notificationModule", function() {
+describe("notificationModule", function () {
const mockNotification = {
monitorId: "123",
};
const mockNotifications = [mockNotification];
let notificationSaveStub, notificationFindStub, notificationDeleteManyStub;
- beforeEach(function() {
+ beforeEach(function () {
notificationSaveStub = sinon.stub(Notification.prototype, "save").resolves();
notificationFindStub = sinon.stub(Notification, "find").resolves();
notificationDeleteManyStub = sinon.stub(Notification, "deleteMany").resolves();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- describe("createNotification", function() {
- it("should create a new notification", async function() {
+ describe("createNotification", function () {
+ it("should create a new notification", async function () {
const notificationData = { _id: "123", name: "test" };
notificationSaveStub.resolves(notificationData);
const res = await createNotification(notificationData);
expect(res).to.deep.equal(notificationData);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
notificationSaveStub.rejects(err);
try {
@@ -42,14 +42,14 @@ describe("notificationModule", function() {
});
});
- describe("getNotificationsByMonitorId", function() {
- it("should return notifications by monitor ID", async function() {
+ describe("getNotificationsByMonitorId", function () {
+ it("should return notifications by monitor ID", async function () {
notificationFindStub.resolves(mockNotifications);
const res = await getNotificationsByMonitorId(mockNotification.monitorId);
expect(res).to.deep.equal(mockNotifications);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
notificationFindStub.rejects(err);
try {
@@ -60,14 +60,14 @@ describe("notificationModule", function() {
});
});
- describe("deleteNotificationsByMonitorId", function() {
- it("should delete notifications by monitor ID", async function() {
+ describe("deleteNotificationsByMonitorId", function () {
+ it("should delete notifications by monitor ID", async function () {
notificationDeleteManyStub.resolves({ deletedCount: mockNotifications.length });
const res = await deleteNotificationsByMonitorId(mockNotification.monitorId);
expect(res).to.deep.equal(mockNotifications.length);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
notificationDeleteManyStub.rejects(err);
try {
diff --git a/Server/tests/db/pageSpeedCheckModule.test.js b/server/tests/db/pageSpeedCheckModule.test.js
old mode 100644
new mode 100755
similarity index 80%
rename from Server/tests/db/pageSpeedCheckModule.test.js
rename to server/tests/db/pageSpeedCheckModule.test.js
index 3bacc4a3b..5ef0e1845
--- a/Server/tests/db/pageSpeedCheckModule.test.js
+++ b/server/tests/db/pageSpeedCheckModule.test.js
@@ -14,26 +14,26 @@ const mockPageSpeedCheck = {
const mockDeletedResult = { deletedCount: 1 };
-describe("pageSpeedCheckModule", function() {
+describe("pageSpeedCheckModule", function () {
let pageSpeedCheckSaveStub, pageSpeedCheckDeleteManyStub;
- beforeEach(function() {
+ beforeEach(function () {
pageSpeedCheckSaveStub = sinon.stub(PageSpeedCheck.prototype, "save");
pageSpeedCheckDeleteManyStub = sinon.stub(PageSpeedCheck, "deleteMany");
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- describe("createPageSpeedCheck", function() {
- it("should return a page speed check", async function() {
+ describe("createPageSpeedCheck", function () {
+ it("should return a page speed check", async function () {
pageSpeedCheckSaveStub.resolves(mockPageSpeedCheck);
const pageSpeedCheck = await createPageSpeedCheck(mockPageSpeedCheck);
expect(pageSpeedCheck).to.deep.equal(mockPageSpeedCheck);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
pageSpeedCheckSaveStub.rejects(err);
try {
@@ -45,14 +45,14 @@ describe("pageSpeedCheckModule", function() {
});
});
- describe("deletePageSpeedChecksByMonitorId", function() {
- it("should return the number of deleted checks", async function() {
+ describe("deletePageSpeedChecksByMonitorId", function () {
+ it("should return the number of deleted checks", async function () {
pageSpeedCheckDeleteManyStub.resolves(mockDeletedResult);
const result = await deletePageSpeedChecksByMonitorId("monitorId");
expect(result).to.deep.equal(mockDeletedResult.deletedCount);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
pageSpeedCheckDeleteManyStub.rejects(err);
try {
diff --git a/Server/tests/db/recoveryModule.test.js b/server/tests/db/recoveryModule.test.js
old mode 100644
new mode 100755
similarity index 88%
rename from Server/tests/db/recoveryModule.test.js
rename to server/tests/db/recoveryModule.test.js
index 9d2978dd3..3f4e11c5c
--- a/Server/tests/db/recoveryModule.test.js
+++ b/server/tests/db/recoveryModule.test.js
@@ -43,7 +43,7 @@ const createQueryChain = (finalResult, comparePasswordResult = false) => ({
save: sinon.stub().resolves(),
});
-describe("recoveryModule", function() {
+describe("recoveryModule", function () {
let deleteManyStub,
saveStub,
findOneStub,
@@ -52,7 +52,7 @@ describe("recoveryModule", function() {
userFindOneStub;
let req, res;
- beforeEach(function() {
+ beforeEach(function () {
req = {
body: { email: "test@test.com" },
};
@@ -64,19 +64,19 @@ describe("recoveryModule", function() {
userFindOneStub = sinon.stub().resolves();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- describe("requestRecoveryToken", function() {
- it("should return a recovery token", async function() {
+ describe("requestRecoveryToken", function () {
+ it("should return a recovery token", async function () {
deleteManyStub.resolves();
saveStub.resolves(mockRecoveryToken);
const result = await requestRecoveryToken(req, res);
expect(result.email).to.equal(mockRecoveryToken.email);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("Test error");
deleteManyStub.rejects(err);
try {
@@ -88,14 +88,14 @@ describe("recoveryModule", function() {
});
});
- describe("validateRecoveryToken", function() {
- it("should return a recovery token if found", async function() {
+ describe("validateRecoveryToken", function () {
+ it("should return a recovery token if found", async function () {
findOneStub.resolves(mockRecoveryToken);
const result = await validateRecoveryToken(req, res);
expect(result).to.deep.equal(mockRecoveryToken);
});
- it("should thrown an error if a token is not found", async function() {
+ it("should thrown an error if a token is not found", async function () {
findOneStub.resolves(null);
try {
await validateRecoveryToken(req, res);
@@ -105,7 +105,7 @@ describe("recoveryModule", function() {
}
});
- it("should handle DB errors", async function() {
+ it("should handle DB errors", async function () {
const err = new Error("Test error");
findOneStub.rejects(err);
try {
@@ -117,19 +117,19 @@ describe("recoveryModule", function() {
});
});
- describe("resetPassword", function() {
- beforeEach(function() {
+ describe("resetPassword", function () {
+ beforeEach(function () {
req.body = {
password: "test",
newPassword: "test1",
};
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should thrown an error if a recovery token is not found", async function() {
+ it("should thrown an error if a recovery token is not found", async function () {
findOneStub.resolves(null);
try {
await resetPassword(req, res);
@@ -139,7 +139,7 @@ describe("recoveryModule", function() {
}
});
- it("should throw an error if a user is not found", async function() {
+ it("should throw an error if a user is not found", async function () {
findOneStub.resolves(mockRecoveryToken);
userFindOneStub = sinon.stub(User, "findOne").resolves(null);
try {
@@ -150,7 +150,7 @@ describe("recoveryModule", function() {
}
});
- it("should throw an error if the passwords match", async function() {
+ it("should throw an error if the passwords match", async function () {
findOneStub.resolves(mockRecoveryToken);
saveStub.resolves();
userFindOneStub = sinon
@@ -164,7 +164,7 @@ describe("recoveryModule", function() {
}
});
- it("should return a user without password if successful", async function() {
+ it("should return a user without password if successful", async function () {
findOneStub.resolves(mockRecoveryToken);
saveStub.resolves();
userFindOneStub = sinon
diff --git a/Server/tests/db/settingsModule.test.js b/server/tests/db/settingsModule.test.js
old mode 100644
new mode 100755
similarity index 75%
rename from Server/tests/db/settingsModule.test.js
rename to server/tests/db/settingsModule.test.js
index b518ba61d..7651adb4b
--- a/Server/tests/db/settingsModule.test.js
+++ b/server/tests/db/settingsModule.test.js
@@ -9,26 +9,26 @@ const mockAppSettings = {
appName: "Test App",
};
-describe("SettingsModule", function() {
+describe("SettingsModule", function () {
let appSettingsFindOneStub, appSettingsFindOneAndUpdateStub;
- beforeEach(function() {
+ beforeEach(function () {
appSettingsFindOneStub = sinon.stub(AppSettings, "findOne");
appSettingsFindOneAndUpdateStub = sinon.stub(AppSettings, "findOneAndUpdate");
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- describe("getAppSettings", function() {
- it("should return app settings", async function() {
+ describe("getAppSettings", function () {
+ it("should return app settings", async function () {
appSettingsFindOneStub.resolves(mockAppSettings);
const result = await getAppSettings();
expect(result).to.deep.equal(mockAppSettings);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("Test error");
appSettingsFindOneStub.throws(err);
try {
@@ -39,14 +39,14 @@ describe("SettingsModule", function() {
});
});
- describe("updateAppSettings", function() {
- it("should update app settings", async function() {
+ describe("updateAppSettings", function () {
+ it("should update app settings", async function () {
appSettingsFindOneAndUpdateStub.resolves(mockAppSettings);
const result = await updateAppSettings(mockAppSettings);
expect(result).to.deep.equal(mockAppSettings);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("Test error");
appSettingsFindOneAndUpdateStub.throws(err);
try {
diff --git a/Server/tests/db/statusPageModule.test.js b/server/tests/db/statusPageModule.test.js
old mode 100644
new mode 100755
similarity index 86%
rename from Server/tests/db/statusPageModule.test.js
rename to server/tests/db/statusPageModule.test.js
index 3d5d5e9d0..60c356aa5
--- a/Server/tests/db/statusPageModule.test.js
+++ b/server/tests/db/statusPageModule.test.js
@@ -6,21 +6,21 @@ import {
import StatusPage from "../../db/models/StatusPage.js";
import { errorMessages } from "../../utils/messages.js";
-describe("statusPageModule", function() {
+describe("statusPageModule", function () {
let statusPageFindOneStub, statusPageSaveStub, statusPageFindStub;
- beforeEach(function() {
+ beforeEach(function () {
statusPageSaveStub = sinon.stub(StatusPage.prototype, "save");
statusPageFindOneStub = sinon.stub(StatusPage, "findOne");
statusPageFindStub = sinon.stub(StatusPage, "find");
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- describe("createStatusPage", function() {
- it("should throw an error if a non-unique url is provided", async function() {
+ describe("createStatusPage", function () {
+ it("should throw an error if a non-unique url is provided", async function () {
statusPageFindOneStub.resolves(true);
try {
await createStatusPage({ url: "test" });
@@ -30,7 +30,7 @@ describe("statusPageModule", function() {
}
});
- it("should handle duplicate URL errors", async function() {
+ it("should handle duplicate URL errors", async function () {
const err = new Error("test");
err.code = 11000;
statusPageSaveStub.rejects(err);
@@ -41,7 +41,7 @@ describe("statusPageModule", function() {
}
});
- it("should return a status page if a unique url is provided", async function() {
+ it("should return a status page if a unique url is provided", async function () {
statusPageFindOneStub.resolves(null);
statusPageFindStub.resolves([]);
const mockStatusPage = { url: "test" };
@@ -51,8 +51,8 @@ describe("statusPageModule", function() {
});
});
- describe("getStatusPageByUrl", function() {
- it("should throw an error if a status page is not found", async function() {
+ describe("getStatusPageByUrl", function () {
+ it("should throw an error if a status page is not found", async function () {
statusPageFindOneStub.resolves(null);
try {
await getStatusPageByUrl("test");
@@ -62,7 +62,7 @@ describe("statusPageModule", function() {
}
});
- it("should return a status page if a status page is found", async function() {
+ it("should return a status page if a status page is found", async function () {
const mockStatusPage = { url: "test" };
statusPageFindOneStub.resolves(mockStatusPage);
const statusPage = await getStatusPageByUrl(mockStatusPage.url);
diff --git a/Server/tests/db/userModule.test.js b/server/tests/db/userModule.test.js
old mode 100644
new mode 100755
similarity index 80%
rename from Server/tests/db/userModule.test.js
rename to server/tests/db/userModule.test.js
index b52ba1880..884956995
--- a/Server/tests/db/userModule.test.js
+++ b/server/tests/db/userModule.test.js
@@ -27,7 +27,7 @@ const imageFile = {
image: 1,
};
-describe("userModule", function() {
+describe("userModule", function () {
let teamSaveStub,
teamFindByIdAndDeleteStub,
userSaveStub,
@@ -40,7 +40,7 @@ describe("userModule", function() {
generateAvatarImageStub,
parseBooleanStub;
- beforeEach(function() {
+ beforeEach(function () {
teamSaveStub = sinon.stub(TeamModel.prototype, "save");
teamFindByIdAndDeleteStub = sinon.stub(TeamModel, "findByIdAndDelete");
userSaveStub = sinon.stub(UserModel.prototype, "save");
@@ -54,12 +54,12 @@ describe("userModule", function() {
parseBooleanStub = sinon.stub().returns(true);
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- describe("insertUser", function() {
- it("should insert a regular user", async function() {
+ describe("insertUser", function () {
+ it("should insert a regular user", async function () {
userSaveStub.resolves(mockUser);
userFindOneStub.returns({
select: sinon.stub().returns({
@@ -70,7 +70,7 @@ describe("userModule", function() {
expect(result).to.deep.equal(mockUser);
});
- it("should insert a superadmin user", async function() {
+ it("should insert a superadmin user", async function () {
userSaveStub.resolves(mockSuperUser);
userFindOneStub.returns({
select: sinon.stub().returns({
@@ -81,7 +81,7 @@ describe("userModule", function() {
expect(result).to.deep.equal(mockSuperUser);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
userSaveStub.rejects(err);
try {
@@ -92,7 +92,7 @@ describe("userModule", function() {
}
});
- it("should handle a duplicate key error", async function() {
+ it("should handle a duplicate key error", async function () {
const err = new Error("test error");
err.code = 11000;
userSaveStub.rejects(err);
@@ -105,8 +105,8 @@ describe("userModule", function() {
});
});
- describe("getUserByEmail", function() {
- it("should return a user", async function() {
+ describe("getUserByEmail", function () {
+ it("should return a user", async function () {
userFindOneStub.returns({
select: sinon.stub().resolves(mockUser),
});
@@ -115,8 +115,8 @@ describe("userModule", function() {
});
});
- describe("getUserByEmail", function() {
- it("throw an error if a user is not found", async function() {
+ describe("getUserByEmail", function () {
+ it("throw an error if a user is not found", async function () {
userFindOneStub.returns({
select: sinon.stub().resolves(null),
});
@@ -128,10 +128,10 @@ describe("userModule", function() {
});
});
- describe("updateUser", function() {
+ describe("updateUser", function () {
let req, res;
- beforeEach(function() {
+ beforeEach(function () {
req = {
params: {
userId: "testId",
@@ -148,9 +148,9 @@ describe("userModule", function() {
res = {};
});
- afterEach(function() {});
+ afterEach(function () {});
- it("should update a user", async function() {
+ it("should update a user", async function () {
parseBooleanStub.returns(false);
userFindByIdAndUpdateStub.returns({
select: sinon.stub().returns({
@@ -166,7 +166,7 @@ describe("userModule", function() {
expect(result).to.deep.equal(mockUser);
});
- it("should delete a user profile image", async function() {
+ it("should delete a user profile image", async function () {
req.body.deleteProfileImage = "true";
userFindByIdAndUpdateStub.returns({
select: sinon.stub().returns({
@@ -182,7 +182,7 @@ describe("userModule", function() {
expect(result).to.deep.equal(mockUser);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
userFindByIdAndUpdateStub.throws(err);
try {
@@ -194,14 +194,14 @@ describe("userModule", function() {
});
});
- describe("deleteUser", function() {
- it("should return a deleted user", async function() {
+ describe("deleteUser", function () {
+ it("should return a deleted user", async function () {
userFindByIdAndDeleteStub.resolves(mockUser);
const result = await deleteUser("testId");
expect(result).to.deep.equal(mockUser);
});
- it("should throw an error if a user is not found", async function() {
+ it("should throw an error if a user is not found", async function () {
try {
await deleteUser("testId");
} catch (error) {
@@ -210,7 +210,7 @@ describe("userModule", function() {
}
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
userFindByIdAndDeleteStub.throws(err);
try {
@@ -222,14 +222,14 @@ describe("userModule", function() {
});
});
- describe("deleteTeam", function() {
- it("should return true if team deleted", async function() {
+ describe("deleteTeam", function () {
+ it("should return true if team deleted", async function () {
teamFindByIdAndDeleteStub.resolves();
const result = await deleteTeam("testId");
expect(result).to.equal(true);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
teamFindByIdAndDeleteStub.throws(err);
try {
@@ -241,14 +241,14 @@ describe("userModule", function() {
});
});
- describe("deleteAllOtherUsers", function() {
- it("should return true if all other users deleted", async function() {
+ describe("deleteAllOtherUsers", function () {
+ it("should return true if all other users deleted", async function () {
userDeleteManyStub.resolves(true);
const result = await deleteAllOtherUsers();
expect(result).to.equal(true);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
userDeleteManyStub.throws(err);
try {
@@ -260,8 +260,8 @@ describe("userModule", function() {
});
});
- describe("getAllUsers", function() {
- it("should return all users", async function() {
+ describe("getAllUsers", function () {
+ it("should return all users", async function () {
userFindStub.returns({
select: sinon.stub().returns({
select: sinon.stub().resolves([mockUser]),
@@ -271,7 +271,7 @@ describe("userModule", function() {
expect(result).to.deep.equal([mockUser]);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
userFindStub.throws(err);
try {
@@ -283,14 +283,14 @@ describe("userModule", function() {
});
});
- describe("logoutUser", function() {
- it("should return true if user logged out", async function() {
+ describe("logoutUser", function () {
+ it("should return true if user logged out", async function () {
userUpdateOneStub.resolves(true);
const result = await logoutUser("testId");
expect(result).to.equal(true);
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const err = new Error("test error");
userUpdateOneStub.throws(err);
try {
diff --git a/Server/tests/services/emailService.test.js b/server/tests/services/emailService.test.js
old mode 100644
new mode 100755
similarity index 89%
rename from Server/tests/services/emailService.test.js
rename to server/tests/services/emailService.test.js
index 2584aa1bc..541789d99
--- a/Server/tests/services/emailService.test.js
+++ b/server/tests/services/emailService.test.js
@@ -1,7 +1,7 @@
import sinon from "sinon";
import EmailService from "../../service/emailService.js";
-describe("EmailService - Constructor", function() {
+describe("EmailService - Constructor", function () {
let settingsServiceMock;
let fsMock;
let pathMock;
@@ -10,7 +10,7 @@ describe("EmailService - Constructor", function() {
let nodemailerMock;
let loggerMock;
- beforeEach(function() {
+ beforeEach(function () {
settingsServiceMock = {
getSettings: sinon.stub().returns({
systemEmailHost: "smtp.example.com",
@@ -43,11 +43,11 @@ describe("EmailService - Constructor", function() {
};
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should initialize template loaders and email transporter", function() {
+ it("should initialize template loaders and email transporter", function () {
const emailService = new EmailService(
settingsServiceMock,
fsMock,
@@ -79,7 +79,7 @@ describe("EmailService - Constructor", function() {
});
});
- it("should have undefined templates if FS fails", function() {
+ it("should have undefined templates if FS fails", function () {
fsMock = {
readFileSync: sinon.stub().throws(new Error("File read error")),
};
@@ -97,7 +97,7 @@ describe("EmailService - Constructor", function() {
});
});
-describe("EmailService - buildAndSendEmail", function() {
+describe("EmailService - buildAndSendEmail", function () {
let settingsServiceMock;
let fsMock;
let pathMock;
@@ -107,7 +107,7 @@ describe("EmailService - buildAndSendEmail", function() {
let loggerMock;
let emailService;
- beforeEach(function() {
+ beforeEach(function () {
settingsServiceMock = {
getSettings: sinon.stub().returns({
systemEmailHost: "smtp.example.com",
@@ -150,11 +150,11 @@ describe("EmailService - buildAndSendEmail", function() {
);
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should build and send email successfully", async function() {
+ it("should build and send email successfully", async function () {
const messageId = await emailService.buildAndSendEmail(
"welcomeEmailTemplate",
{},
@@ -166,7 +166,7 @@ describe("EmailService - buildAndSendEmail", function() {
expect(nodemailerMock.createTransport().sendMail.calledOnce).to.be.true;
});
- it("should log error if building HTML fails", async function() {
+ it("should log error if building HTML fails", async function () {
mjml2htmlMock.throws(new Error("MJML error"));
const messageId = await emailService.buildAndSendEmail(
@@ -179,7 +179,7 @@ describe("EmailService - buildAndSendEmail", function() {
expect(loggerMock.error.getCall(0).args[0].message).to.equal("MJML error");
});
- it("should log error if sending email fails", async function() {
+ it("should log error if sending email fails", async function () {
nodemailerMock.createTransport().sendMail.rejects(new Error("SMTP error"));
await emailService.buildAndSendEmail(
"welcomeEmailTemplate",
@@ -191,7 +191,7 @@ describe("EmailService - buildAndSendEmail", function() {
expect(loggerMock.error.getCall(0).args[0].message).to.equal("SMTP error");
});
- it("should log error if both building HTML and sending email fail", async function() {
+ it("should log error if both building HTML and sending email fail", async function () {
mjml2htmlMock.throws(new Error("MJML error"));
nodemailerMock.createTransport().sendMail.rejects(new Error("SMTP error"));
@@ -208,5 +208,5 @@ describe("EmailService - buildAndSendEmail", function() {
expect(loggerMock.error.getCall(1).args[0].message).to.equal("SMTP error");
});
- it("should log an error if buildHtml fails", async function() {});
+ it("should log an error if buildHtml fails", async function () {});
});
diff --git a/Server/tests/services/jobQueue.test.js b/server/tests/services/jobQueue.test.js
old mode 100644
new mode 100755
similarity index 90%
rename from Server/tests/services/jobQueue.test.js
rename to server/tests/services/jobQueue.test.js
index a7778a56d..88d57f339
--- a/Server/tests/services/jobQueue.test.js
+++ b/server/tests/services/jobQueue.test.js
@@ -51,7 +51,7 @@ class WorkerStub {
}
}
-describe("JobQueue", function() {
+describe("JobQueue", function () {
let settingsService,
logger,
db,
@@ -60,7 +60,7 @@ describe("JobQueue", function() {
notificationService,
jobQueue;
- beforeEach(async function() {
+ beforeEach(async function () {
settingsService = { getSettings: sinon.stub() };
statusService = { updateStatus: sinon.stub() };
notificationService = { handleNotifications: sinon.stub() };
@@ -83,12 +83,12 @@ describe("JobQueue", function() {
);
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- describe("createJobQueue", function() {
- it("should create a new JobQueue and add jobs for active monitors", async function() {
+ describe("createJobQueue", function () {
+ it("should create a new JobQueue and add jobs for active monitors", async function () {
db.getAllMonitors.returns([
{ id: 1, isActive: true },
{ id: 2, isActive: true },
@@ -108,7 +108,7 @@ describe("JobQueue", function() {
expect(jobQueue.queue.jobs.length).to.equal(4);
});
- it("should reject with an error if an error occurs", async function() {
+ it("should reject with an error if an error occurs", async function () {
db.getAllMonitors.throws("Error");
try {
const jobQueue = await JobQueue.createJobQueue(
@@ -127,7 +127,7 @@ describe("JobQueue", function() {
}
});
- it("should reject with an error if an error occurs, should not overwrite error data", async function() {
+ it("should reject with an error if an error occurs, should not overwrite error data", async function () {
const error = new Error("Error");
error.service = "otherService";
error.method = "otherMethod";
@@ -151,15 +151,15 @@ describe("JobQueue", function() {
});
});
- describe("Constructor", function() {
- it("should construct a new JobQueue with default port and host if not provided", async function() {
+ describe("Constructor", function () {
+ it("should construct a new JobQueue with default port and host if not provided", async function () {
settingsService.getSettings.returns({});
expect(jobQueue.connection.host).to.equal("127.0.0.1");
expect(jobQueue.connection.port).to.equal(6379);
});
- it("should construct a new JobQueue with provided port and host", async function() {
+ it("should construct a new JobQueue with provided port and host", async function () {
settingsService.getSettings.returns({ redisHost: "localhost", redisPort: 1234 });
const jobQueue = await JobQueue.createJobQueue(
db,
@@ -176,8 +176,8 @@ describe("JobQueue", function() {
});
});
- describe("isMaintenanceWindow", function() {
- it("should throw an error if error occurs", async function() {
+ describe("isMaintenanceWindow", function () {
+ it("should throw an error if error occurs", async function () {
db.getMaintenanceWindowsByMonitorId.throws("Error");
const jobQueue = await JobQueue.createJobQueue(
db,
@@ -197,7 +197,7 @@ describe("JobQueue", function() {
}
});
- it("should return true if in maintenance window with no repeat", async function() {
+ it("should return true if in maintenance window with no repeat", async function () {
db.getMaintenanceWindowsByMonitorId.returns([
{
active: true,
@@ -220,7 +220,7 @@ describe("JobQueue", function() {
expect(inWindow).to.be.true;
});
- it("should return true if in maintenance window with repeat", async function() {
+ it("should return true if in maintenance window with repeat", async function () {
db.getMaintenanceWindowsByMonitorId.returns([
{
active: true,
@@ -243,7 +243,7 @@ describe("JobQueue", function() {
expect(inWindow).to.be.true;
});
- it("should return false if in end < start", async function() {
+ it("should return false if in end < start", async function () {
db.getMaintenanceWindowsByMonitorId.returns([
{
active: true,
@@ -266,7 +266,7 @@ describe("JobQueue", function() {
expect(inWindow).to.be.false;
});
- it("should return false if not in maintenance window", async function() {
+ it("should return false if not in maintenance window", async function () {
db.getMaintenanceWindowsByMonitorId.returns([
{
active: false,
@@ -290,8 +290,8 @@ describe("JobQueue", function() {
});
});
- describe("createJobHandler", function() {
- it("resolve to an error if an error is thrown within", async function() {
+ describe("createJobHandler", function () {
+ it("resolve to an error if an error is thrown within", async function () {
const jobQueue = await JobQueue.createJobQueue(
db,
networkService,
@@ -312,7 +312,7 @@ describe("JobQueue", function() {
}
});
- it("should log info if job is in maintenance window", async function() {
+ it("should log info if job is in maintenance window", async function () {
const jobQueue = await JobQueue.createJobQueue(
db,
networkService,
@@ -332,7 +332,7 @@ describe("JobQueue", function() {
);
});
- it("should return if status has not changed", async function() {
+ it("should return if status has not changed", async function () {
const jobQueue = await JobQueue.createJobQueue(
db,
networkService,
@@ -350,7 +350,7 @@ describe("JobQueue", function() {
expect(jobQueue.notificationService.handleNotifications.notCalled).to.be.true;
});
- it("should return if status has changed, but prevStatus was undefined (monitor paused)", async function() {
+ it("should return if status has changed, but prevStatus was undefined (monitor paused)", async function () {
const jobQueue = await JobQueue.createJobQueue(
db,
networkService,
@@ -370,7 +370,7 @@ describe("JobQueue", function() {
expect(jobQueue.notificationService.handleNotifications.notCalled).to.be.true;
});
- it("should call notification service if status changed and monitor was not paused", async function() {
+ it("should call notification service if status changed and monitor was not paused", async function () {
const jobQueue = await JobQueue.createJobQueue(
db,
networkService,
@@ -391,8 +391,8 @@ describe("JobQueue", function() {
});
});
- describe("getWorkerStats", function() {
- it("should throw an error if getRepeatable Jobs fails", async function() {
+ describe("getWorkerStats", function () {
+ it("should throw an error if getRepeatable Jobs fails", async function () {
const jobQueue = await JobQueue.createJobQueue(
db,
networkService,
@@ -414,7 +414,7 @@ describe("JobQueue", function() {
}
});
- it("should throw an error if getRepeatable Jobs fails but respect existing error data", async function() {
+ it("should throw an error if getRepeatable Jobs fails but respect existing error data", async function () {
const jobQueue = await JobQueue.createJobQueue(
db,
networkService,
@@ -440,8 +440,8 @@ describe("JobQueue", function() {
});
});
- describe("scaleWorkers", function() {
- it("should scale workers to 5 if no workers", async function() {
+ describe("scaleWorkers", function () {
+ it("should scale workers to 5 if no workers", async function () {
const jobQueue = await JobQueue.createJobQueue(
db,
networkService,
@@ -455,7 +455,7 @@ describe("JobQueue", function() {
expect(jobQueue.workers.length).to.equal(5);
});
- it("should scale workers up", async function() {
+ it("should scale workers up", async function () {
const jobQueue = await JobQueue.createJobQueue(
db,
networkService,
@@ -473,7 +473,7 @@ describe("JobQueue", function() {
expect(jobQueue.workers.length).to.equal(20);
});
- it("should scale workers down, even with error of worker.close fails", async function() {
+ it("should scale workers down, even with error of worker.close fails", async function () {
WorkerStub.prototype.close = async () => {
throw new Error("Error");
};
@@ -499,7 +499,7 @@ describe("JobQueue", function() {
expect(jobQueue.workers.length).to.equal(5);
});
- it("should scale workers down", async function() {
+ it("should scale workers down", async function () {
WorkerStub.prototype.close = async () => {
return true;
};
@@ -525,7 +525,7 @@ describe("JobQueue", function() {
expect(jobQueue.workers.length).to.equal(5);
});
- it("should return false if scaling doesn't happen", async function() {
+ it("should return false if scaling doesn't happen", async function () {
const jobQueue = await JobQueue.createJobQueue(
db,
networkService,
@@ -542,8 +542,8 @@ describe("JobQueue", function() {
});
});
- describe("getJobs", function() {
- it("should return jobs", async function() {
+ describe("getJobs", function () {
+ it("should return jobs", async function () {
const jobQueue = await JobQueue.createJobQueue(
db,
networkService,
@@ -558,7 +558,7 @@ describe("JobQueue", function() {
expect(jobs.length).to.equal(0);
});
- it("should throw an error if getRepeatableJobs fails", async function() {
+ it("should throw an error if getRepeatableJobs fails", async function () {
const jobQueue = await JobQueue.createJobQueue(
db,
networkService,
@@ -581,7 +581,7 @@ describe("JobQueue", function() {
}
});
- it("should throw an error if getRepeatableJobs fails but respect existing error data", async function() {
+ it("should throw an error if getRepeatableJobs fails but respect existing error data", async function () {
const jobQueue = await JobQueue.createJobQueue(
db,
networkService,
@@ -608,13 +608,13 @@ describe("JobQueue", function() {
});
});
- describe("getJobStats", function() {
- it("should return job stats for no jobs", async function() {
+ describe("getJobStats", function () {
+ it("should return job stats for no jobs", async function () {
const jobStats = await jobQueue.getJobStats();
expect(jobStats).to.deep.equal({ jobs: [], workers: 5 });
});
- it("should return job stats for jobs", async function() {
+ it("should return job stats for jobs", async function () {
jobQueue.queue.getJobs = async () => {
return [{ data: { url: "test" }, getState: async () => "completed" }];
};
@@ -625,7 +625,7 @@ describe("JobQueue", function() {
});
});
- it("should reject with an error if mapping jobs fails", async function() {
+ it("should reject with an error if mapping jobs fails", async function () {
jobQueue.queue.getJobs = async () => {
return [
{
@@ -645,7 +645,7 @@ describe("JobQueue", function() {
}
});
- it("should reject with an error if mapping jobs fails but respect existing error data", async function() {
+ it("should reject with an error if mapping jobs fails but respect existing error data", async function () {
jobQueue.queue.getJobs = async () => {
return [
{
@@ -669,13 +669,13 @@ describe("JobQueue", function() {
});
});
- describe("addJob", function() {
- it("should add a job to the queue", async function() {
+ describe("addJob", function () {
+ it("should add a job to the queue", async function () {
jobQueue.addJob("test", { url: "test" });
expect(jobQueue.queue.jobs.length).to.equal(1);
});
- it("should reject with an error if adding fails", async function() {
+ it("should reject with an error if adding fails", async function () {
jobQueue.queue.add = async () => {
throw new Error("Error adding job");
};
@@ -688,7 +688,7 @@ describe("JobQueue", function() {
}
});
- it("should reject with an error if adding fails but respect existing error data", async function() {
+ it("should reject with an error if adding fails but respect existing error data", async function () {
jobQueue.queue.add = async () => {
const error = new Error("Error adding job");
error.service = "otherService";
@@ -705,8 +705,8 @@ describe("JobQueue", function() {
});
});
- describe("deleteJob", function() {
- it("should delete a job from the queue", async function() {
+ describe("deleteJob", function () {
+ it("should delete a job from the queue", async function () {
jobQueue.getWorkerStats = sinon.stub().returns({ load: 1, jobs: [{}] });
jobQueue.scaleWorkers = sinon.stub();
const monitor = { _id: 1 };
@@ -719,7 +719,7 @@ describe("JobQueue", function() {
// expect(jobQueue.scaleWorkers.calledOnce).to.be.true;
});
- it("should log an error if job is not found", async function() {
+ it("should log an error if job is not found", async function () {
jobQueue.getWorkerStats = sinon.stub().returns({ load: 1, jobs: [{}] });
jobQueue.scaleWorkers = sinon.stub();
const monitor = { _id: 1 };
@@ -729,7 +729,7 @@ describe("JobQueue", function() {
expect(logger.error.calledOnce).to.be.true;
});
- it("should reject with an error if removeRepeatable fails", async function() {
+ it("should reject with an error if removeRepeatable fails", async function () {
jobQueue.queue.removeRepeatable = async () => {
const error = new Error("removeRepeatable error");
throw error;
@@ -744,7 +744,7 @@ describe("JobQueue", function() {
}
});
- it("should reject with an error if removeRepeatable fails but respect existing error data", async function() {
+ it("should reject with an error if removeRepeatable fails but respect existing error data", async function () {
jobQueue.queue.removeRepeatable = async () => {
const error = new Error("removeRepeatable error");
error.service = "otherService";
@@ -762,8 +762,8 @@ describe("JobQueue", function() {
});
});
- describe("getMetrics", function() {
- it("should return metrics for the job queue", async function() {
+ describe("getMetrics", function () {
+ it("should return metrics for the job queue", async function () {
jobQueue.queue.getWaitingCount = async () => 1;
jobQueue.queue.getActiveCount = async () => 2;
jobQueue.queue.getCompletedCount = async () => 3;
@@ -781,7 +781,7 @@ describe("JobQueue", function() {
});
});
- it("should log an error if metrics operations fail", async function() {
+ it("should log an error if metrics operations fail", async function () {
jobQueue.queue.getWaitingCount = async () => {
throw new Error("Error");
};
@@ -791,8 +791,8 @@ describe("JobQueue", function() {
});
});
- describe("obliterate", function() {
- it("should return true if obliteration is successful", async function() {
+ describe("obliterate", function () {
+ it("should return true if obliteration is successful", async function () {
jobQueue.queue.pause = async () => true;
jobQueue.getJobs = async () => [{ key: 1, id: 1 }];
jobQueue.queue.removeRepeatableByKey = async () => true;
@@ -802,7 +802,7 @@ describe("JobQueue", function() {
expect(obliteration).to.be.true;
});
- it("should throw an error if obliteration fails", async function() {
+ it("should throw an error if obliteration fails", async function () {
jobQueue.getMetrics = async () => {
throw new Error("Error");
};
@@ -815,7 +815,7 @@ describe("JobQueue", function() {
}
});
- it("should throw an error if obliteration fails but respect existing error data", async function() {
+ it("should throw an error if obliteration fails but respect existing error data", async function () {
jobQueue.getMetrics = async () => {
const error = new Error("Error");
error.service = "otherService";
diff --git a/Server/tests/services/networkService.test.js b/server/tests/services/networkService.test.js
old mode 100644
new mode 100755
similarity index 91%
rename from Server/tests/services/networkService.test.js
rename to server/tests/services/networkService.test.js
index a5a59c938..44ddf8576
--- a/Server/tests/services/networkService.test.js
+++ b/server/tests/services/networkService.test.js
@@ -3,10 +3,10 @@ import NetworkService from "../../service/networkService.js";
import { expect } from "chai";
import http from "http";
import { errorMessages } from "../../utils/messages.js";
-describe("Network Service", function() {
+describe("Network Service", function () {
let axios, ping, Docker, logger, networkService;
- beforeEach(function() {
+ beforeEach(function () {
axios = {
get: sinon.stub().resolves({
data: { foo: "bar" },
@@ -35,22 +35,22 @@ describe("Network Service", function() {
networkService = new NetworkService(axios, ping, logger, http, Docker);
});
- describe("constructor", function() {
- it("should create a new NetworkService instance", function() {
+ describe("constructor", function () {
+ it("should create a new NetworkService instance", function () {
const networkService = new NetworkService();
expect(networkService).to.be.an.instanceOf(NetworkService);
});
});
- describe("timeRequest", function() {
- it("should time an asynchronous operation", async function() {
+ describe("timeRequest", function () {
+ it("should time an asynchronous operation", async function () {
const operation = sinon.stub().resolves("success");
const { response, responseTime } = await networkService.timeRequest(operation);
expect(response).to.equal("success");
expect(responseTime).to.be.a("number");
});
- it("should handle errors if operation throws error", async function() {
+ it("should handle errors if operation throws error", async function () {
const error = new Error("Test error");
const operation = sinon.stub().throws(error);
const { response, responseTime } = await networkService.timeRequest(operation);
@@ -60,8 +60,8 @@ describe("Network Service", function() {
});
});
- describe("requestPing", function() {
- it("should return a response object if ping successful", async function() {
+ describe("requestPing", function () {
+ it("should return a response object if ping successful", async function () {
const pingResult = await networkService.requestPing({
data: { url: "http://test.com", _id: "123" },
});
@@ -71,7 +71,7 @@ describe("Network Service", function() {
expect(pingResult.status).to.be.true;
});
- it("should return a response object if ping unsuccessful", async function() {
+ it("should return a response object if ping unsuccessful", async function () {
const error = new Error("Test error");
networkService.timeRequest = sinon
.stub()
@@ -86,7 +86,7 @@ describe("Network Service", function() {
expect(pingResult.code).to.equal(networkService.PING_ERROR);
});
- it("should throw an error if ping cannot resolve", async function() {
+ it("should throw an error if ping cannot resolve", async function () {
const error = new Error("test error");
networkService.timeRequest = sinon.stub().throws(error);
try {
@@ -100,8 +100,8 @@ describe("Network Service", function() {
});
});
- describe("requestHttp", function() {
- it("should return a response object if http successful", async function() {
+ describe("requestHttp", function () {
+ it("should return a response object if http successful", async function () {
const job = { data: { url: "http://test.com", _id: "123", type: "http" } };
const httpResult = await networkService.requestHttp(job);
expect(httpResult.monitorId).to.equal("123");
@@ -110,7 +110,7 @@ describe("Network Service", function() {
expect(httpResult.status).to.be.true;
});
- it("should return a response object if http unsuccessful", async function() {
+ it("should return a response object if http unsuccessful", async function () {
const error = new Error("Test error");
error.response = { status: 404 };
networkService.timeRequest = sinon
@@ -125,7 +125,7 @@ describe("Network Service", function() {
expect(httpResult.code).to.equal(404);
});
- it("should return a response object if http unsuccessful with unknown code", async function() {
+ it("should return a response object if http unsuccessful with unknown code", async function () {
const error = new Error("Test error");
error.response = {};
networkService.timeRequest = sinon
@@ -140,7 +140,7 @@ describe("Network Service", function() {
expect(httpResult.code).to.equal(networkService.NETWORK_ERROR);
});
- it("should throw an error if an error occurs", async function() {
+ it("should throw an error if an error occurs", async function () {
const error = new Error("test error");
networkService.timeRequest = sinon.stub().throws(error);
try {
@@ -154,8 +154,8 @@ describe("Network Service", function() {
});
});
- describe("requestPagespeed", function() {
- it("should return a response object if pagespeed successful", async function() {
+ describe("requestPagespeed", function () {
+ it("should return a response object if pagespeed successful", async function () {
const job = { data: { url: "http://test.com", _id: "123", type: "pagespeed" } };
const pagespeedResult = await networkService.requestPagespeed(job);
expect(pagespeedResult.monitorId).to.equal("123");
@@ -164,7 +164,7 @@ describe("Network Service", function() {
expect(pagespeedResult.status).to.be.true;
});
- it("should return a response object if pagespeed unsuccessful", async function() {
+ it("should return a response object if pagespeed unsuccessful", async function () {
const error = new Error("Test error");
error.response = { status: 404 };
networkService.timeRequest = sinon
@@ -179,7 +179,7 @@ describe("Network Service", function() {
expect(pagespeedResult.code).to.equal(404);
});
- it("should return a response object if pagespeed unsuccessful with an unknown code", async function() {
+ it("should return a response object if pagespeed unsuccessful with an unknown code", async function () {
const error = new Error("Test error");
error.response = {};
networkService.timeRequest = sinon
@@ -194,7 +194,7 @@ describe("Network Service", function() {
expect(pagespeedResult.code).to.equal(networkService.NETWORK_ERROR);
});
- it("should throw an error if pagespeed cannot resolve", async function() {
+ it("should throw an error if pagespeed cannot resolve", async function () {
const error = new Error("test error");
networkService.timeRequest = sinon.stub().throws(error);
try {
@@ -208,8 +208,8 @@ describe("Network Service", function() {
});
});
- describe("requestHardware", function() {
- it("should return a response object if hardware successful", async function() {
+ describe("requestHardware", function () {
+ it("should return a response object if hardware successful", async function () {
const job = { data: { url: "http://test.com", _id: "123", type: "hardware" } };
const httpResult = await networkService.requestHardware(job);
expect(httpResult.monitorId).to.equal("123");
@@ -218,7 +218,7 @@ describe("Network Service", function() {
expect(httpResult.status).to.be.true;
});
- it("should return a response object if hardware successful and job has a secret", async function() {
+ it("should return a response object if hardware successful and job has a secret", async function () {
const job = {
data: {
url: "http://test.com",
@@ -234,7 +234,7 @@ describe("Network Service", function() {
expect(httpResult.status).to.be.true;
});
- it("should return a response object if hardware unsuccessful", async function() {
+ it("should return a response object if hardware unsuccessful", async function () {
const error = new Error("Test error");
error.response = { status: 404 };
networkService.timeRequest = sinon
@@ -249,7 +249,7 @@ describe("Network Service", function() {
expect(httpResult.code).to.equal(404);
});
- it("should return a response object if hardware unsuccessful with unknown code", async function() {
+ it("should return a response object if hardware unsuccessful with unknown code", async function () {
const error = new Error("Test error");
error.response = {};
networkService.timeRequest = sinon
@@ -264,7 +264,7 @@ describe("Network Service", function() {
expect(httpResult.code).to.equal(networkService.NETWORK_ERROR);
});
- it("should throw an error if hardware cannot resolve", async function() {
+ it("should throw an error if hardware cannot resolve", async function () {
const error = new Error("test error");
networkService.timeRequest = sinon.stub().throws(error);
try {
@@ -278,8 +278,8 @@ describe("Network Service", function() {
});
});
- describe("requestDocker", function() {
- it("should return a response object if docker successful", async function() {
+ describe("requestDocker", function () {
+ it("should return a response object if docker successful", async function () {
const job = { data: { url: "http://test.com", _id: "123", type: "docker" } };
const dockerResult = await networkService.requestDocker(job);
expect(dockerResult.monitorId).to.equal("123");
@@ -288,7 +288,7 @@ describe("Network Service", function() {
expect(dockerResult.status).to.be.true;
});
- it("should return a response object with status false if container not running", async function() {
+ it("should return a response object with status false if container not running", async function () {
Docker = class {
listContainers = sinon.stub().resolves([
{
@@ -307,7 +307,7 @@ describe("Network Service", function() {
expect(dockerResult.code).to.equal(200);
});
- it("should handle an error when fetching the container", async function() {
+ it("should handle an error when fetching the container", async function () {
Docker = class {
listContainers = sinon.stub().resolves([
{
@@ -326,7 +326,7 @@ describe("Network Service", function() {
expect(dockerResult.code).to.equal(networkService.NETWORK_ERROR);
});
- it("should throw an error if operations fail", async function() {
+ it("should throw an error if operations fail", async function () {
Docker = class {
listContainers = sinon.stub().resolves([
{
@@ -345,7 +345,7 @@ describe("Network Service", function() {
}
});
- it("should throw an error if no matching images found", async function() {
+ it("should throw an error if no matching images found", async function () {
Docker = class {
listContainers = sinon.stub().resolves([]);
getContainer = sinon.stub().throws(new Error("test error"));
@@ -360,8 +360,8 @@ describe("Network Service", function() {
});
});
- describe("getStatus", function() {
- beforeEach(function() {
+ describe("getStatus", function () {
+ beforeEach(function () {
networkService.requestPing = sinon.stub();
networkService.requestHttp = sinon.stub();
networkService.requestPagespeed = sinon.stub();
@@ -369,11 +369,11 @@ describe("Network Service", function() {
networkService.requestDocker = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should call requestPing if type is ping", async function() {
+ it("should call requestPing if type is ping", async function () {
await networkService.getStatus({ data: { type: "ping" } });
expect(networkService.requestPing.calledOnce).to.be.true;
expect(networkService.requestDocker.notCalled).to.be.true;
@@ -381,7 +381,7 @@ describe("Network Service", function() {
expect(networkService.requestPagespeed.notCalled).to.be.true;
});
- it("should call requestHttp if type is http", async function() {
+ it("should call requestHttp if type is http", async function () {
await networkService.getStatus({ data: { type: "http" } });
expect(networkService.requestPing.notCalled).to.be.true;
expect(networkService.requestDocker.notCalled).to.be.true;
@@ -389,7 +389,7 @@ describe("Network Service", function() {
expect(networkService.requestPagespeed.notCalled).to.be.true;
});
- it("should call requestPagespeed if type is pagespeed", async function() {
+ it("should call requestPagespeed if type is pagespeed", async function () {
await networkService.getStatus({ data: { type: "pagespeed" } });
expect(networkService.requestPing.notCalled).to.be.true;
expect(networkService.requestDocker.notCalled).to.be.true;
@@ -397,7 +397,7 @@ describe("Network Service", function() {
expect(networkService.requestPagespeed.calledOnce).to.be.true;
});
- it("should call requestHardware if type is hardware", async function() {
+ it("should call requestHardware if type is hardware", async function () {
await networkService.getStatus({ data: { type: "hardware" } });
expect(networkService.requestHardware.calledOnce).to.be.true;
expect(networkService.requestDocker.notCalled).to.be.true;
@@ -405,7 +405,7 @@ describe("Network Service", function() {
expect(networkService.requestPagespeed.notCalled).to.be.true;
});
- it("should call requestDocker if type is Docker", async function() {
+ it("should call requestDocker if type is Docker", async function () {
await networkService.getStatus({ data: { type: "docker" } });
expect(networkService.requestDocker.calledOnce).to.be.true;
expect(networkService.requestHardware.notCalled).to.be.true;
@@ -413,7 +413,7 @@ describe("Network Service", function() {
expect(networkService.requestPagespeed.notCalled).to.be.true;
});
- it("should throw an error if an unknown type is provided", async function() {
+ it("should throw an error if an unknown type is provided", async function () {
try {
await networkService.getStatus({ data: { type: "unknown" } });
} catch (error) {
@@ -423,7 +423,7 @@ describe("Network Service", function() {
}
});
- it("should throw an error if job type is undefined", async function() {
+ it("should throw an error if job type is undefined", async function () {
try {
await networkService.getStatus({ data: { type: undefined } });
} catch (error) {
@@ -433,7 +433,7 @@ describe("Network Service", function() {
}
});
- it("should throw an error if job is empty", async function() {
+ it("should throw an error if job is empty", async function () {
try {
await networkService.getStatus({});
} catch (error) {
@@ -442,7 +442,7 @@ describe("Network Service", function() {
}
});
- it("should throw an error if job is null", async function() {
+ it("should throw an error if job is null", async function () {
try {
await networkService.getStatus(null);
} catch (error) {
diff --git a/Server/tests/services/notificationService.test.js b/server/tests/services/notificationService.test.js
old mode 100644
new mode 100755
similarity index 87%
rename from Server/tests/services/notificationService.test.js
rename to server/tests/services/notificationService.test.js
index e6220b20c..207b40db0
--- a/Server/tests/services/notificationService.test.js
+++ b/server/tests/services/notificationService.test.js
@@ -2,10 +2,10 @@ import sinon from "sinon";
import NotificationService from "../../service/notificationService.js";
import { expect } from "chai";
-describe("NotificationService", function() {
+describe("NotificationService", function () {
let emailService, db, logger, notificationService;
- beforeEach(function() {
+ beforeEach(function () {
db = {
getNotificationsByMonitorId: sinon.stub(),
};
@@ -19,18 +19,18 @@ describe("NotificationService", function() {
notificationService = new NotificationService(emailService, db, logger);
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- describe("constructor", function() {
- it("should create a new instance of NotificationService", function() {
+ describe("constructor", function () {
+ it("should create a new instance of NotificationService", function () {
expect(notificationService).to.be.an.instanceOf(NotificationService);
});
});
- describe("sendEmail", function() {
- it("should send an email notification with Up Template", async function() {
+ describe("sendEmail", function () {
+ it("should send an email notification with Up Template", async function () {
const networkResponse = {
monitor: {
name: "Test Monitor",
@@ -50,7 +50,7 @@ describe("NotificationService", function() {
);
});
- it("should send an email notification with Down Template", async function() {
+ it("should send an email notification with Down Template", async function () {
const networkResponse = {
monitor: {
name: "Test Monitor",
@@ -64,7 +64,7 @@ describe("NotificationService", function() {
expect(notificationService.emailService.buildAndSendEmail.calledOnce).to.be.true;
});
- it("should send an email notification with Up Template", async function() {
+ it("should send an email notification with Up Template", async function () {
const networkResponse = {
monitor: {
name: "Test Monitor",
@@ -79,8 +79,8 @@ describe("NotificationService", function() {
});
});
- describe("handleNotifications", function() {
- it("should handle notifications based on the network response", async function() {
+ describe("handleNotifications", function () {
+ it("should handle notifications based on the network response", async function () {
notificationService.sendEmail = sinon.stub();
const res = await notificationService.handleNotifications({
monitor: {
@@ -91,7 +91,7 @@ describe("NotificationService", function() {
expect(res).to.be.true;
});
- it("should handle hardware notifications", async function() {
+ it("should handle hardware notifications", async function () {
notificationService.sendEmail = sinon.stub();
const res = await notificationService.handleNotifications({
monitor: {
@@ -102,7 +102,7 @@ describe("NotificationService", function() {
expect(res).to.be.true;
});
- it("should handle an error when getting notifications", async function() {
+ it("should handle an error when getting notifications", async function () {
const testError = new Error("Test Error");
notificationService.db.getNotificationsByMonitorId.rejects(testError);
await notificationService.handleNotifications({ monitorId: "123" });
@@ -110,10 +110,10 @@ describe("NotificationService", function() {
});
});
- describe("sendHardwareEmail", function() {
+ describe("sendHardwareEmail", function () {
let networkResponse, address, alerts;
- beforeEach(function() {
+ beforeEach(function () {
networkResponse = {
monitor: {
name: "Test Monitor",
@@ -126,11 +126,11 @@ describe("NotificationService", function() {
alerts = ["test"];
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should send an email notification with Hardware Template", async function() {
+ it("should send an email notification with Hardware Template", async function () {
emailService.buildAndSendEmail.resolves(true);
const res = await notificationService.sendHardwareEmail(
networkResponse,
@@ -140,7 +140,7 @@ describe("NotificationService", function() {
expect(res).to.be.true;
});
- it("should return false if no alerts are provided", async function() {
+ it("should return false if no alerts are provided", async function () {
alerts = [];
emailService.buildAndSendEmail.resolves(true);
const res = await notificationService.sendHardwareEmail(
@@ -152,10 +152,10 @@ describe("NotificationService", function() {
});
});
- describe("handleStatusNotifications", function() {
+ describe("handleStatusNotifications", function () {
let networkResponse;
- beforeEach(function() {
+ beforeEach(function () {
networkResponse = {
monitor: {
name: "Test Monitor",
@@ -167,11 +167,11 @@ describe("NotificationService", function() {
};
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- it("should handle status notifications", async function() {
+ it("should handle status notifications", async function () {
db.getNotificationsByMonitorId.resolves([
{ type: "email", address: "test@test.com" },
]);
@@ -179,19 +179,19 @@ describe("NotificationService", function() {
expect(res).to.be.true;
});
- it("should return false if status hasn't changed", async function() {
+ it("should return false if status hasn't changed", async function () {
networkResponse.statusChanged = false;
const res = await notificationService.handleStatusNotifications(networkResponse);
expect(res).to.be.false;
});
- it("should return false if prevStatus is undefined", async function() {
+ it("should return false if prevStatus is undefined", async function () {
networkResponse.prevStatus = undefined;
const res = await notificationService.handleStatusNotifications(networkResponse);
expect(res).to.be.false;
});
- it("should handle an error", async function() {
+ it("should handle an error", async function () {
const testError = new Error("Test Error");
db.getNotificationsByMonitorId.rejects(testError);
try {
@@ -203,10 +203,10 @@ describe("NotificationService", function() {
});
});
- describe("handleHardwareNotifications", function() {
+ describe("handleHardwareNotifications", function () {
let networkResponse;
- beforeEach(function() {
+ beforeEach(function () {
networkResponse = {
monitor: {
name: "Test Monitor",
@@ -240,26 +240,26 @@ describe("NotificationService", function() {
};
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- describe("it should return false if no thresholds are set", function() {
- it("should return false if no thresholds are set", async function() {
+ describe("it should return false if no thresholds are set", function () {
+ it("should return false if no thresholds are set", async function () {
networkResponse.monitor.thresholds = undefined;
const res =
await notificationService.handleHardwareNotifications(networkResponse);
expect(res).to.be.false;
});
- it("should return false if metrics are null", async function() {
+ it("should return false if metrics are null", async function () {
networkResponse.payload.data = null;
const res =
await notificationService.handleHardwareNotifications(networkResponse);
expect(res).to.be.false;
});
- it("should return true if request is well formed and thresholds > 0", async function() {
+ it("should return true if request is well formed and thresholds > 0", async function () {
db.getNotificationsByMonitorId.resolves([
{
type: "email",
@@ -276,7 +276,7 @@ describe("NotificationService", function() {
expect(res).to.be.true;
});
- it("should return true if thresholds are exceeded", async function() {
+ it("should return true if thresholds are exceeded", async function () {
db.getNotificationsByMonitorId.resolves([
{
type: "email",
diff --git a/Server/tests/services/settingsService.test.js b/server/tests/services/settingsService.test.js
old mode 100644
new mode 100755
similarity index 91%
rename from Server/tests/services/settingsService.test.js
rename to server/tests/services/settingsService.test.js
index 94f7737bc..3e04ced38
--- a/Server/tests/services/settingsService.test.js
+++ b/server/tests/services/settingsService.test.js
@@ -4,7 +4,7 @@ import { expect } from "chai";
import NetworkService from "../../service/networkService.js";
const SERVICE_NAME = "SettingsService";
-describe("SettingsService", function() {
+describe("SettingsService", function () {
let sandbox, mockAppSettings;
beforeEach(function () {
@@ -37,15 +37,15 @@ describe("SettingsService", function() {
sinon.restore();
});
- describe("constructor", function() {
- it("should construct a new SettingsService", function() {
+ describe("constructor", function () {
+ it("should construct a new SettingsService", function () {
const settingsService = new SettingsService(mockAppSettings);
expect(settingsService.appSettings).to.equal(mockAppSettings);
});
});
- describe("loadSettings", function() {
- it("should load settings from DB when environment variables are not set", async function() {
+ describe("loadSettings", function () {
+ it("should load settings from DB when environment variables are not set", async function () {
const dbSettings = { logLevel: "debug", apiBaseUrl: "http://localhost" };
const appSettings = { findOne: sinon.stub().returns(dbSettings) };
const settingsService = new SettingsService(appSettings);
@@ -68,7 +68,7 @@ describe("SettingsService", function() {
}
});
- it("should add its method and service name to error if not present", async function() {
+ it("should add its method and service name to error if not present", async function () {
const appSettings = { findOne: sinon.stub().throws(new Error("Test error")) };
const settingsService = new SettingsService(appSettings);
try {
@@ -80,7 +80,7 @@ describe("SettingsService", function() {
}
});
- it("should not add its method and service name to error if present", async function() {
+ it("should not add its method and service name to error if present", async function () {
const error = new Error("Test error");
error.method = "otherMethod";
error.service = "OTHER_SERVICE";
@@ -106,8 +106,8 @@ describe("SettingsService", function() {
});
});
- describe("reloadSettings", function() {
- it("should call loadSettings", async function() {
+ describe("reloadSettings", function () {
+ it("should call loadSettings", async function () {
const dbSettings = { logLevel: "debug", apiBaseUrl: "http://localhost" };
const appSettings = { findOne: sinon.stub().returns(dbSettings) };
const settingsService = new SettingsService(appSettings);
@@ -117,8 +117,8 @@ describe("SettingsService", function() {
});
});
- describe("getSettings", function() {
- it("should return the current settings", function() {
+ describe("getSettings", function () {
+ it("should return the current settings", function () {
const dbSettings = { logLevel: "debug", apiBaseUrl: "http://localhost" };
const appSettings = { findOne: sinon.stub().returns(dbSettings) };
const settingsService = new SettingsService(appSettings);
@@ -127,7 +127,7 @@ describe("SettingsService", function() {
expect(result).to.deep.equal(dbSettings);
});
- it("should throw an error if settings have not been loaded", function() {
+ it("should throw an error if settings have not been loaded", function () {
const appSettings = { findOne: sinon.stub().returns(null) };
const settingsService = new SettingsService(appSettings);
settingsService.settings = null;
diff --git a/Server/tests/services/statusService.test.js b/server/tests/services/statusService.test.js
old mode 100644
new mode 100755
similarity index 90%
rename from Server/tests/services/statusService.test.js
rename to server/tests/services/statusService.test.js
index f7473e37e..aa8865024
--- a/Server/tests/services/statusService.test.js
+++ b/server/tests/services/statusService.test.js
@@ -5,7 +5,7 @@ import { afterEach, describe } from "node:test";
describe("StatusService", () => {
let db, logger, statusService;
- beforeEach(function() {
+ beforeEach(function () {
db = {
getMonitorById: sinon.stub(),
createCheck: sinon.stub(),
@@ -23,27 +23,27 @@ describe("StatusService", () => {
});
describe("constructor", () => {
- it("should create an instance of StatusService", function() {
+ it("should create an instance of StatusService", function () {
expect(statusService).to.be.an.instanceOf(StatusService);
});
});
describe("getStatusString", () => {
- it("should return 'up' if status is true", function() {
+ it("should return 'up' if status is true", function () {
expect(statusService.getStatusString(true)).to.equal("up");
});
- it("should return 'down' if status is false", function() {
+ it("should return 'down' if status is false", function () {
expect(statusService.getStatusString(false)).to.equal("down");
});
- it("should return 'unknown' if status is undefined or null", function() {
+ it("should return 'unknown' if status is undefined or null", function () {
expect(statusService.getStatusString(undefined)).to.equal("unknown");
});
});
describe("updateStatus", () => {
- beforeEach(function() {
+ beforeEach(function () {
// statusService.insertCheck = sinon.stub().resolves;
});
@@ -51,7 +51,7 @@ describe("StatusService", () => {
sinon.restore();
});
- it("should throw an error if an error occurs", async function() {
+ it("should throw an error if an error occurs", async function () {
const error = new Error("Test error");
statusService.db.getMonitorById = sinon.stub().throws(error);
try {
@@ -62,7 +62,7 @@ describe("StatusService", () => {
// expect(statusService.insertCheck.calledOnce).to.be.true;
});
- it("should return {statusChanged: false} if status hasn't changed", async function() {
+ it("should return {statusChanged: false} if status hasn't changed", async function () {
statusService.db.getMonitorById = sinon.stub().returns({ status: true });
const result = await statusService.updateStatus({
monitorId: "test",
@@ -72,7 +72,7 @@ describe("StatusService", () => {
// expect(statusService.insertCheck.calledOnce).to.be.true;
});
- it("should return {statusChanged: true} if status has changed from down to up", async function() {
+ it("should return {statusChanged: true} if status has changed from down to up", async function () {
statusService.db.getMonitorById = sinon
.stub()
.returns({ status: false, save: sinon.stub() });
@@ -86,7 +86,7 @@ describe("StatusService", () => {
// expect(statusService.insertCheck.calledOnce).to.be.true;
});
- it("should return {statusChanged: true} if status has changed from up to down", async function() {
+ it("should return {statusChanged: true} if status has changed from up to down", async function () {
statusService.db.getMonitorById = sinon
.stub()
.returns({ status: true, save: sinon.stub() });
@@ -102,7 +102,7 @@ describe("StatusService", () => {
});
describe("buildCheck", () => {
- it("should build a check object", function() {
+ it("should build a check object", function () {
const check = statusService.buildCheck({
monitorId: "test",
type: "test",
@@ -119,7 +119,7 @@ describe("StatusService", () => {
expect(check.message).to.equal("Test message");
});
- it("should build a check object for pagespeed type", function() {
+ it("should build a check object for pagespeed type", function () {
const check = statusService.buildCheck({
monitorId: "test",
type: "pagespeed",
@@ -163,7 +163,7 @@ describe("StatusService", () => {
});
});
- it("should build a check object for pagespeed type with missing data", function() {
+ it("should build a check object for pagespeed type with missing data", function () {
const check = statusService.buildCheck({
monitorId: "test",
type: "pagespeed",
@@ -196,7 +196,7 @@ describe("StatusService", () => {
});
});
- it("should build a check for hardware type", function() {
+ it("should build a check for hardware type", function () {
const check = statusService.buildCheck({
monitorId: "test",
type: "hardware",
@@ -217,7 +217,7 @@ describe("StatusService", () => {
expect(check.host).to.equal("host");
});
- it("should build a check for hardware type with missing data", function() {
+ it("should build a check for hardware type with missing data", function () {
const check = statusService.buildCheck({
monitorId: "test",
type: "hardware",
@@ -240,7 +240,7 @@ describe("StatusService", () => {
});
describe("insertCheck", () => {
- it("should log an error if one is thrown", async function() {
+ it("should log an error if one is thrown", async function () {
const testError = new Error("Test error");
statusService.db.createCheck = sinon.stub().throws(testError);
try {
@@ -251,7 +251,7 @@ describe("StatusService", () => {
expect(statusService.logger.error.calledOnce).to.be.true;
});
- it("should insert a check into the database", async function() {
+ it("should insert a check into the database", async function () {
await statusService.insertCheck({ monitorId: "test", type: "http" });
expect(statusService.db.createCheck.calledOnce).to.be.true;
});
diff --git a/Server/tests/utils/dataUtils.test.js b/server/tests/utils/dataUtils.test.js
old mode 100644
new mode 100755
similarity index 90%
rename from Server/tests/utils/dataUtils.test.js
rename to server/tests/utils/dataUtils.test.js
index 0b73a5f95..e39af5a75
--- a/Server/tests/utils/dataUtils.test.js
+++ b/server/tests/utils/dataUtils.test.js
@@ -1,8 +1,8 @@
import { NormalizeData, calculatePercentile } from "../../utils/dataUtils.js";
import sinon from "sinon";
-describe("NormalizeData", function() {
- it("should normalize response times when checks length is greater than 1", function() {
+describe("NormalizeData", function () {
+ it("should normalize response times when checks length is greater than 1", function () {
const checks = [
{ responseTime: 20, _doc: { id: 1 } },
{ responseTime: 40, _doc: { id: 2 } },
@@ -21,7 +21,7 @@ describe("NormalizeData", function() {
});
});
- it("should return checks with original response times when checks length is 1", function() {
+ it("should return checks with original response times when checks length is 1", function () {
const checks = [{ responseTime: 20, _doc: { id: 1 } }];
const rangeMin = 1;
const rangeMax = 100;
@@ -32,7 +32,7 @@ describe("NormalizeData", function() {
expect(result[0]).to.have.property("originalResponseTime", 20);
});
- it("should handle edge cases with extreme response times", function() {
+ it("should handle edge cases with extreme response times", function () {
const checks = [
{ responseTime: 5, _doc: { id: 1 } },
{ responseTime: 95, _doc: { id: 2 } },
@@ -49,8 +49,8 @@ describe("NormalizeData", function() {
});
});
-describe("calculatePercentile", function() {
- it("should return the lower value when upper is greater than or equal to the length of the sorted array", function() {
+describe("calculatePercentile", function () {
+ it("should return the lower value when upper is greater than or equal to the length of the sorted array", function () {
const checks = [
{ responseTime: 10 },
{ responseTime: 20 },
diff --git a/Server/tests/utils/imageProcessing.test.js b/server/tests/utils/imageProcessing.test.js
old mode 100644
new mode 100755
similarity index 91%
rename from Server/tests/utils/imageProcessing.test.js
rename to server/tests/utils/imageProcessing.test.js
index 7a779c93d..29e47af6a
--- a/Server/tests/utils/imageProcessing.test.js
+++ b/server/tests/utils/imageProcessing.test.js
@@ -3,8 +3,8 @@ import sinon from "sinon";
import sharp from "sharp";
import { GenerateAvatarImage } from "../../utils/imageProcessing.js";
-describe("imageProcessing - GenerateAvatarImage", function() {
- it("should resize the image to 64x64 and return a base64 string", async function() {
+describe("imageProcessing - GenerateAvatarImage", function () {
+ it("should resize the image to 64x64 and return a base64 string", async function () {
const file = {
buffer: Buffer.from("test image buffer"),
};
@@ -30,7 +30,7 @@ describe("imageProcessing - GenerateAvatarImage", function() {
sharpStub.restore();
});
- it("should throw an error if resizing fails", async function() {
+ it("should throw an error if resizing fails", async function () {
const file = {
buffer: Buffer.from("test image buffer"),
};
diff --git a/Server/tests/utils/logger.test.js b/server/tests/utils/logger.test.js
old mode 100644
new mode 100755
similarity index 89%
rename from Server/tests/utils/logger.test.js
rename to server/tests/utils/logger.test.js
index 8030ff8fb..2d5bd82a9
--- a/Server/tests/utils/logger.test.js
+++ b/server/tests/utils/logger.test.js
@@ -3,20 +3,20 @@ import logger from "../../utils/logger.js";
import { Logger } from "../../utils/logger.js";
import winston from "winston";
-describe("Logger", function() {
+describe("Logger", function () {
let infoStub, warnStub, errorStub;
- beforeEach(function() {
+ beforeEach(function () {
infoStub = sinon.stub(logger.logger, "info");
warnStub = sinon.stub(logger.logger, "warn");
errorStub = sinon.stub(logger.logger, "error");
});
- afterEach(function() {
+ afterEach(function () {
sinon.restore();
});
- describe("constructor", function() {
+ describe("constructor", function () {
let createLoggerStub;
beforeEach(function () {
@@ -69,8 +69,8 @@ describe("Logger", function() {
});
});
- describe("info", function() {
- it("should log an informational message", function() {
+ describe("info", function () {
+ it("should log an informational message", function () {
const config = {
message: "Info message",
service: "TestService",
@@ -91,8 +91,8 @@ describe("Logger", function() {
});
});
- describe("warn", function() {
- it("should log a warning message", function() {
+ describe("warn", function () {
+ it("should log a warning message", function () {
const config = {
message: "Warning message",
service: "TestService",
@@ -113,8 +113,8 @@ describe("Logger", function() {
});
});
- describe("error", function() {
- it("should log an error message", function() {
+ describe("error", function () {
+ it("should log an error message", function () {
const config = {
message: "Error message",
service: "TestService",
diff --git a/Server/tests/utils/messages.test.js b/server/tests/utils/messages.test.js
old mode 100644
new mode 100755
similarity index 64%
rename from Server/tests/utils/messages.test.js
rename to server/tests/utils/messages.test.js
index 7ece332c4..719af1be0
--- a/Server/tests/utils/messages.test.js
+++ b/server/tests/utils/messages.test.js
@@ -1,14 +1,14 @@
import { errorMessages, successMessages } from "../../utils/messages.js";
-describe("Messages", function() {
- describe("messages - errorMessages", function() {
- it("should have a DB_FIND_MONITOR_BY_ID function", function() {
+describe("Messages", function () {
+ describe("messages - errorMessages", function () {
+ it("should have a DB_FIND_MONITOR_BY_ID function", function () {
const monitorId = "12345";
expect(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId)).to.equal(
`Monitor with id ${monitorId} not found`
);
});
- it("should have a DB_DELETE_CHECKS function", function() {
+ it("should have a DB_DELETE_CHECKS function", function () {
const monitorId = "12345";
expect(errorMessages.DB_DELETE_CHECKS(monitorId)).to.equal(
`No checks found for monitor with id ${monitorId}`
@@ -16,8 +16,8 @@ describe("Messages", function() {
});
});
- describe("messages - successMessages", function() {
- it("should have a MONITOR_GET_BY_USER_ID function", function() {
+ describe("messages - successMessages", function () {
+ it("should have a MONITOR_GET_BY_USER_ID function", function () {
const userId = "12345";
expect(successMessages.MONITOR_GET_BY_USER_ID(userId)).to.equal(
`Got monitor for ${userId} successfully"`
diff --git a/Server/tests/utils/utils.test.js b/server/tests/utils/utils.test.js
old mode 100644
new mode 100755
similarity index 77%
rename from Server/tests/utils/utils.test.js
rename to server/tests/utils/utils.test.js
index f697c9b4a..2630bb8e6
--- a/Server/tests/utils/utils.test.js
+++ b/server/tests/utils/utils.test.js
@@ -1,49 +1,49 @@
import { ParseBoolean, getTokenFromHeaders } from "../../utils/utils.js";
-describe("utils - ParseBoolean", function() {
- it("should return true", function() {
+describe("utils - ParseBoolean", function () {
+ it("should return true", function () {
const result = ParseBoolean("true");
expect(result).to.be.true;
});
- it("should return false", function() {
+ it("should return false", function () {
const result = ParseBoolean("false");
expect(result).to.be.false;
});
- it("should return false", function() {
+ it("should return false", function () {
const result = ParseBoolean(null);
expect(result).to.be.false;
});
- it("should return false", function() {
+ it("should return false", function () {
const result = ParseBoolean(undefined);
expect(result).to.be.false;
});
});
-describe("utils - getTokenFromHeaders", function() {
- it("should throw an error if authorization header is missing", function() {
+describe("utils - getTokenFromHeaders", function () {
+ it("should throw an error if authorization header is missing", function () {
const headers = {};
expect(() => getTokenFromHeaders(headers)).to.throw("No auth headers");
});
- it("should throw an error if authorization header does not start with Bearer", function() {
+ it("should throw an error if authorization header does not start with Bearer", function () {
const headers = { authorization: "Basic abcdef" };
expect(() => getTokenFromHeaders(headers)).to.throw("Invalid auth headers");
});
- it("should return the token if authorization header is correctly formatted", function() {
+ it("should return the token if authorization header is correctly formatted", function () {
const headers = { authorization: "Bearer abcdef" };
expect(getTokenFromHeaders(headers)).to.equal("abcdef");
});
- it("should throw an error if authorization header has more than two parts", function() {
+ it("should throw an error if authorization header has more than two parts", function () {
const headers = { authorization: "Bearer abc def" };
expect(() => getTokenFromHeaders(headers)).to.throw("Invalid auth headers");
});
- it("should throw an error if authorization header has less than two parts", function() {
+ it("should throw an error if authorization header has less than two parts", function () {
const headers = { authorization: "Bearer" };
expect(() => getTokenFromHeaders(headers)).to.throw("Invalid auth headers");
});
diff --git a/Server/utils/dataUtils.js b/server/utils/dataUtils.js
old mode 100644
new mode 100755
similarity index 86%
rename from Server/utils/dataUtils.js
rename to server/utils/dataUtils.js
index ca6ca66df..d164b92fd
--- a/Server/utils/dataUtils.js
+++ b/server/utils/dataUtils.js
@@ -84,7 +84,31 @@ const NormalizeDataUptimeDetails = (checks, rangeMin, rangeMax) => {
}
};
+const safelyParseFloat = (value, defaultValue = 0) => {
+ if (value === null || typeof value === "undefined") {
+ return defaultValue;
+ }
+ const stringValue = String(value).trim();
+
+ if (typeof value === "number" && !isNaN(value)) {
+ return value;
+ }
+
+ if (stringValue === "") {
+ return defaultValue;
+ }
+
+ const parsedValue = parseFloat(stringValue);
+
+ if (isNaN(parsedValue) || !isFinite(parsedValue)) {
+ return defaultValue;
+ }
+
+ return parsedValue;
+};
+
export {
+ safelyParseFloat,
calculatePercentile,
NormalizeData,
calculatePercentileUptimeDetails,
diff --git a/Server/utils/demoMonitors.json b/server/utils/demoMonitors.json
old mode 100644
new mode 100755
similarity index 100%
rename from Server/utils/demoMonitors.json
rename to server/utils/demoMonitors.json
diff --git a/Server/utils/demoMonitorsOld.json b/server/utils/demoMonitorsOld.json
old mode 100644
new mode 100755
similarity index 100%
rename from Server/utils/demoMonitorsOld.json
rename to server/utils/demoMonitorsOld.json
diff --git a/Server/utils/imageProcessing.js b/server/utils/imageProcessing.js
old mode 100644
new mode 100755
similarity index 100%
rename from Server/utils/imageProcessing.js
rename to server/utils/imageProcessing.js
diff --git a/Server/utils/logger.js b/server/utils/logger.js
old mode 100644
new mode 100755
similarity index 66%
rename from Server/utils/logger.js
rename to server/utils/logger.js
index e263085a7..155adc957
--- a/Server/utils/logger.js
+++ b/server/utils/logger.js
@@ -1,9 +1,11 @@
import { createLogger, format, transports } from "winston";
+import dotenv from "dotenv";
+dotenv.config();
class Logger {
constructor() {
const consoleFormat = format.printf(
- ({ level, message, service, method, details, timestamp }) => {
+ ({ level, message, service, method, details, timestamp, stack }) => {
if (message instanceof Object) {
message = JSON.stringify(message, null, 2);
}
@@ -16,12 +18,34 @@ class Logger {
method && (msg += `(${method})`);
message && (msg += ` ${message}`);
details && (msg += ` (details: ${details})`);
+
+ if (typeof stack !== "undefined") {
+ const stackTrace = stack
+ ?.split("\n")
+ .slice(1) // Remove first line (error message)
+ .map((line) => {
+ const match = line.match(/at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)/);
+ if (match) {
+ return {
+ function: match[1],
+ file: match[2],
+ line: parseInt(match[3]),
+ column: parseInt(match[4]),
+ };
+ }
+ return line.trim();
+ });
+ stack && (msg += ` (stack: ${JSON.stringify(stackTrace, null, 2)})`);
+ }
+
return msg;
}
);
+ const logLevel = process.env.LOG_LEVEL || "info";
+
this.logger = createLogger({
- level: "info",
+ level: logLevel,
format: format.combine(format.timestamp()),
transports: [
new transports.Console({
@@ -87,6 +111,22 @@ class Logger {
stack: config.stack,
});
}
+ /**
+ * Logs a debug message.
+ * @param {Object} config - The configuration object.
+ * @param {string} config.message - The message to log.
+ * @param {string} config.service - The service name.
+ * @param {string} config.method - The method name.
+ * @param {Object} config.details - Additional details.
+ */
+ debug(config) {
+ this.logger.debug(config.message, {
+ service: config.service,
+ method: config.method,
+ details: config.details,
+ stack: config.stack,
+ });
+ }
}
const logger = new Logger();
diff --git a/Server/utils/utils.js b/server/utils/utils.js
old mode 100644
new mode 100755
similarity index 80%
rename from Server/utils/utils.js
rename to server/utils/utils.js
index 5bd9258f9..57d181886
--- a/Server/utils/utils.js
+++ b/server/utils/utils.js
@@ -27,9 +27,4 @@ const getTokenFromHeaders = (headers) => {
return parts[1];
};
-const tokenType = Object.freeze({
- ACCESS_TOKEN: "Access token",
- REFRESH_TOKEN: "Refresh token",
-});
-
-export { ParseBoolean, getTokenFromHeaders, tokenType };
+export { ParseBoolean, getTokenFromHeaders };
diff --git a/Server/validation/joi.js b/server/validation/joi.js
old mode 100644
new mode 100755
similarity index 68%
rename from Server/validation/joi.js
rename to server/validation/joi.js
index 8f366a113..997d35d65
--- a/Server/validation/joi.js
+++ b/server/validation/joi.js
@@ -35,16 +35,21 @@ const loginValidation = joi.object({
}),
password: joi.string().min(8).required().pattern(passwordPattern),
});
+const nameValidation = joi
+ .string()
+ .trim()
+ .max(50)
+ .pattern(/^(?=.*[\p{L}\p{Sc}])[\p{L}\p{Sc}\s']+$/u)
+ .messages({
+ "string.empty": "Name is required",
+ "string.max": "Name must be less than 50 characters",
+ "string.pattern.base":
+ "Name must contain at least 1 letter or currency symbol and only allow letters, spaces, apostrophes, and currency symbols",
+ });
const registrationBodyValidation = joi.object({
- firstName: joi
- .string()
- .required()
- .pattern(/^[A-Za-z]+$/),
- lastName: joi
- .string()
- .required()
- .pattern(/^[A-Za-z]+$/),
+ firstName: nameValidation.required(),
+ lastName: nameValidation.required(),
email: joi
.string()
.email()
@@ -58,11 +63,7 @@ const registrationBodyValidation = joi.object({
}),
password: joi.string().min(8).required().pattern(passwordPattern),
profileImage: joi.any(),
- role: joi
- .array()
- .items(joi.string().valid("superadmin", "admin", "user", "demo"))
- .min(1)
- .required(),
+ role: joi.array().items(joi.string().valid("superadmin", "admin", "user", "demo")),
teamId: joi.string().allow("").required(),
inviteToken: joi.string().allow("").required(),
});
@@ -72,13 +73,12 @@ const editUserParamValidation = joi.object({
});
const editUserBodyValidation = joi.object({
- firstName: joi.string().pattern(/^[A-Za-z]+$/),
- lastName: joi.string().pattern(/^[A-Za-z]+$/),
+ firstName: nameValidation.required(),
+ lastName: nameValidation.required(),
profileImage: joi.any(),
newPassword: joi.string().min(8).pattern(passwordPattern),
password: joi.string().min(8).pattern(passwordPattern),
deleteProfileImage: joi.boolean(),
- role: joi.array(),
});
const recoveryValidation = joi.object({
@@ -183,6 +183,7 @@ const createMonitorBodyValidation = joi.object({
description: joi.string().required(),
type: joi.string().required(),
url: joi.string().required(),
+ ignoreTlsErrors: joi.boolean().default(false),
port: joi.number(),
isActive: joi.boolean(),
interval: joi.number(),
@@ -194,14 +195,30 @@ const createMonitorBodyValidation = joi.object({
}),
notifications: joi.array().items(joi.object()),
secret: joi.string(),
+ jsonPath: joi.string().allow(""),
+ expectedValue: joi.string().allow(""),
+ matchMethod: joi.string(),
});
+const createMonitorsBodyValidation = joi.array().items(createMonitorBodyValidation);
+
const editMonitorBodyValidation = joi.object({
name: joi.string(),
description: joi.string(),
interval: joi.number(),
notifications: joi.array().items(joi.object()),
secret: joi.string(),
+ ignoreTlsErrors: joi.boolean(),
+ jsonPath: joi.string().allow(""),
+ expectedValue: joi.string().allow(""),
+ matchMethod: joi.string(),
+ port: joi.number().min(1).max(65535),
+ thresholds: joi.object().keys({
+ usage_cpu: joi.number(),
+ usage_memory: joi.number(),
+ usage_disk: joi.number(),
+ usage_temperature: joi.number(),
+ }),
});
const pauseMonitorParamValidation = joi.object({
@@ -217,7 +234,7 @@ const getHardwareDetailsByIdParamValidation = joi.object({
});
const getHardwareDetailsByIdQueryValidation = joi.object({
- dateRange: joi.string().valid("hour", "day", "week", "month", "all"),
+ dateRange: joi.string().valid("recent", "hour", "day", "week", "month", "all"),
});
//****************************************
@@ -286,12 +303,25 @@ const getChecksParamValidation = joi.object({
});
const getChecksQueryValidation = joi.object({
+ type: joi
+ .string()
+ .valid(
+ "http",
+ "ping",
+ "pagespeed",
+ "hardware",
+ "docker",
+ "port",
+ "distributed_http",
+ "distributed_test"
+ ),
sortOrder: joi.string().valid("asc", "desc"),
limit: joi.number(),
- dateRange: joi.string().valid("hour", "day", "week", "month", "all"),
+ dateRange: joi.string().valid("recent", "hour", "day", "week", "month", "all"),
filter: joi.string().valid("all", "down", "resolve"),
page: joi.number(),
rowsPerPage: joi.number(),
+ status: joi.boolean(),
});
const getTeamChecksParamValidation = joi.object({
@@ -305,6 +335,7 @@ const getTeamChecksQueryValidation = joi.object({
filter: joi.string().valid("all", "down", "resolve"),
page: joi.number(),
rowsPerPage: joi.number(),
+ status: joi.boolean(),
});
const deleteChecksParamValidation = joi.object({
@@ -393,19 +424,14 @@ const editMaintenanceByIdWindowBodyValidation = joi.object({
// SettingsValidation
//****************************************
const updateAppSettingsBodyValidation = joi.object({
- apiBaseUrl: joi.string().allow(""),
- logLevel: joi.string().valid("debug", "none", "error", "warn").allow(""),
- clientHost: joi.string().allow(""),
- dbType: joi.string().allow(""),
- dbConnectionString: joi.string().allow(""),
- redisHost: joi.string().allow(""),
- redisPort: joi.number().allow(null, ""),
- jwtTTL: joi.string().allow(""),
+ checkTTL: joi.number().allow(""),
pagespeedApiKey: joi.string().allow(""),
+ language: joi.string().allow(""),
systemEmailHost: joi.string().allow(""),
systemEmailPort: joi.number().allow(""),
systemEmailAddress: joi.string().allow(""),
systemEmailPassword: joi.string().allow(""),
+ systemEmailUser: joi.string().allow(""),
});
//****************************************
@@ -416,12 +442,26 @@ const getStatusPageParamValidation = joi.object({
url: joi.string().required(),
});
+const getStatusPageQueryValidation = joi.object({
+ type: joi.string().valid("uptime", "distributed").required(),
+ timeFrame: joi.number().optional(),
+});
+
const createStatusPageBodyValidation = joi.object({
+ userId: joi.string().required(),
+ teamId: joi.string().required(),
+ type: joi.string().valid("uptime", "distributed").required(),
companyName: joi.string().required(),
- url: joi.string().required(),
- timezone: joi.string().required(),
- color: joi.string().required(),
- theme: joi.string().required(),
+ url: joi
+ .string()
+ .pattern(/^[a-zA-Z0-9_-]+$/) // Only allow alphanumeric, underscore, and hyphen
+ .required()
+ .messages({
+ "string.pattern.base":
+ "URL can only contain letters, numbers, underscores, and hyphens",
+ }),
+ timezone: joi.string().optional(),
+ color: joi.string().optional(),
monitors: joi
.array()
.items(joi.string().pattern(/^[0-9a-fA-F]{24}$/))
@@ -432,6 +472,122 @@ const createStatusPageBodyValidation = joi.object({
"array.empty": "At least one monitor is required",
"any.required": "Monitors are required",
}),
+ subMonitors: joi
+ .array()
+ .items(joi.string().pattern(/^[0-9a-fA-F]{24}$/))
+ .optional(),
+ deleteSubmonitors: joi.boolean().optional(),
+ isPublished: joi.boolean(),
+ showCharts: joi.boolean().optional(),
+ showUptimePercentage: joi.boolean(),
+});
+
+const imageValidation = joi
+ .object({
+ fieldname: joi.string().required(),
+ originalname: joi.string().required(),
+ encoding: joi.string().required(),
+ mimetype: joi
+ .string()
+ .valid("image/jpeg", "image/png", "image/jpg")
+ .required()
+ .messages({
+ "string.valid": "File must be a valid image (jpeg, jpg, or png)",
+ }),
+ size: joi.number().max(3145728).required().messages({
+ "number.max": "File size must be less than 3MB",
+ }),
+ buffer: joi.binary().required(),
+ destination: joi.string(),
+ filename: joi.string(),
+ path: joi.string(),
+ })
+ .messages({
+ "any.required": "Image file is required",
+ });
+
+const webhookConfigValidation = joi
+ .object({
+ webhookUrl: joi
+ .string()
+ .uri()
+ .when("$platform", {
+ switch: [
+ {
+ is: "telegram",
+ then: joi.optional(),
+ },
+ {
+ is: "discord",
+ then: joi.required().messages({
+ "string.empty": "Discord webhook URL is required",
+ "string.uri": "Discord webhook URL must be a valid URL",
+ "any.required": "Discord webhook URL is required",
+ }),
+ },
+ {
+ is: "slack",
+ then: joi.required().messages({
+ "string.empty": "Slack webhook URL is required",
+ "string.uri": "Slack webhook URL must be a valid URL",
+ "any.required": "Slack webhook URL is required",
+ }),
+ },
+ ],
+ }),
+ botToken: joi.string().when("$platform", {
+ is: "telegram",
+ then: joi.required().messages({
+ "string.empty": "Telegram bot token is required",
+ "any.required": "Telegram bot token is required",
+ }),
+ otherwise: joi.optional(),
+ }),
+ chatId: joi.string().when("$platform", {
+ is: "telegram",
+ then: joi.required().messages({
+ "string.empty": "Telegram chat ID is required",
+ "any.required": "Telegram chat ID is required",
+ }),
+ otherwise: joi.optional(),
+ }),
+ })
+ .required();
+
+const triggerNotificationBodyValidation = joi.object({
+ monitorId: joi.string().required().messages({
+ "string.empty": "Monitor ID is required",
+ "any.required": "Monitor ID is required",
+ }),
+ type: joi.string().valid("webhook").required().messages({
+ "string.empty": "Notification type is required",
+ "any.required": "Notification type is required",
+ "any.only": "Notification type must be webhook",
+ }),
+ platform: joi.string().valid("telegram", "discord", "slack").required().messages({
+ "string.empty": "Platform type is required",
+ "any.required": "Platform type is required",
+ "any.only": "Platform must be telegram, discord, or slack",
+ }),
+ config: webhookConfigValidation.required().messages({
+ "any.required": "Webhook configuration is required",
+ }),
+});
+
+//****************************************
+// Announcetment Page Validation
+//****************************************
+
+const createAnnouncementValidation = joi.object({
+ title: joi.string().required().messages({
+ "string.empty": "Title cannot be empty",
+ "any.required": "Title is required",
+ }),
+ message: joi.string().required().messages({
+ "string.empty": "Message cannot be empty",
+ "any.required": "Message is required",
+ }),
+ userId: joi.string().required(),
});
export {
@@ -445,6 +601,7 @@ export {
inviteBodyValidation,
inviteVerificationBodyValidation,
createMonitorBodyValidation,
+ createMonitorsBodyValidation,
getMonitorByIdParamValidation,
getMonitorByIdQueryValidation,
getMonitorsByTeamIdParamValidation,
@@ -491,4 +648,9 @@ export {
updateAppSettingsBodyValidation,
createStatusPageBodyValidation,
getStatusPageParamValidation,
+ getStatusPageQueryValidation,
+ imageValidation,
+ triggerNotificationBodyValidation,
+ webhookConfigValidation,
+ createAnnouncementValidation,
};
diff --git a/uptime.sh b/uptime.sh
deleted file mode 100755
index 956d5e33c..000000000
--- a/uptime.sh
+++ /dev/null
@@ -1,117 +0,0 @@
-default_server_base_url="http://localhost:5000/api/v1"
-default_client_host="http://localhost:5173"
-default_jwt_secret="my_secret"
-default_db_type="MongoDB"
-default_db_connection_string="mongodb://mongodb:27017/uptime_db"
-default_redis_host="redis"
-default_redis_port=6379
-default_token_ttl="99d"
-
-default_system_email_host="smtp.gmail.com"
-default_system_email_port=465
-
-echo "Welcome to the Uptime Monitor Setup Script! \n"
-echo
-
-echo "Configuring client"
-printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' '*'
-echo
-
-read -p "Enter the API Base URL (press enter for default) [$default_server_base_url]: " input_url
-input_url="${input_url:-$default_server_base_url}"
-
-
-echo "API base url: $input_url"
-echo
-
-echo "Writing to ./Docker/client.env"
-echo
-
-echo "VITE_APP_API_BASE_URL=\"$input_url\"" > ./Client/.env
-
-echo "Configuring server"
-printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' '*'
-echo
-
-read -p "Enter the Client Host [$default_client_host]: " client_host
-client_host="${client_host:-$default_client_host}"
-echo "Client Host: $client_host"
-echo
-
-read -p "Enter your JWT secret [$default_jwt_secret]: " jwt_secret
-jwt_secret="${jwt_secret:-$default_jwt_secret}"
-echo "JWT Secret: $jwt_secret"
-echo
-
-read -p "Enter your DB type [$default_db_type]: " db_type
-db_type="${db_type:-$default_db_type}"
-echo "DB Type: $db_type"
-echo
-
-read -p "Enter your DB connection string [$default_db_connection_string]: " db_connection_string
-db_connection_string="${db_connection_string:-$default_db_connection_string}"
-echo "DB connection string: $db_connection_string"
-echo
-
-read -p "Enter your Redis Host [$default_redis_host]: " redis_host
-redis_host="${redis_host:-$default_redis_host}"
-echo "Redis Host: $redis_host"
-echo
-
-read -p "Enter your Redis Port [$default_redis_port]: " redis_port
-redis_port="${redis_port:-$default_redis_port}"
-echo "Redis Port: $redis_port"
-echo
-
-read -p "Enter your system email host [$default_system_email_host]: " system_email_host
-system_email_host="${system_email_host:-$default_system_email_host}"
-echo "System email host: $system_email_host"
-echo
-
-read -p "Enter your system email port [$default_system_email_port]: " system_email_port
-system_email_port="${system_email_port:-$default_system_email_port}"
-echo "System email port: $system_email_port"
-echo
-
-read -p "Enter your system email address: " system_email_address
-echo "System email address: $system_email_address"
-echo
-
-read -p "Enter your system email password: " system_email_password
-echo "System email password: $system_email_password"
-echo
-
-
-
-read -p "Enter your Token TTL [$default_token_ttl]: " token_ttl
-token_ttl="${token_ttl:-$default_token_ttl}"
-echo "Token TTL: $token_ttl"
-echo
-
-read -p "Enter your Pagespeed API key: " pagespeed_api_key
-echo "Pagespeed API key: $pagespeed_api_key"
-echo
-
-echo "Writing to ./Docker/server.env"
-echo
-
-{
- echo "CLIENT_HOST=\"$client_host\""
- echo "JWT_SECRET=\"$jwt_secret\""
- echo "DB_TYPE=\"$db_type\""
- echo "DB_CONNECTION_STRING=\"$db_connection_string\""
- echo "REDIS_HOST=\"$redis_host\""
- echo "REDIS_PORT=$redis_port"
- echo "SYSTEM_EMAIL_HOST=\"$system_email_host\""
- echo "SYSTEM_EMAIL_PORT=$system_email_port"
- echo "SYSTEM_EMAIL_ADDRESS=\"$system_email_address\""
- echo "SYSTEM_EMAIL_PASSWORD=\"$system_email_password\""
- echo "TOKEN_TTL=\"$token_ttl\""
- echo "PAGESPEED_API_KEY=\"$pagespeed_api_key\""
-} > ./Docker/server.env
-
-cd ./Docker
-source ./build_images.sh
-
-cd ./Docker
-docker-compose up
\ No newline at end of file
| |