Compare commits

..
Author SHA1 Message Date
ajnart 525eda3cbb style: auto-fix lint and format 2026-07-04 08:46:48 +00:00
Thomas Camlong d0709a684c fix: namespace request-handler cache per handler and stop persist retries in demo mode
The in-memory request handler cache introduced in #6075 keyed entries by
JSON.stringify(input) in a Map shared across all handlers. Any two handlers
querying the same integration with equal options (e.g. {}) collided and read
each other's data — with the mock integration serving every widget kind, all
demo widgets received whichever handler's data was cached first (beszel
getting health-monitoring payloads, etc.). Cache keys are now namespaced per
handler definition.

Also disable the query-cache persister after the first FORBIDDEN response so
demo mode doesn't retry a mutation that is always rejected.
2026-07-04 10:41:36 +02:00
Thomas Camlong cf075040e8 fix: use SuperJSON for cache persistence and add null guards to all widgets
SuperJSON preserves Date/Map/Set types through the Redis cache round-trip,
fixing RangeError crashes from date formatting. Added defensive null/undefined
guards across all widget components to handle useQuery loading states and
potential cache shape mismatches.
2026-07-04 10:19:16 +02:00
103 changed files with 1340 additions and 16675 deletions

No files matched your search

+1 -8
View File
@@ -59,11 +59,4 @@ TURBO_TELEMETRY_DISABLED=1
# ENABLE_KUBERNETES=true # ENABLE_KUBERNETES=true
# Enable mock integration # Enable mock integration
UNSAFE_ENABLE_MOCK_INTEGRATION=true UNSAFE_ENABLE_MOCK_INTEGRATION=true
# Enable demo mode (seeds a demo user "demo"/"demo", a sample board and a mock integration)
# DEMO_MODE=true
# Whether demo mode is read-only. Defaults to true (the public demo blocks all mutations).
# Set to false for writable preview deployments so the demo user can modify the dashboard.
# DEMO_READ_ONLY=false
-1
View File
@@ -33,7 +33,6 @@ body:
options: options:
# The below comment is used to insert a new version with on-release.yml # The below comment is used to insert a new version with on-release.yml
#NEXT_VERSION# #NEXT_VERSION#
- 1.69.2
- 1.69.0 - 1.69.0
- 1.68.0 - 1.68.0
- 1.67.0 - 1.67.0
+1 -1
View File
@@ -11,7 +11,7 @@ outputs:
runs: runs:
using: "composite" using: "composite"
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v6
with: with:
persist-credentials: false persist-credentials: false
- name: Set up Docker Buildx - name: Set up Docker Buildx
+1 -1
View File
@@ -17,7 +17,7 @@ jobs:
if: github.actor_id == 158783068 || github.actor_id == 190541745 || github.actor_id == 210161987 || github.actor_id == 175486441 if: github.actor_id == 158783068 || github.actor_id == 190541745 || github.actor_id == 210161987 || github.actor_id == 175486441
steps: steps:
- name: Checkout code - name: Checkout code
uses: actions/checkout@v7 uses: actions/checkout@v6
- name: Obtain token - name: Obtain token
id: obtainToken id: obtainToken
uses: actions/create-github-app-token@v3 uses: actions/create-github-app-token@v3
+70 -8
View File
@@ -25,13 +25,13 @@ env:
jobs: jobs:
lint-format-autofix: lint-format-autofix:
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.id == github.repository_id if: github.event_name == 'pull_request'
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 5 timeout-minutes: 5
permissions: permissions:
contents: write contents: write
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v6
with: with:
fetch-depth: 0 fetch-depth: 0
ref: ${{ github.head_ref }} ref: ${{ github.head_ref }}
@@ -60,7 +60,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 10 timeout-minutes: 10
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v6
with: with:
fetch-depth: 0 fetch-depth: 0
@@ -78,7 +78,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 10 timeout-minutes: 10
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v6
with: with:
fetch-depth: 0 fetch-depth: 0
@@ -92,7 +92,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 10 timeout-minutes: 10
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v6
with: with:
fetch-depth: 0 fetch-depth: 0
@@ -106,7 +106,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 10 timeout-minutes: 10
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v6
- name: Setup - name: Setup
uses: ./tooling/github/setup uses: ./tooling/github/setup
@@ -124,7 +124,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 15 timeout-minutes: 15
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v6
- name: Setup - name: Setup
uses: ./tooling/github/setup uses: ./tooling/github/setup
- name: Set up Docker Buildx - name: Set up Docker Buildx
@@ -153,7 +153,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 10 timeout-minutes: 10
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v6
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Setup - name: Setup
@@ -163,3 +163,65 @@ jobs:
run: cp .env.example .env run: cp .env.example .env
- name: Build - name: Build
run: pnpm turbo build --affected run: pnpm turbo build --affected
memory-regression:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v6
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Build Docker image
uses: docker/build-push-action@v7
with:
platforms: linux/amd64
context: .
push: false
load: true
tags: homarr-memory-test
network: host
cache-from: type=gha
cache-to: type=gha,mode=max
env:
SKIP_ENV_VALIDATION: true
- name: Start container and measure memory
run: |
docker run -d --name homarr-mem-test -p 17575:7575 homarr-memory-test
# Wait for container to be healthy (up to 60s)
healthy=false
for i in $(seq 1 30); do
if curl -sf http://localhost:17575/api/health 2>/dev/null; then
echo "Container healthy after $((i * 2))s"
healthy=true
break
fi
sleep 2
done
if [ "$healthy" != "true" ]; then
echo "ERROR: Container never became healthy"
docker logs homarr-mem-test --tail 50
exit 1
fi
# Warm up: hit the dashboard page a few times
for i in $(seq 1 5); do
curl -sf http://localhost:17575/ > /dev/null 2>&1 || true
sleep 2
done
# Measure RSS after warmup
MEM_KB=$(docker stats --no-stream --format '{{.MemUsage}}' homarr-mem-test | sed 's| /.*||')
echo "Raw memory: $MEM_KB"
# Convert to numeric MB (handles GiB and MiB suffixes)
MEM_NUM=$(echo "$MEM_KB" | awk '{
if ($0 ~ /GiB/) { gsub(/GiB/,""); print $1 * 1024 }
else if ($0 ~ /MiB/) { gsub(/MiB/,""); print $1 }
else if ($0 ~ /KiB/) { gsub(/KiB/,""); print $1 / 1024 }
else { print $1 / 1048576 }
}')
echo "Memory usage: ${MEM_NUM} MB"
MAX_MB=700
if awk "BEGIN {exit !($MEM_NUM > $MAX_MB)}"; then
echo "ERROR: Memory usage ${MEM_NUM} MB exceeds ${MAX_MB} MB threshold"
docker logs homarr-mem-test --tail 50
exit 1
fi
echo "Memory check passed: ${MEM_NUM} MB <= ${MAX_MB} MB"
@@ -15,7 +15,7 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v7 uses: actions/checkout@v6
- name: Obtain token - name: Obtain token
id: obtainToken id: obtainToken
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v7 uses: actions/checkout@v6
- name: Upload Crowdin translations - name: Upload Crowdin translations
uses: crowdin/github-action@v2 uses: crowdin/github-action@v2
@@ -26,7 +26,7 @@ jobs:
with: with:
args: "Beta release has been triggered: [run ${{ github.run_number }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})" args: "Beta release has been triggered: [run ${{ github.run_number }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})"
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v7 uses: actions/checkout@v6
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Get Next Version - name: Get Next Version
@@ -57,7 +57,7 @@ jobs:
client-id: ${{ secrets.RENOVATE_MERGE_APP_ID }} client-id: ${{ secrets.RENOVATE_MERGE_APP_ID }}
permission-contents: write # required to commit package.json & changelog changes, merge them to dev / next and publish the release permission-contents: write # required to commit package.json & changelog changes, merge them to dev / next and publish the release
- uses: actions/checkout@v7 - uses: actions/checkout@v6
if: env.SKIP_RELEASE == 'false' if: env.SKIP_RELEASE == 'false'
with: with:
persist-credentials: false persist-credentials: false
@@ -119,7 +119,7 @@ jobs:
outputs: outputs:
digest: ${{ steps.build.outputs.digest }} digest: ${{ steps.build.outputs.digest }}
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v6
with: with:
ref: ${{ needs.release.outputs.git_ref }} ref: ${{ needs.release.outputs.git_ref }}
@@ -158,7 +158,7 @@ jobs:
outputs: outputs:
digest: ${{ steps.build.outputs.digest }} digest: ${{ steps.build.outputs.digest }}
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v6
with: with:
ref: ${{ needs.release.outputs.git_ref }} ref: ${{ needs.release.outputs.git_ref }}
+1 -1
View File
@@ -30,7 +30,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 10 timeout-minutes: 10
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v6
- name: Setup - name: Setup
uses: ./tooling/github/setup uses: ./tooling/github/setup
- name: Build docs - name: Build docs
@@ -29,7 +29,7 @@ jobs:
with: with:
args: "Automatic release has been triggered: [run ${{ github.run_number }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})" args: "Automatic release has been triggered: [run ${{ github.run_number }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})"
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v7 uses: actions/checkout@v6
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Get Next Version - name: Get Next Version
+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 10 timeout-minutes: 10
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v6
- name: Setup - name: Setup
uses: ./tooling/github/setup uses: ./tooling/github/setup
@@ -19,7 +19,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 10 timeout-minutes: 10
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v6
with: with:
ref: dev ref: dev
+1 -1
View File
@@ -16,7 +16,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 10 timeout-minutes: 10
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v6
with: with:
ref: dev ref: dev
@@ -13,7 +13,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 5 timeout-minutes: 5
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v6
- name: Validate prebuilt dependencies for amd64 - name: Validate prebuilt dependencies for amd64
id: validate-amd64 id: validate-amd64
uses: ./.github/actions/prebuilt-debian uses: ./.github/actions/prebuilt-debian
@@ -30,7 +30,7 @@ jobs:
runs-on: ubuntu-24.04-arm runs-on: ubuntu-24.04-arm
timeout-minutes: 5 timeout-minutes: 5
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v6
- name: Validate prebuilt dependencies for arm64 - name: Validate prebuilt dependencies for arm64
id: validate-arm64 id: validate-arm64
uses: ./.github/actions/prebuilt-debian uses: ./.github/actions/prebuilt-debian
@@ -13,7 +13,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 2 timeout-minutes: 2
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v6
- run: | - run: |
npx --yes --package renovate -- \ npx --yes --package renovate -- \
renovate-config-validator --strict .github/renovate.json5 renovate-config-validator --strict .github/renovate.json5
+1 -1
View File
@@ -52,7 +52,7 @@ jobs:
permission-contents: write # required to commit to branch permission-contents: write # required to commit to branch
permission-pull-requests: write # required to create pr & enable automerge permission-pull-requests: write # required to create pr & enable automerge
- name: Checkout code - name: Checkout code
uses: actions/checkout@v7 uses: actions/checkout@v6
with: with:
token: ${{ steps.obtainToken.outputs.token }} token: ${{ steps.obtainToken.outputs.token }}
ref: dev ref: dev
+1 -1
View File
@@ -29,7 +29,7 @@ jobs:
permission-pull-requests: write # required to create pr & enable automerge permission-pull-requests: write # required to create pr & enable automerge
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v7 uses: actions/checkout@v6
env: env:
GITHUB_TOKEN: ${{ steps.obtainToken.outputs.token }} GITHUB_TOKEN: ${{ steps.obtainToken.outputs.token }}
@@ -28,7 +28,7 @@ jobs:
permission-contents: write # required to commit to branch permission-contents: write # required to commit to branch
permission-pull-requests: write # required to create pr & enable automerge permission-pull-requests: write # required to create pr & enable automerge
- name: Checkout code - name: Checkout code
uses: actions/checkout@v7 uses: actions/checkout@v6
env: env:
GITHUB_TOKEN: ${{ steps.obtainToken.outputs.token }} GITHUB_TOKEN: ${{ steps.obtainToken.outputs.token }}
- name: Setup - name: Setup
-12
View File
@@ -1,15 +1,3 @@
## [1.69.2](https://github.com/homarr-labs/homarr/compare/v1.69.1...v1.69.2) (2026-07-06)
### Bug Fixes
* **layout:** raise AppShellHeader z-index above Indicator dots ([687edb9](https://github.com/homarr-labs/homarr/commit/687edb9226307cb83986097abb24fe7f672e1778)), closes [#6194](https://github.com/homarr-labs/homarr/issues/6194)
## [1.69.1](https://github.com/homarr-labs/homarr/compare/v1.69.0...v1.69.1) (2026-07-04)
### Bug Fixes
* unblock query cache mutations in demo mode and add cache buster ([#6176](https://github.com/homarr-labs/homarr/issues/6176)) ([a382c75](https://github.com/homarr-labs/homarr/commit/a382c75968e73bafff55b5890b1e95f0779b50d3))
## [1.69.0](https://github.com/homarr-labs/homarr/compare/v1.68.1...v1.69.0) (2026-07-03) ## [1.69.0](https://github.com/homarr-labs/homarr/compare/v1.68.1...v1.69.0) (2026-07-03)
### Features ### Features
+8 -21
View File
@@ -39,26 +39,13 @@ import { immichServerStatsWidget } from '../../widgets/immich-server-stats';
'Scroll down to "API Keys"', 'Scroll down to "API Keys"',
'Click "New API Key"', 'Click "New API Key"',
'Enter a name, e.g. "Homarr"', 'Enter a name, e.g. "Homarr"',
( (<span>
Select the following permissions:{" "}
<span> <code>album.read</code>,{" "}
<code>user.read</code>,{" "}
Select the following permissions:{" "} <code>server.statistics</code>,{" "}
<code>album.statistics</code>,{" "} <code>asset.download</code>
<code>album.read</code>,{" "} </span>),
<code>album.create</code>,{" "}
<code>user.read</code>,{" "}
<code>user.update</code>,{" "}
<code>asset.read</code>,{" "}
<code>asset.download</code>,{" "}
<code>asset.statistics</code>,{" "}
<code>server.statistics</code>,{" "}
<code>server.about</code>.
<br />
Additional permissions may be required depending on your Immich version. If you encounter authorization errors, grant any missing permissions requested by the server.
</span>
),
'Create the integration in Homarr and copy the API key to there' 'Create the integration in Homarr and copy the API key to there'
] ]
}]} /> }]} />
+6 -18
View File
@@ -1,25 +1,18 @@
// Algolia DocSearch crawler for homarr.dev // Algolia DocSearch crawler for homarr.dev
// Crawler ID: cd77a285-2756-4557-bf21-ee703748df15 // Crawler ID: cd77a285-2756-4557-bf21-ee703748df15
// Paste this in the Algolia crawler editor. // DocSearch-managed crawlers: paste this in the Algolia crawler editor or send to DocSearch support.
// Template: https://docsearch.algolia.com/docs/templates/#docusaurus-v3-template
// Markdown indexing: https://www.algolia.com/doc/guides/algolia-ai/askai/guides/markdown-indexing
new Crawler({ new Crawler({
appId: "N69WSPZTID", appId: "N69WSPZTID",
apiKey: "YOUR_CRAWLER_ADMIN_API_KEY", apiKey: "YOUR_CRAWLER_ADMIN_API_KEY",
indexPrefix: "", rateLimit: 8,
rateLimit: 32, maxDepth: 10,
maxDepth: 4,
startUrls: ["https://homarr.dev/"], startUrls: ["https://homarr.dev/"],
sitemaps: ["https://homarr.dev/sitemap.xml"], sitemaps: ["https://homarr.dev/sitemap.xml"],
ignoreCanonicalTo: true, ignoreCanonicalTo: true,
discoveryPatterns: ["https://homarr.dev/**"], discoveryPatterns: ["https://homarr.dev/**"],
exclusionPatterns: [
"https://homarr.dev/docs/tags/**",
"https://homarr.dev/blog/tags/**",
"https://homarr.dev/blog/authors/**",
"https://homarr.dev/blog/archive/**",
"https://homarr.dev/search/**",
"https://homarr.dev/docs/category/**",
],
actions: [ actions: [
{ {
indexName: "Docusaurus", indexName: "Docusaurus",
@@ -112,6 +105,7 @@ new Crawler({
advancedSyntax: true, advancedSyntax: true,
attributeCriteriaComputedByMinProximity: true, attributeCriteriaComputedByMinProximity: true,
removeWordsIfNoResults: "allOptional", removeWordsIfNoResults: "allOptional",
separatorsToIndex: "_",
}, },
markdown: { markdown: {
attributesForFaceting: ["lang", "language", "version", "docusaurus_tag"], attributesForFaceting: ["lang", "language", "version", "docusaurus_tag"],
@@ -125,10 +119,4 @@ new Crawler({
advancedSyntax: false, advancedSyntax: false,
}, },
}, },
apiKey: "YOUR_CRAWLER_ADMIN_API_KEY",
schedule: "on saturday",
renderJavaScript: false,
maxUrls: null,
cache: { enabled: false },
safetyChecks: { beforeIndexPublishing: { maxLostRecordsPercentage: 99 } },
}); });
+2 -21
View File
@@ -8,7 +8,7 @@ const config: Config = {
tagline: "A simple yet powerful dashboard for your server.", tagline: "A simple yet powerful dashboard for your server.",
url: "https://homarr.dev", url: "https://homarr.dev",
baseUrl: "/", baseUrl: "/",
trailingSlash: undefined, trailingSlash: true,
favicon: "img/logo.png", favicon: "img/logo.png",
organizationName: "homarr-labs", organizationName: "homarr-labs",
projectName: "homarr", projectName: "homarr",
@@ -79,27 +79,8 @@ const config: Config = {
sitemap: { sitemap: {
changefreq: "weekly", changefreq: "weekly",
priority: 0.5, priority: 0.5,
ignorePatterns: ["/tags/**", "/docs/category/**"], ignorePatterns: ["/tags/**"],
filename: "sitemap.xml", filename: "sitemap.xml",
createSitemapItems: async ({ routes, siteConfig, defaultCreateSitemapItems }) => {
const items = await defaultCreateSitemapItems({ routes, siteConfig });
return items.map((item) => {
const path = new URL(item.url).pathname;
if (path === "/" || path === "") {
return { ...item, priority: 1.0, changefreq: "weekly" };
}
if (path.startsWith("/docs/")) {
return { ...item, priority: 0.7, changefreq: "monthly" };
}
if (path.startsWith("/blog/")) {
return { ...item, priority: 0.3, changefreq: "never" };
}
if (path.startsWith("/about-us")) {
return { ...item, priority: 0.4, changefreq: "yearly" };
}
return item;
});
},
}, },
} satisfies Preset.Options, } satisfies Preset.Options,
], ],
+3 -3
View File
@@ -32,7 +32,7 @@
"@scalar/api-reference-react": "catalog:", "@scalar/api-reference-react": "catalog:",
"@signalwire/docusaurus-plugin-llms-txt": "^1.2.2", "@signalwire/docusaurus-plugin-llms-txt": "^1.2.2",
"@tabler/icons-react": "catalog:", "@tabler/icons-react": "catalog:",
"@tailwindcss/postcss": "^4.3.2", "@tailwindcss/postcss": "^4.3.1",
"clsx": "catalog:", "clsx": "catalog:",
"dayjs": "catalog:", "dayjs": "catalog:",
"docusaurus-plugin-image-zoom": "^3.0.1", "docusaurus-plugin-image-zoom": "^3.0.1",
@@ -43,8 +43,8 @@
"random-word-slugs": "^0.1.7", "random-word-slugs": "^0.1.7",
"react": "catalog:", "react": "catalog:",
"react-dom": "catalog:", "react-dom": "catalog:",
"swiper": "^14.0.1", "swiper": "^12.2.0",
"tailwindcss": "^4.3.2" "tailwindcss": "^4.3.1"
}, },
"devDependencies": { "devDependencies": {
"@docusaurus/module-type-aliases": "^3.10.1", "@docusaurus/module-type-aliases": "^3.10.1",
+2 -1
View File
@@ -1,7 +1,8 @@
@import url("https://api.fontshare.com/v2/css?f[]=work-sans@2,1&display=swap");
@import "tailwindcss/theme" layer(theme); @import "tailwindcss/theme" layer(theme);
@import "tailwindcss/utilities" layer(utilities); @import "tailwindcss/utilities" layer(utilities);
@import url(https://api.fontshare.com/v2/css?f[]=work-sans@2,1&display=swap);
@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *)); @custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *));
@theme { @theme {
+4 -5
View File
@@ -1,6 +1,9 @@
{ {
"extends": "@docusaurus/tsconfig",
"compilerOptions": { "compilerOptions": {
"target": "ES2022", "ignoreDeprecations": "6.0",
"baseUrl": ".",
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"], "lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true, "allowJs": true,
"skipLibCheck": true, "skipLibCheck": true,
@@ -9,14 +12,10 @@
"noEmit": true, "noEmit": true,
"esModuleInterop": true, "esModuleInterop": true,
"module": "esnext", "module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"jsx": "preserve", "jsx": "preserve",
"incremental": true, "incremental": true,
"paths": {
"@site/*": ["./*"]
},
}, },
"include": [ "include": [
"**/*.ts", "**/*.ts",
+14 -12
View File
@@ -5,9 +5,21 @@ import "@homarr/common/env";
import "@homarr/core/infrastructure/logs/env"; import "@homarr/core/infrastructure/logs/env";
import "@homarr/docker/env"; import "@homarr/docker/env";
import { readFileSync } from "fs";
import type { NextConfig } from "next"; import type { NextConfig } from "next";
import createNextIntlPlugin from "next-intl/plugin"; import createNextIntlPlugin from "next-intl/plugin";
const homarrVersion = (() => {
for (const candidate of ["../../package.json", "./package.json"]) {
try {
const pkg = JSON.parse(readFileSync(candidate, "utf-8"));
if (pkg.name === "homarr") return pkg.version as string;
} catch {}
}
return "unknown";
})();
// Package path does not work... so we need to use relative path // Package path does not work... so we need to use relative path
const withNextIntl = createNextIntlPlugin({ const withNextIntl = createNextIntlPlugin({
requestConfig: "../../packages/translation/src/request.ts", requestConfig: "../../packages/translation/src/request.ts",
@@ -15,7 +27,7 @@ const withNextIntl = createNextIntlPlugin({
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
env: { env: {
HOMARR_VERSION: process.env.HOMARR_VERSION ?? "unknown", HOMARR_VERSION: homarrVersion,
}, },
output: "standalone", output: "standalone",
reactStrictMode: true, reactStrictMode: true,
@@ -31,19 +43,9 @@ const nextConfig: NextConfig = {
experimental: { experimental: {
optimizePackageImports: ["@mantine/core", "@mantine/hooks", "@tabler/icons-react"], optimizePackageImports: ["@mantine/core", "@mantine/hooks", "@tabler/icons-react"],
turbopackFileSystemCacheForDev: true, turbopackFileSystemCacheForDev: true,
preloadEntriesOnStart: false,
webpackMemoryOptimizations: true, webpackMemoryOptimizations: true,
}, },
turbopack: {
// ponytail: known Turbopack NFT warning from path.join(process.cwd(), …) in
// src/app/api/backup/{route,shared}.ts. No working placement in 16.2.x
// (see vercel/next.js#95125). Suppress until upstream fix lands.
ignoreIssue: [
{
path: "**/*",
title: "Encountered unexpected file in NFT list",
},
],
},
transpilePackages: ["@homarr/ui", "@homarr/notifications", "@homarr/modals", "@homarr/spotlight", "@homarr/widgets"], transpilePackages: ["@homarr/ui", "@homarr/notifications", "@homarr/modals", "@homarr/spotlight", "@homarr/widgets"],
images: { images: {
localPatterns: [ localPatterns: [
+1 -1
View File
@@ -4,7 +4,7 @@
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
"build": "HOMARR_VERSION=$(node -p \"require('../../package.json').version\") pnpm with-env next build", "build": "pnpm with-env next build",
"clean": "git clean -xdf .next .turbo node_modules", "clean": "git clean -xdf .next .turbo node_modules",
"dev": "pnpm with-env next dev", "dev": "pnpm with-env next dev",
"format": "oxfmt .", "format": "oxfmt .",
@@ -1,22 +1,39 @@
import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister"; import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister";
import { TRPCClientError } from "@trpc/client";
import superjson from "superjson"; import superjson from "superjson";
import { fetchApi } from "@homarr/api/client"; import { fetchApi } from "@homarr/api/client";
import { getActiveQueryCacheBoardId, queryCacheStoragePrefix } from "@homarr/api/query-cache"; import { getActiveQueryCacheBoardId, queryCacheStoragePrefix } from "@homarr/api/query-cache";
// Set once the server rejects a persist mutation as read-only (demo mode),
// so we stop retrying a mutation that can never succeed.
let persistDisabled = false;
const isReadOnlyError = (error: unknown) => error instanceof TRPCClientError && error.data?.code === "FORBIDDEN";
const queryCacheStorage = { const queryCacheStorage = {
getItem: (_key: string) => null as string | null, getItem: (_key: string) => null as string | null,
async setItem(_key: string, value: string) { async setItem(_key: string, value: string) {
if (persistDisabled) return;
const boardId = getActiveQueryCacheBoardId(); const boardId = getActiveQueryCacheBoardId();
if (!boardId) return; if (!boardId) return;
await fetchApi.queryCache.setItem.mutate({ boardId, value }).catch((error) => { await fetchApi.queryCache.setItem.mutate({ boardId, value }).catch((error) => {
if (isReadOnlyError(error)) {
persistDisabled = true;
return;
}
console.warn("[query-cache] persist failed", error); console.warn("[query-cache] persist failed", error);
}); });
}, },
async removeItem(_key: string) { async removeItem(_key: string) {
if (persistDisabled) return;
const boardId = getActiveQueryCacheBoardId(); const boardId = getActiveQueryCacheBoardId();
if (!boardId) return; if (!boardId) return;
await fetchApi.queryCache.removeItem.mutate({ boardId }).catch((error) => { await fetchApi.queryCache.removeItem.mutate({ boardId }).catch((error) => {
if (isReadOnlyError(error)) {
persistDisabled = true;
return;
}
console.warn("[query-cache] remove failed", error); console.warn("[query-cache] remove failed", error);
}); });
}, },
@@ -24,7 +24,6 @@ import type { AppRouter } from "@homarr/api";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { import {
isPersistableWidgetQueryKey, isPersistableWidgetQueryKey,
queryCacheBuster,
queryCacheDefaultGcTimeMs, queryCacheDefaultGcTimeMs,
queryCacheDefaultRefetchIntervalMs, queryCacheDefaultRefetchIntervalMs,
queryCacheDefaultStaleTimeMs, queryCacheDefaultStaleTimeMs,
@@ -137,7 +136,6 @@ export function TRPCReactProvider(props: PropsWithChildren) {
client={queryClient} client={queryClient}
persistOptions={{ persistOptions={{
persister, persister,
buster: queryCacheBuster,
maxAge: queryCacheDefaultGcTimeMs, maxAge: queryCacheDefaultGcTimeMs,
dehydrateOptions: { dehydrateOptions: {
shouldDehydrateQuery: (query) => shouldDehydrateQuery: (query) =>
@@ -7,8 +7,7 @@ import "~/styles/gridstack.scss";
import { dehydrate, HydrationBoundary } from "@tanstack/react-query"; import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
import type { PersistedClient } from "@tanstack/react-query-persist-client"; import type { PersistedClient } from "@tanstack/react-query-persist-client";
import superjson from "superjson"; import SuperJSON from "superjson";
import { queryCacheBuster } from "@homarr/api/query-cache";
import { getQueryClient } from "@homarr/api/server"; import { getQueryClient } from "@homarr/api/server";
import { IntegrationProvider } from "@homarr/auth/client"; import { IntegrationProvider } from "@homarr/auth/client";
import { auth } from "@homarr/auth/next"; import { auth } from "@homarr/auth/next";
@@ -123,9 +122,8 @@ async function QueryCacheHydration({ userId, boardId }: { userId: string; boardI
const serialized = await getQueryCacheAsync(userId, boardId); const serialized = await getQueryCacheAsync(userId, boardId);
if (!serialized) return null; if (!serialized) return null;
const persisted = superjson.parse<PersistedClient | undefined>(serialized); const persisted = SuperJSON.parse<PersistedClient>(serialized);
if (!persisted || persisted.buster !== queryCacheBuster) return null; if (!persisted?.clientState?.queries?.length) return null;
if (!persisted.clientState?.queries?.length) return null;
return <HydrationBoundary state={persisted.clientState} />; return <HydrationBoundary state={persisted.clientState} />;
} catch (error) { } catch (error) {
@@ -45,9 +45,7 @@ export const BoardContentHeaderActions = () => {
const [isEditMode] = useEditMode(); const [isEditMode] = useEditMode();
const board = useRequiredBoard(); const board = useRequiredBoard();
const { hasChangeAccess } = useBoardPermissions(board); const { hasChangeAccess } = useBoardPermissions(board);
// Fall back to read-only if the query has no data (e.g. errored) so we never expose const { data: demoMode, isLoading } = clientApi.info.isDemoMode.useQuery();
// edit/save/settings UI that would then fail server-side.
const { data: demoReadOnly = true, isLoading } = clientApi.info.isDemoReadOnly.useQuery();
if (!hasChangeAccess || isLoading) { if (!hasChangeAccess || isLoading) {
return <SelectBoardsMenu />; return <SelectBoardsMenu />;
@@ -57,9 +55,9 @@ export const BoardContentHeaderActions = () => {
<> <>
{isEditMode && <AddMenu />} {isEditMode && <AddMenu />}
<EditModeMenu demoReadOnly={demoReadOnly} /> <EditModeMenu demoMode={demoMode ?? false} />
{!demoReadOnly && ( {!demoMode && (
<OnboardingTour.Target id="board-settings"> <OnboardingTour.Target id="board-settings">
<HeaderButton href={`/boards/${board.name}/settings`}> <HeaderButton href={`/boards/${board.name}/settings`}>
<IconSettings stroke={1.5} /> <IconSettings stroke={1.5} />
@@ -160,7 +158,7 @@ const AddMenu = () => {
); );
}; };
const EditModeMenu = ({ demoReadOnly }: { demoReadOnly: boolean }) => { const EditModeMenu = ({ demoMode }: { demoMode: boolean }) => {
const [isEditMode, { open, close }] = useEditMode(); const [isEditMode, { open, close }] = useEditMode();
const board = useRequiredBoard(); const board = useRequiredBoard();
const utils = clientApi.useUtils(); const utils = clientApi.useUtils();
@@ -190,11 +188,11 @@ const EditModeMenu = ({ demoReadOnly }: { demoReadOnly: boolean }) => {
const toggle = useCallback(() => { const toggle = useCallback(() => {
if (isEditMode) { if (isEditMode) {
if (demoReadOnly) return discardDemoChanges(); if (demoMode) return discardDemoChanges();
return saveBoard(board); return saveBoard(board);
} }
open(); open();
}, [board, isEditMode, demoReadOnly, saveBoard, open, discardDemoChanges]); }, [board, isEditMode, demoMode, saveBoard, open, discardDemoChanges]);
useHotkeys([[hotkeys.toggleBoardEdit, toggle]]); useHotkeys([[hotkeys.toggleBoardEdit, toggle]]);
usePreventLeaveWithDirty(isEditMode); usePreventLeaveWithDirty(isEditMode);
+8 -10
View File
@@ -1,13 +1,11 @@
import fs from "fs"; import fs from "fs";
import path from "path"; import path from "path";
export const findMigrationsFolder = () => { const migrationsFolderCandidates = [
const cwd = process.cwd(); path.join(process.cwd(), "db/migrations/sqlite"),
const migrationsFolderCandidates = [ path.join(process.cwd(), "packages/db/migrations/sqlite"),
path.join(cwd, "db/migrations/sqlite"), path.resolve(process.cwd(), "../../db/migrations/sqlite"),
path.join(cwd, "packages/db/migrations/sqlite"), "/app/db/migrations/sqlite",
path.resolve(cwd, "../../db/migrations/sqlite"), ];
"/app/db/migrations/sqlite",
]; export const findMigrationsFolder = () => migrationsFolderCandidates.find((candidate) => fs.existsSync(candidate));
return migrationsFolderCandidates.find((candidate) => fs.existsSync(candidate));
};
@@ -2,10 +2,10 @@
import type { MutableRefObject, ReactNode } from "react"; import type { MutableRefObject, ReactNode } from "react";
import { useCallback, useEffect, useMemo, useState } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
import { Group, Loader, Menu, Switch, Text } from "@mantine/core"; import { Group, Menu, Switch, Text } from "@mantine/core";
import { IconCopy, IconLayoutKanban, IconRefresh, IconSettings, IconTrash } from "@tabler/icons-react"; import { IconCopy, IconLayoutKanban, IconRefresh, IconSettings, IconTrash } from "@tabler/icons-react";
import type { QueryClient } from "@tanstack/react-query"; import type { QueryClient } from "@tanstack/react-query";
import { useIsFetching, useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { useSession } from "@homarr/auth/client"; import { useSession } from "@homarr/auth/client";
@@ -50,9 +50,8 @@ export const WidgetContextMenu = ({ item, widgetStateRef, children }: WidgetCont
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const widgetQueryKey = useMemo(() => [["widget", item.kind]], [item.kind]); const widgetQueryKey = useMemo(() => [["widget", item.kind]], [item.kind]);
const isWidgetFetching = useIsFetching({ queryKey: widgetQueryKey }) > 0;
const handleRefetch = useCallback(() => { const handleRefetch = useCallback(() => {
void queryClient.refetchQueries({ queryKey: widgetQueryKey, type: "all" }); void queryClient.invalidateQueries({ queryKey: widgetQueryKey });
}, [queryClient, widgetQueryKey]); }, [queryClient, widgetQueryKey]);
const options = useMemo( const options = useMemo(
@@ -224,15 +223,11 @@ export const WidgetContextMenu = ({ item, widgetStateRef, children }: WidgetCont
<> <>
{(toggleOptions.length > 0 || visibleWidgetActions.length > 0 || isEditMode) && <Menu.Divider />} {(toggleOptions.length > 0 || visibleWidgetActions.length > 0 || isEditMode) && <Menu.Divider />}
<Menu.Item <Menu.Item closeMenuOnClick leftSection={<IconRefresh size={16} />} onClick={handleRefetch}>
leftSection={isWidgetFetching ? <Loader size={16} /> : <IconRefresh size={16} />}
onClick={handleRefetch}
disabled={isWidgetFetching}
>
<Group justify="space-between" wrap="nowrap"> <Group justify="space-between" wrap="nowrap">
{tMenu("refresh")} {tMenu("refresh")}
<Text size="xs" c="dimmed"> <Text size="xs" c="dimmed">
<WidgetCacheAge queryClient={queryClient} queryKey={widgetQueryKey} isFetching={isWidgetFetching} /> <WidgetCacheAge queryClient={queryClient} queryKey={widgetQueryKey} />
</Text> </Text>
</Group> </Group>
</Menu.Item> </Menu.Item>
@@ -270,24 +265,13 @@ export const WidgetContextMenu = ({ item, widgetStateRef, children }: WidgetCont
); );
}; };
const WidgetCacheAge = ({ const WidgetCacheAge = ({ queryClient, queryKey }: { queryClient: QueryClient; queryKey: unknown[] }) => {
queryClient,
queryKey,
isFetching,
}: {
queryClient: QueryClient;
queryKey: unknown[];
isFetching: boolean;
}) => {
// 1s tick for "just now" → "1s ago" label transition; isFetching prop handles refetch reactivity
const [, setTick] = useState(0); const [, setTick] = useState(0);
useEffect(() => { useEffect(() => {
const id = setInterval(() => setTick((n) => n + 1), 1000); const id = setInterval(() => setTick((n) => n + 1), 1000);
return () => clearInterval(id); return () => clearInterval(id);
}, []); }, []);
if (isFetching) return <Loader size={12} />;
const timestamps = queryClient const timestamps = queryClient
.getQueryCache() .getQueryCache()
.findAll({ queryKey }) .findAll({ queryKey })
+1 -1
View File
@@ -18,7 +18,7 @@ interface Props {
export const MainHeader = ({ logo, actions, hasNavigation = true }: Props) => { export const MainHeader = ({ logo, actions, hasNavigation = true }: Props) => {
return ( return (
<AppShellHeader maw="100vw" zIndex={201} style={{ overflowX: "hidden" }}> <AppShellHeader maw="100vw" style={{ overflowX: "hidden" }}>
<Group h="100%" gap="xl" px="md" justify="apart" wrap="nowrap"> <Group h="100%" gap="xl" px="md" justify="apart" wrap="nowrap">
<Group h="100%" align="center" style={{ flex: 1 }} wrap="nowrap"> <Group h="100%" align="center" style={{ flex: 1 }} wrap="nowrap">
{hasNavigation && <ClientBurger />} {hasNavigation && <ClientBurger />}
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "homarr-prebuilt-debian", "name": "homarr-prebuilt-debian",
"private": true, "private": true,
"dependencies": { "dependencies": {
"better-sqlite3": "^12.11.1" "better-sqlite3": "^12.10.0"
}, },
"engines": { "engines": {
"node": ">=24.18.0", "node": ">=24.18.0",
+5 -5
View File
@@ -9,16 +9,16 @@ importers:
.: .:
dependencies: dependencies:
better-sqlite3: better-sqlite3:
specifier: ^12.11.1 specifier: ^12.10.0
version: 12.11.1 version: 12.10.0
packages: packages:
base64-js@1.5.1: base64-js@1.5.1:
resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}
better-sqlite3@12.11.1: better-sqlite3@12.10.0:
resolution: {integrity: sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==} resolution: {integrity: sha512-CyzaZRQKyHkB2ZInfTTl2nvT33EbDpjkLEbE8/Zck3Ll6O0qqvuGdrJ45HgtH+HykRg88ITY3AdreBGN70aBSQ==}
engines: {node: 20.x || 22.x || 23.x || 24.x || 25.x || 26.x} engines: {node: 20.x || 22.x || 23.x || 24.x || 25.x || 26.x}
bindings@1.5.0: bindings@1.5.0:
@@ -148,7 +148,7 @@ snapshots:
base64-js@1.5.1: {} base64-js@1.5.1: {}
better-sqlite3@12.11.1: better-sqlite3@12.10.0:
dependencies: dependencies:
bindings: 1.5.0 bindings: 1.5.0
prebuild-install: 7.1.3 prebuild-install: 7.1.3
+1 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "homarr", "name": "homarr",
"version": "1.69.2", "version": "1.69.0",
"private": true, "private": true,
"scripts": { "scripts": {
"build": "cross-env CI=true turbo build", "build": "cross-env CI=true turbo build",
@@ -43,7 +43,6 @@
"@semantic-release/release-notes-generator": "catalog:", "@semantic-release/release-notes-generator": "catalog:",
"@testcontainers/redis": "catalog:", "@testcontainers/redis": "catalog:",
"@turbo/gen": "catalog:", "@turbo/gen": "catalog:",
"@vitejs/plugin-react": "catalog:", "@vitejs/plugin-react": "catalog:",
"@vitest/coverage-v8": "catalog:", "@vitest/coverage-v8": "catalog:",
"@vitest/ui": "catalog:", "@vitest/ui": "catalog:",
-2
View File
@@ -6,11 +6,9 @@ export const env = createEnv({
server: { server: {
KUBERNETES_SERVICE_ACCOUNT_NAME: z.string().optional(), KUBERNETES_SERVICE_ACCOUNT_NAME: z.string().optional(),
DEMO_MODE: createBooleanSchema(false), DEMO_MODE: createBooleanSchema(false),
DEMO_READ_ONLY: createBooleanSchema(true),
}, },
runtimeEnv: { runtimeEnv: {
KUBERNETES_SERVICE_ACCOUNT_NAME: process.env.KUBERNETES_SERVICE_ACCOUNT_NAME, KUBERNETES_SERVICE_ACCOUNT_NAME: process.env.KUBERNETES_SERVICE_ACCOUNT_NAME,
DEMO_MODE: process.env.DEMO_MODE, DEMO_MODE: process.env.DEMO_MODE,
DEMO_READ_ONLY: process.env.DEMO_READ_ONLY,
}, },
}); });
-1
View File
@@ -5,7 +5,6 @@ export const queryCacheDefaultRefetchIntervalMs = 30_000;
export const queryCacheDefaultGcTimeMs = 1000 * 60 * 60 * 24; export const queryCacheDefaultGcTimeMs = 1000 * 60 * 60 * 24;
export const queryCacheMaxValueBytes = 1024 * 1024; export const queryCacheMaxValueBytes = 1024 * 1024;
export const queryCacheStoragePrefix = "homarr-widget-query"; export const queryCacheStoragePrefix = "homarr-widget-query";
export const queryCacheBuster = "v2-superjson";
let activeQueryCacheBoardId: string | null = null; let activeQueryCacheBoardId: string | null = null;
+1 -2
View File
@@ -1,7 +1,7 @@
import z from "zod/v4"; import z from "zod/v4";
import packageJson from "../../../../package.json"; import packageJson from "../../../../package.json";
import { createTRPCRouter, isDemoMode, isDemoReadOnly, publicProcedure, protectedProcedure } from "../trpc"; import { createTRPCRouter, isDemoMode, publicProcedure, protectedProcedure } from "../trpc";
export const infoRouter = createTRPCRouter({ export const infoRouter = createTRPCRouter({
getInfo: protectedProcedure getInfo: protectedProcedure
@@ -20,5 +20,4 @@ export const infoRouter = createTRPCRouter({
}; };
}), }),
isDemoMode: publicProcedure.query(() => isDemoMode), isDemoMode: publicProcedure.query(() => isDemoMode),
isDemoReadOnly: publicProcedure.query(() => isDemoReadOnly),
}); });
+3 -3
View File
@@ -5,7 +5,7 @@ import { boards } from "@homarr/db/schema";
import { removeQueryCacheAsync, setQueryCacheAsync } from "@homarr/redis"; import { removeQueryCacheAsync, setQueryCacheAsync } from "@homarr/redis";
import { queryCacheDefaultGcTimeMs, queryCacheMaxValueBytes } from "../query-cache"; import { queryCacheDefaultGcTimeMs, queryCacheMaxValueBytes } from "../query-cache";
import { createTRPCRouter, internalProcedure } from "../trpc"; import { createTRPCRouter, publicProcedure } from "../trpc";
import { throwIfActionForbiddenAsync } from "./board/board-access"; import { throwIfActionForbiddenAsync } from "./board/board-access";
const queryCacheBoardInput = z.object({ const queryCacheBoardInput = z.object({
@@ -21,7 +21,7 @@ const validateBoardAccessAsync = async (ctx: Parameters<typeof throwIfActionForb
}; };
export const queryCacheRouter = createTRPCRouter({ export const queryCacheRouter = createTRPCRouter({
setItem: internalProcedure.input(queryCacheSetInput).mutation(async ({ ctx, input }) => { setItem: publicProcedure.input(queryCacheSetInput).mutation(async ({ ctx, input }) => {
await validateBoardAccessAsync(ctx, input.boardId); await validateBoardAccessAsync(ctx, input.boardId);
const userId = ctx.session?.user.id ?? "anonymous"; const userId = ctx.session?.user.id ?? "anonymous";
return { return {
@@ -34,7 +34,7 @@ export const queryCacheRouter = createTRPCRouter({
), ),
}; };
}), }),
removeItem: internalProcedure.input(queryCacheBoardInput).mutation(async ({ ctx, input }) => { removeItem: publicProcedure.input(queryCacheBoardInput).mutation(async ({ ctx, input }) => {
await validateBoardAccessAsync(ctx, input.boardId); await validateBoardAccessAsync(ctx, input.boardId);
const userId = ctx.session?.user.id ?? "anonymous"; const userId = ctx.session?.user.id ?? "anonymous";
await removeQueryCacheAsync(userId, input.boardId); await removeQueryCacheAsync(userId, input.boardId);
+2 -8
View File
@@ -95,12 +95,8 @@ export const createTRPCRouter = t.router;
export const isDemoMode = env.DEMO_MODE; export const isDemoMode = env.DEMO_MODE;
// The public "real demo" (demo + mock integrations) stays read-only, while preview
// deployments run with DEMO_MODE + DEMO_READ_ONLY=false to allow mutations.
export const isDemoReadOnly = env.DEMO_MODE && env.DEMO_READ_ONLY;
const enforceDemoModeReadOnly = t.middleware(({ ctx, next, type }) => { const enforceDemoModeReadOnly = t.middleware(({ ctx, next, type }) => {
if (isDemoReadOnly && type === "mutation") { if (env.DEMO_MODE && type === "mutation") {
throw new TRPCError({ throw new TRPCError({
code: "FORBIDDEN", code: "FORBIDDEN",
message: "Mutations are disabled in demo mode", message: "Mutations are disabled in demo mode",
@@ -109,7 +105,7 @@ const enforceDemoModeReadOnly = t.middleware(({ ctx, next, type }) => {
return next({ ctx }); return next({ ctx });
}); });
const baseProcedure = isDemoReadOnly ? t.procedure.use(enforceDemoModeReadOnly) : t.procedure; const baseProcedure = env.DEMO_MODE ? t.procedure.use(enforceDemoModeReadOnly) : t.procedure;
/** /**
* Public (unauthed) procedure * Public (unauthed) procedure
@@ -120,8 +116,6 @@ const baseProcedure = isDemoReadOnly ? t.procedure.use(enforceDemoModeReadOnly)
*/ */
export const publicProcedure = baseProcedure; export const publicProcedure = baseProcedure;
export const internalProcedure = t.procedure;
const enforceUserIsAuthed = t.middleware(({ ctx, next }) => { const enforceUserIsAuthed = t.middleware(({ ctx, next }) => {
if (!ctx.session?.user) { if (!ctx.session?.user) {
throw new TRPCError({ code: "UNAUTHORIZED" }); throw new TRPCError({ code: "UNAUTHORIZED" });
+1 -1
View File
@@ -6,5 +6,5 @@ export function parseCookies(cookieString: string) {
} }
export function setClientCookie(name: string, value: string, options: SerializeOptions = {}) { export function setClientCookie(name: string, value: string, options: SerializeOptions = {}) {
document.cookie = stringifySetCookie({ name, value, ...options }); document.cookie = stringifySetCookie(name, value, options);
} }
@@ -25,7 +25,7 @@ export class AxiosHttpErrorHandler extends HttpErrorHandler {
return new RequestError(requestErrorInput, { return new RequestError(requestErrorInput, {
cause: error, cause: error,
}) as AnyRequestError; });
} }
handleResponseError(error: unknown): ResponseError | undefined { handleResponseError(error: unknown): ResponseError | undefined {
if (!(error instanceof AxiosError)) return undefined; if (!(error instanceof AxiosError)) return undefined;
@@ -20,7 +20,7 @@ export class FetchHttpErrorHandler extends HttpErrorHandler {
const result = matchErrorCode(error.cause.code); const result = matchErrorCode(error.cause.code);
if (!result) return undefined; if (!result) return undefined;
return new RequestError(result, { cause: error }) as AnyRequestError; return new RequestError(result, { cause: error });
} }
/** /**
@@ -59,7 +59,7 @@ export const matchErrorCode = (code: string): AnyRequestErrorInput | undefined =
type: key, type: key,
reason: found[0] as RequestErrorReason<typeof key>, reason: found[0] as RequestErrorReason<typeof key>,
code: code as RequestErrorCode, code: code as RequestErrorCode,
} as AnyRequestErrorInput; };
} }
return undefined; return undefined;
@@ -30,7 +30,7 @@ export class NodeFetchHttpErrorHandler extends HttpErrorHandler {
return new RequestError(requestErrorInput, { return new RequestError(requestErrorInput, {
cause: error, cause: error,
}) as AnyRequestError; });
} }
/** /**
@@ -1,9 +0,0 @@
CREATE TABLE `widget_secret` (
`item_id` varchar(64) NOT NULL,
`kind` varchar(64) NOT NULL,
`value` text NOT NULL,
`updated_at` timestamp NOT NULL,
CONSTRAINT `widget_secret_item_id_kind_pk` PRIMARY KEY(`item_id`,`kind`)
);
--> statement-breakpoint
ALTER TABLE `widget_secret` ADD CONSTRAINT `widget_secret_item_id_item_id_fk` FOREIGN KEY (`item_id`) REFERENCES `item`(`id`) ON DELETE cascade ON UPDATE no action;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -295,13 +295,6 @@
"when": 1780764500000, "when": 1780764500000,
"tag": "0041_merge_custom_widget_url", "tag": "0041_merge_custom_widget_url",
"breakpoints": true "breakpoints": true
},
{
"idx": 42,
"version": "5",
"when": 1783176100870,
"tag": "0042_add_widget_secret",
"breakpoints": true
} }
] ]
} }
@@ -1,9 +0,0 @@
CREATE TABLE "widget_secret" (
"item_id" varchar(64) NOT NULL,
"kind" varchar(64) NOT NULL,
"value" text NOT NULL,
"updated_at" timestamp NOT NULL,
CONSTRAINT "widget_secret_item_id_kind_pk" PRIMARY KEY("item_id","kind")
);
--> statement-breakpoint
ALTER TABLE "widget_secret" ADD CONSTRAINT "widget_secret_item_id_item_id_fk" FOREIGN KEY ("item_id") REFERENCES "public"."item"("id") ON DELETE cascade ON UPDATE no action;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -57,13 +57,6 @@
"when": 1780764500000, "when": 1780764500000,
"tag": "0007_merge_custom_widget_url", "tag": "0007_merge_custom_widget_url",
"breakpoints": true "breakpoints": true
},
{
"idx": 8,
"version": "7",
"when": 1783176100870,
"tag": "0008_add_widget_secret",
"breakpoints": true
} }
] ]
} }
@@ -1,8 +0,0 @@
CREATE TABLE `widget_secret` (
`item_id` text NOT NULL,
`kind` text NOT NULL,
`value` text NOT NULL,
`updated_at` integer NOT NULL,
PRIMARY KEY(`item_id`, `kind`),
FOREIGN KEY (`item_id`) REFERENCES `item`(`id`) ON UPDATE no action ON DELETE cascade
);
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -281,13 +281,6 @@
"when": 1780764500000, "when": 1780764500000,
"tag": "0039_merge_custom_widget_url", "tag": "0039_merge_custom_widget_url",
"breakpoints": true "breakpoints": true
},
{
"idx": 40,
"version": "6",
"when": 1783176100870,
"tag": "0040_add_widget_secret",
"breakpoints": true
} }
] ]
} }
@@ -60,8 +60,8 @@ export type HomarrDocumentationPath =
| "/docs/tags/connections" | "/docs/tags/connections"
| "/docs/tags/custom-widgets" | "/docs/tags/custom-widgets"
| "/docs/tags/customization" | "/docs/tags/customization"
| "/docs/tags/data"
| "/docs/tags/data-sources" | "/docs/tags/data-sources"
| "/docs/tags/data"
| "/docs/tags/database" | "/docs/tags/database"
| "/docs/tags/developer" | "/docs/tags/developer"
| "/docs/tags/development" | "/docs/tags/development"
@@ -99,8 +99,8 @@ export type HomarrDocumentationPath =
| "/docs/tags/redis" | "/docs/tags/redis"
| "/docs/tags/responsive" | "/docs/tags/responsive"
| "/docs/tags/roles" | "/docs/tags/roles"
| "/docs/tags/search"
| "/docs/tags/search-engines" | "/docs/tags/search-engines"
| "/docs/tags/search"
| "/docs/tags/secrets" | "/docs/tags/secrets"
| "/docs/tags/security" | "/docs/tags/security"
| "/docs/tags/self-signed" | "/docs/tags/self-signed"
@@ -132,6 +132,15 @@ export type HomarrDocumentationPath =
| "/docs/advanced/running-as-different-user" | "/docs/advanced/running-as-different-user"
| "/docs/advanced/single-sign-on" | "/docs/advanced/single-sign-on"
| "/docs/advanced/styling" | "/docs/advanced/styling"
| "/docs/category/advanced"
| "/docs/category/community"
| "/docs/category/developer-guides"
| "/docs/category/getting-started"
| "/docs/category/installation-1"
| "/docs/category/installation"
| "/docs/category/integrations"
| "/docs/category/management"
| "/docs/category/widgets"
| "/docs/community/donate" | "/docs/community/donate"
| "/docs/community/faq" | "/docs/community/faq"
| "/docs/community/get-in-touch" | "/docs/community/get-in-touch"
@@ -72,14 +72,7 @@ export const AppForm = ({
} }
form.initialize(toFormValues(initialValues)); form.initialize(toFormValues(initialValues));
// `form` is a new object every render (Mantine useForm returns a fresh literal), }, [initialValuesKey, form, initialValues]);
// so it must not be a dep here — it would re-run every render and, since
// form.initialize() always calls clearErrors() (new {} object) internally,
// trigger an infinite update loop. initialValuesKey (a primitive string)
// already captures the only case this effect exists for: re-initializing
// when initialValues actually changes (e.g. navigating between edit pages).
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [initialValuesKey]);
// Debounce the name value with 200ms delay // Debounce the name value with 200ms delay
const [debouncedName] = useDebouncedValue(form.values.name, 200); const [debouncedName] = useDebouncedValue(form.values.name, 200);
@@ -46,7 +46,7 @@ const gluetunServerSelectionSchema = z.object({
isps: z.array(z.string()).nullable(), isps: z.array(z.string()).nullable(),
names: z.array(z.string()).nullable(), names: z.array(z.string()).nullable(),
numbers: z.array(z.number()).nullable(), numbers: z.array(z.number()).nullable(),
hostnames: z.array(z.string()).nullable(), hostnames: z.array(z.string()),
owned_only: z.boolean(), owned_only: z.boolean(),
free_only: z.boolean(), free_only: z.boolean(),
premium_only: z.boolean(), premium_only: z.boolean(),
@@ -65,7 +65,7 @@ const gluetunPortForwardingSchema = z.object({
status_file_path: z.string(), status_file_path: z.string(),
up_command: z.string(), up_command: z.string(),
down_command: z.string(), down_command: z.string(),
listening_port: z.union([z.number(), z.array(z.number())]), listening_port: z.number(),
username: z.string(), username: z.string(),
password: z.string(), password: z.string(),
}); });
@@ -98,7 +98,7 @@ const gluetunOpenvpnSettingsSchema = z.object({
const gluetunWireguardSettingsSchema = z.object({ const gluetunWireguardSettingsSchema = z.object({
private_key: z.string(), private_key: z.string(),
pre_shared_key: z.string(), pre_shared_key: z.string(),
addresses: z.array(z.string()).nullable(), addresses: z.array(z.string()),
allowed_ips: z.array(z.string()), allowed_ips: z.array(z.string()),
interface: z.string(), interface: z.string(),
persistent_keep_alive_interval: z.number(), persistent_keep_alive_interval: z.number(),
@@ -124,126 +124,6 @@ const VPN_SETTINGS_PAYLOAD = {
}, },
}; };
const ALT_VPN_SETTINGS_PAYLOAD = {
type: "openvpn",
provider: {
name: "custom",
server_selection: {
vpn: "openvpn",
countries: null,
categories: null,
regions: null,
cities: null,
isps: null,
names: null,
numbers: null,
hostnames: null,
owned_only: false,
free_only: false,
premium_only: false,
stream_only: false,
multi_hop_only: false,
port_forward_only: false,
secure_core_only: false,
tor_only: false,
openvpn: {
config_file_path: "/gluetun/custom.conf",
protocol: "tcp",
endpoint_ip: "0.0.0.0",
custom_port: 0,
pia_encryption_preset: "",
},
wireguard: {
endpoint_ip: "0.0.0.0",
endpoint_port: 0,
public_key: "",
},
},
port_forwarding: {
enabled: false,
provider: "",
status_file_path: "/tmp/gluetun/forwarded_port",
up_command: "",
down_command: "",
listening_port: [0],
ports_count: 0,
username: "",
password: "",
},
},
amneziawg: {
wireguard: {
private_key: "",
pre_shared_key: "",
addresses: null,
allowed_ips: ["0.0.0.0/0", "::/0"],
interface: "tun0",
persistent_keep_alive_interval: 0,
mtu: 0,
implementation: "userspace",
},
junk_packet_count: 0,
junk_packet_min: 0,
junk_packet_max: 0,
padding_s1: 0,
padding_s2: 0,
padding_s3: 0,
padding_s4: 0,
header_h1: "",
header_h2: "",
header_h3: "",
header_h4: "",
init_packet_i1: "",
init_packet_i2: "",
init_packet_i3: "",
init_packet_i4: "",
init_packet_i5: "",
},
openvpn: {
version: "2.6",
user: "",
password: "",
config_file_path: "/gluetun/custom.conf",
ciphers: null,
auth: "",
cert: "",
key: "",
encrypted_key: "",
key_passphrase: "",
pia_encryption_preset: "",
mssfix: 0,
interface: "tun0",
process_user: "nonrootuser",
verbosity: 1,
flags: null,
},
wireguard: {
private_key: "",
pre_shared_key: "",
addresses: null,
allowed_ips: ["0.0.0.0/0", "::/0"],
interface: "tun0",
persistent_keep_alive_interval: 0,
mtu: 0,
implementation: "auto",
},
pmtud: {
icmp_addresses: ["1.1.1.1", "8.8.8.8"],
tcp_addresses: [
"1.1.1.1:443",
"8.8.8.8:443",
"1.1.1.1:53",
"8.8.8.8:53",
"[2606:4700:4700::1111]:53",
"[2001:4860:4860::8888]:53",
"[2606:4700:4700::1111]:443",
"[2001:4860:4860::8888]:443",
],
},
up_command: "",
down_command: "",
};
const jsonResponse = (body: unknown, init: ResponseInit = { status: 200 }): FetchResponse => const jsonResponse = (body: unknown, init: ResponseInit = { status: 200 }): FetchResponse =>
new Response(JSON.stringify(body), { new Response(JSON.stringify(body), {
...init, ...init,
@@ -488,54 +368,4 @@ describe("gluetun schemas", () => {
test("vpn settings schema rejects a non-string type", () => { test("vpn settings schema rejects a non-string type", () => {
expect(() => gluetunVpnSettingsSchema.parse({ ...VPN_SETTINGS_PAYLOAD, type: 1 })).toThrow(); expect(() => gluetunVpnSettingsSchema.parse({ ...VPN_SETTINGS_PAYLOAD, type: 1 })).toThrow();
}); });
test("vpn settings schema parses the live gluetun-latest custom/OpenVPN payload", () => {
const parsed = gluetunVpnSettingsSchema.parse(ALT_VPN_SETTINGS_PAYLOAD);
expect(parsed.type).toBe("openvpn");
expect(parsed.provider.name).toBe("custom");
});
test("vpn settings schema accepts null server-selection hostnames", () => {
const payload = {
...VPN_SETTINGS_PAYLOAD,
provider: {
...VPN_SETTINGS_PAYLOAD.provider,
server_selection: {
...VPN_SETTINGS_PAYLOAD.provider.server_selection,
hostnames: null,
},
},
};
expect(() => gluetunVpnSettingsSchema.parse(payload)).not.toThrow();
});
test("vpn settings schema accepts listening_port as a number or a list", () => {
const asList = {
...VPN_SETTINGS_PAYLOAD,
provider: {
...VPN_SETTINGS_PAYLOAD.provider,
port_forwarding: {
...VPN_SETTINGS_PAYLOAD.provider.port_forwarding,
listening_port: [0],
},
},
};
// The happy-path fixture already exercises the scalar form (listening_port: 0).
expect(() => gluetunVpnSettingsSchema.parse(VPN_SETTINGS_PAYLOAD)).not.toThrow();
expect(() => gluetunVpnSettingsSchema.parse(asList)).not.toThrow();
});
test("vpn settings schema accepts null wireguard addresses", () => {
const payload = {
...VPN_SETTINGS_PAYLOAD,
wireguard: {
...VPN_SETTINGS_PAYLOAD.wireguard,
addresses: null,
},
};
expect(() => gluetunVpnSettingsSchema.parse(payload)).not.toThrow();
});
}); });
@@ -14,17 +14,28 @@ interface Options<TData, TKind extends IntegrationKind, TInput extends Record<st
requestAsync: (integration: IntegrationOfKind<TKind>, input: TInput) => Promise<TData>; requestAsync: (integration: IntegrationOfKind<TKind>, input: TInput) => Promise<TData>;
} }
let integrationHandlerCounter = 0;
export const createIntegrationRequestHandler = < export const createIntegrationRequestHandler = <
TData, TData,
TKind extends IntegrationKind, TKind extends IntegrationKind,
TInput extends Record<string, unknown>, TInput extends Record<string, unknown>,
>( >(
options: Options<TData, TKind, TInput>, options: Options<TData, TKind, TInput>,
) => ({ ) => {
handler: (integration: IntegrationOfKind<TKind>, itemOptions: TInput) => { // Stable per handler definition: the inner request handler is re-created on every
const inner = createRequestHandler<TData, { integrationId: string; options: TInput }>({ // call, so without an explicit cacheKey each call would get a fresh namespace
requestAsync: async (input) => options.requestAsync(integration, input.options), // (no cache hits) — and without any namespace different handlers hitting the same
}); // integration with equal options would share cache entries and cross their data.
return inner.handler({ integrationId: integration.id, options: itemOptions }); const cacheKey = `integration-handler-${integrationHandlerCounter++}`;
},
}); return {
handler: (integration: IntegrationOfKind<TKind>, itemOptions: TInput) => {
const inner = createRequestHandler<TData, { integrationId: string; options: TInput }>({
cacheKey,
requestAsync: async (input) => options.requestAsync(integration, input.options),
});
return inner.handler({ integrationId: integration.id, options: itemOptions });
},
};
};
@@ -1,51 +1,65 @@
interface Options<TData, TInput extends Record<string, unknown>> { interface Options<TData, TInput extends Record<string, unknown>> {
requestAsync: (input: TInput) => Promise<TData>; requestAsync: (input: TInput) => Promise<TData>;
cacheTtlMs?: number; cacheTtlMs?: number;
/**
* Namespace for cache entries of this handler. Defaults to a unique id per
* createRequestHandler call. Callers that re-create handlers per request
* (e.g. createIntegrationRequestHandler) must pass a stable key themselves,
* otherwise the cache never hits.
*/
cacheKey?: string;
} }
type CacheEntry<TData> = { data: TData; timestamp: Date; expiresAt: number }; type CacheEntry<TData> = { data: TData; timestamp: Date; expiresAt: number };
const MAX_CACHE_SIZE = 1000; const MAX_CACHE_SIZE = 1000;
const cache = new Map<string, CacheEntry<unknown>>();
const inflight = new Map<string, Promise<CacheEntry<unknown>>>();
const DEFAULT_TTL_MS = 10_000; const DEFAULT_TTL_MS = 10_000;
const evictExpired = <TData>(cache: Map<string, CacheEntry<TData>>) => { const evictExpired = () => {
const now = Date.now(); const now = Date.now();
for (const [key, entry] of cache) { for (const [key, entry] of cache) {
if (now >= entry.expiresAt) cache.delete(key); if (now >= entry.expiresAt) cache.delete(key);
} }
}; };
let autoCacheKeyCounter = 0;
export const createRequestHandler = <TData, TInput extends Record<string, unknown>>( export const createRequestHandler = <TData, TInput extends Record<string, unknown>>(
options: Options<TData, TInput>, options: Options<TData, TInput>,
) => { ) => {
const cache = new Map<string, CacheEntry<TData>>(); // The cache map is shared between all handlers, so entries have to be namespaced
const inflight = new Map<string, Promise<CacheEntry<TData>>>(); // per handler — otherwise handlers receiving the same input (e.g. the same
// integrationId with empty options) would read each other's data.
const cacheKey = options.cacheKey ?? `handler-${autoCacheKeyCounter++}`;
return { return {
handler: (input: TInput) => ({ handler: (input: TInput) => ({
async getDataAsync(): Promise<{ data: TData; timestamp: Date }> { async getDataAsync(): Promise<{ data: TData; timestamp: Date }> {
const ttl = options.cacheTtlMs ?? DEFAULT_TTL_MS; const ttl = options.cacheTtlMs ?? DEFAULT_TTL_MS;
const key = JSON.stringify(input); const key = `${cacheKey}:${JSON.stringify(input)}`;
const cached = cache.get(key); const cached = cache.get(key) as CacheEntry<TData> | undefined;
if (cached && Date.now() < cached.expiresAt) { if (cached && Date.now() < cached.expiresAt) {
return { data: cached.data, timestamp: cached.timestamp }; return { data: cached.data, timestamp: cached.timestamp };
} }
if (cached) cache.delete(key); if (cached) cache.delete(key);
const existing = inflight.get(key); const existing = inflight.get(key);
if (existing) return existing; if (existing) return existing as Promise<CacheEntry<TData>>;
const promise = options const promise = options
.requestAsync(input) .requestAsync(input)
.then((data) => { .then((data) => {
if (cache.size >= MAX_CACHE_SIZE) evictExpired(cache); if (cache.size >= MAX_CACHE_SIZE) evictExpired();
if (cache.size >= MAX_CACHE_SIZE) { if (cache.size >= MAX_CACHE_SIZE) {
const oldest = cache.keys().next().value; const oldest = cache.keys().next().value;
if (oldest) cache.delete(oldest); if (oldest) cache.delete(oldest);
} }
const entry: CacheEntry<TData> = { data, timestamp: new Date(), expiresAt: Date.now() + ttl }; const entry: CacheEntry<TData> = { data, timestamp: new Date(), expiresAt: Date.now() + ttl };
cache.set(key, entry); cache.set(key, entry as CacheEntry<unknown>);
inflight.delete(key); inflight.delete(key);
return entry; return entry;
}) })
@@ -54,7 +68,7 @@ export const createRequestHandler = <TData, TInput extends Record<string, unknow
throw err; throw err;
}); });
inflight.set(key, promise); inflight.set(key, promise as Promise<CacheEntry<unknown>>);
return promise; return promise;
}, },
}), }),
+12 -12
View File
@@ -732,8 +732,8 @@
"displayType": "", "displayType": "",
"jsonPath": "", "jsonPath": "",
"jsonPathHint": "", "jsonPathHint": "",
"label": "Étiquette", "label": "",
"unit": "Unité", "unit": "",
"mappings": "", "mappings": "",
"tablePath": "", "tablePath": "",
"tablePathHint": "", "tablePathHint": "",
@@ -755,14 +755,14 @@
"striped": "", "striped": "",
"compact": "", "compact": "",
"maxHeight": "", "maxHeight": "",
"color": "Couleur", "color": "",
"buttonLabel": "", "buttonLabel": "",
"buttonColor": "", "buttonColor": "",
"confirmText": "Texte de confirmation", "confirmText": "",
"confirmTextHint": "", "confirmTextHint": "",
"successMessage": "Message de réussite", "successMessage": "",
"successMessageHint": "", "successMessageHint": "",
"enabled": "Activé", "enabled": "",
"template": { "template": {
"label": "", "label": "",
"description": "" "description": ""
@@ -1017,13 +1017,13 @@
"timetable": "", "timetable": "",
"photoService": "", "photoService": "",
"documents": "", "documents": "",
"notes": "Notes", "notes": "",
"mediaMonitoring": "Supervision", "mediaMonitoring": "",
"speedtest": "Test de débit", "speedtest": "",
"analytics": "", "analytics": "",
"vpn": "", "vpn": "",
"mediaLibrary": "Bibliothèque de médias", "mediaLibrary": "",
"uptimeMonitoring": "Surveillance des disponibilités" "uptimeMonitoring": ""
}, },
"testConnection": { "testConnection": {
"action": { "action": {
@@ -1298,7 +1298,7 @@
"newLabel": "Nouvelle clé privée" "newLabel": "Nouvelle clé privée"
}, },
"slug": { "slug": {
"label": "Slug de la page de statut", "label": "",
"newLabel": "" "newLabel": ""
} }
} }
+11 -11
View File
@@ -1599,7 +1599,7 @@
"menu": { "menu": {
"label": { "label": {
"settings": "Impostazioni", "settings": "Impostazioni",
"refresh": "Aggiorna", "refresh": "",
"options": "Opzioni", "options": "Opzioni",
"actions": "Azioni" "actions": "Azioni"
} }
@@ -1904,7 +1904,7 @@
"noStation": "Nessuna stazione selezionata", "noStation": "Nessuna stazione selezionata",
"option": { "option": {
"baseUrl": { "baseUrl": {
"label": "Url Search.ch" "label": ""
}, },
"station": { "station": {
"label": "Stazione" "label": "Stazione"
@@ -2791,8 +2791,8 @@
"description": "Visualizza la data dell'immagine e l'indice corrente nella parte inferiore della presentazione" "description": "Visualizza la data dell'immagine e l'indice corrente nella parte inferiore della presentazione"
}, },
"randomizePhotos": { "randomizePhotos": {
"label": "Immagini casuali", "label": "",
"description": "Mostra le foto in ordine casuale invece di iniziare sempre con lo stesso ordine degli album." "description": ""
} }
}, },
"description": "Presentazione delle immagini nel tuo album Immich", "description": "Presentazione delle immagini nel tuo album Immich",
@@ -3158,7 +3158,7 @@
"label": "Provider" "label": "Provider"
}, },
"providerUrl": { "providerUrl": {
"label": "URL Provider" "label": ""
}, },
"identifier": { "identifier": {
"label": "Identificatore", "label": "Identificatore",
@@ -3209,10 +3209,10 @@
"tooltip": "Impossibile analizzare il provider, impostarlo manualmente dopo aver importato le immagini" "tooltip": "Impossibile analizzare il provider, impostarlo manualmente dopo aver importato le immagini"
}, },
"tokens": { "tokens": {
"label": "Token Provider", "label": "",
"token": "Token", "token": "",
"configured": "Token configurato", "configured": "",
"notConfigured": "Nessun token impostato", "notConfigured": "",
"save": "Salva" "save": "Salva"
} }
} }
@@ -3236,9 +3236,9 @@
"invalidIdentifier": "Identificatore non valido", "invalidIdentifier": "Identificatore non valido",
"noMatchingVersion": "Nessuna versione corrispondente trovata", "noMatchingVersion": "Nessuna versione corrispondente trovata",
"noReleasesFound": "Nessun rilascio trovato", "noReleasesFound": "Nessun rilascio trovato",
"noProviderSelected": "Nessun provider selezionato", "noProviderSelected": "",
"noProviderResponse": "Nessuna risposta dal provider", "noProviderResponse": "Nessuna risposta dal provider",
"unexpected": "Errore provider inaspettato" "unexpected": ""
} }
} }
}, },
+33 -33
View File
@@ -6,9 +6,9 @@
"subtitle": "", "subtitle": "",
"description": "", "description": "",
"action": { "action": {
"scratch": "Sākt no jauna", "scratch": "",
"importOldmarr": "", "importOldmarr": "",
"restoreSqlite": "SQLite rezerves kopija", "restoreSqlite": "",
"restoreSqliteDescription": "", "restoreSqliteDescription": "",
"backToOptions": "" "backToOptions": ""
} }
@@ -26,19 +26,19 @@
} }
}, },
"importSettings": { "importSettings": {
"title": "Importēt iestatījumus", "title": "",
"description": "" "description": ""
}, },
"boardSelection": { "boardSelection": {
"title": "", "title": "",
"description": "", "description": "",
"action": { "action": {
"selectAll": "Atzīmēt visu", "selectAll": "",
"unselectAll": "" "unselectAll": ""
} }
}, },
"summary": { "summary": {
"title": "Importēšanas kopsavilkums", "title": "",
"description": "", "description": "",
"action": { "action": {
"import": "" "import": ""
@@ -46,7 +46,7 @@
"entities": { "entities": {
"apps": "Lietotnes", "apps": "Lietotnes",
"boards": "Dēļi", "boards": "Dēļi",
"integrations": "Integrācijas", "integrations": "",
"credentialUsers": "" "credentialUsers": ""
} }
}, },
@@ -67,15 +67,15 @@
} }
}, },
"user": { "user": {
"title": "Administratora lietotājs", "title": "",
"subtitle": "", "subtitle": "",
"notification": { "notification": {
"success": { "success": {
"title": "Lietotājs izveidots", "title": "",
"message": "" "message": ""
}, },
"error": { "error": {
"title": "Lietotāja izveide neizdevās" "title": ""
} }
} }
}, },
@@ -94,19 +94,19 @@
"subtitle": "" "subtitle": ""
}, },
"integrations": { "integrations": {
"title": "Integrācijas", "title": "",
"subtitle": "", "subtitle": "",
"description": "", "description": "",
"action": { "action": {
"continue": "Turpināt", "continue": "",
"skip": "Pagaidām izlaist šo soli" "skip": ""
}, },
"configure": { "configure": {
"progress": "{current} no {total}", "progress": "",
"skip": "Izlaist šo integrāciju", "skip": "",
"finishing": "", "finishing": "",
"error": { "error": {
"title": "Neizdevās iestatīt!", "title": "",
"message": "" "message": ""
}, },
"helpers": { "helpers": {
@@ -115,7 +115,7 @@
} }
}, },
"urlTemplate": { "urlTemplate": {
"label": "Bāzes URL", "label": "",
"placeholder": "", "placeholder": "",
"hint": "", "hint": "",
"warning": "", "warning": "",
@@ -136,14 +136,14 @@
} }
}, },
"finish": { "finish": {
"title": "Pabeigt Iestatīšanu", "title": "",
"subtitle": "", "subtitle": "",
"description": "", "description": "",
"action": { "action": {
"goToBoard": "", "goToBoard": "",
"createBoard": "", "createBoard": "",
"inviteUser": "Ielūgt citus lietotājus", "inviteUser": "",
"docs": "Lasīt dokumentāciju" "docs": ""
} }
} }
}, },
@@ -158,7 +158,7 @@
"subtitle": "" "subtitle": ""
}, },
"invite": { "invite": {
"title": "Pievienoties Homarr", "title": "",
"subtitle": "", "subtitle": "",
"description": "" "description": ""
}, },
@@ -177,20 +177,20 @@
}, },
"password": { "password": {
"label": "Parole", "label": "Parole",
"suggestionsTitle": "Paroles ieteikumi", "suggestionsTitle": "",
"suggestion": { "suggestion": {
"length": "Vismaz 8 rakstzīmes", "length": "",
"lowercase": "Ietver mazo burtu", "lowercase": "Ietver mazo burtu",
"uppercase": "Ietver lielo burtu", "uppercase": "Ietver lielo burtu",
"number": "Ietver numuru", "number": "Ietver numuru",
"special": "Iekļauj speciālo simbolu" "special": ""
} }
}, },
"passwordConfirm": { "passwordConfirm": {
"label": "Apstipriniet paroli" "label": "Apstipriniet paroli"
}, },
"previousPassword": { "previousPassword": {
"label": "Iepriekšējā parole" "label": ""
}, },
"homeBoard": { "homeBoard": {
"label": "" "label": ""
@@ -218,10 +218,10 @@
"notification": { "notification": {
"success": { "success": {
"title": "", "title": "",
"message": "Jūs esat veiksmīgi pieteicies" "message": ""
}, },
"error": { "error": {
"title": "Pieteikšanās neizdevās", "title": "",
"message": "" "message": ""
} }
}, },
@@ -245,13 +245,13 @@
}, },
"create": "Izveidot lietotāju", "create": "Izveidot lietotāju",
"changePassword": { "changePassword": {
"label": "Mainīt paroli", "label": "",
"notification": { "notification": {
"success": { "success": {
"message": "Parole veiksmīgi nomainīta." "message": ""
}, },
"error": { "error": {
"message": "Nav iespējams nomainīt paroli" "message": ""
} }
} }
}, },
@@ -595,12 +595,12 @@
} }
}, },
"defaultGroup": { "defaultGroup": {
"name": "Noklusētā grupa", "name": "",
"description": "" "description": ""
} }
}, },
"app": { "app": {
"search": "Atrast aplikāciju", "search": "",
"page": { "page": {
"list": { "list": {
"title": "Lietotnes", "title": "Lietotnes",
@@ -689,7 +689,7 @@
"list": { "list": {
"title": "", "title": "",
"noResults": "", "noResults": "",
"loading": "Notiek ielāde..." "loading": ""
}, },
"create": { "create": {
"title": "", "title": "",
@@ -700,7 +700,7 @@
} }
}, },
"action": { "action": {
"create": "Izveidot", "create": "",
"import": "", "import": "",
"save": "", "save": "",
"delete": "", "delete": "",
+12 -12
View File
@@ -1599,7 +1599,7 @@
"menu": { "menu": {
"label": { "label": {
"settings": "Ustawienia", "settings": "Ustawienia",
"refresh": "Odśwież", "refresh": "",
"options": "Opcje", "options": "Opcje",
"actions": "Akcje" "actions": "Akcje"
} }
@@ -1904,7 +1904,7 @@
"noStation": "Nie wybrano stacji", "noStation": "Nie wybrano stacji",
"option": { "option": {
"baseUrl": { "baseUrl": {
"label": "Szukaj adresu URL" "label": ""
}, },
"station": { "station": {
"label": "Stacja" "label": "Stacja"
@@ -2791,8 +2791,8 @@
"description": "Wyświetl datę zdjęcia oraz bieżący indeks na dole pokazu slajdów" "description": "Wyświetl datę zdjęcia oraz bieżący indeks na dole pokazu slajdów"
}, },
"randomizePhotos": { "randomizePhotos": {
"label": "Losowe zdjęcia", "label": "",
"description": "Pokaż zdjęcia w losowej kolejności, zamiast zawsze rozpoczynać się od tej samej kolejności albumu." "description": ""
} }
}, },
"description": "Pokaz slajdów zdjęć z Twojego albumu w Immich", "description": "Pokaz slajdów zdjęć z Twojego albumu w Immich",
@@ -3158,7 +3158,7 @@
"label": "Dostawca" "label": "Dostawca"
}, },
"providerUrl": { "providerUrl": {
"label": "URL dostawcy" "label": ""
}, },
"identifier": { "identifier": {
"label": "Identyfikator", "label": "Identyfikator",
@@ -3209,11 +3209,11 @@
"tooltip": "Nie udało się rozpoznać dostawcy. Ustaw go ręcznie po zaimportowaniu obrazów." "tooltip": "Nie udało się rozpoznać dostawcy. Ustaw go ręcznie po zaimportowaniu obrazów."
}, },
"tokens": { "tokens": {
"label": "Tokeny dostawcy", "label": "",
"token": "Token", "token": "",
"configured": "Token skonfigurowany", "configured": "",
"notConfigured": "Brak ustawionych tokenów", "notConfigured": "",
"save": "Zapisz" "save": ""
} }
} }
}, },
@@ -3236,9 +3236,9 @@
"invalidIdentifier": "Nieprawidłowy identyfikator", "invalidIdentifier": "Nieprawidłowy identyfikator",
"noMatchingVersion": "Nie znaleziono pasującej wersji", "noMatchingVersion": "Nie znaleziono pasującej wersji",
"noReleasesFound": "Nie znaleziono wydań!", "noReleasesFound": "Nie znaleziono wydań!",
"noProviderSelected": "Nie wybrano dostawcy", "noProviderSelected": "",
"noProviderResponse": "Brak odpowiedzi od dostawcy", "noProviderResponse": "Brak odpowiedzi od dostawcy",
"unexpected": "Nieoczekiwany błąd dostawcy" "unexpected": ""
} }
} }
}, },
+4 -4
View File
@@ -3132,7 +3132,7 @@
"label": "" "label": ""
}, },
"showOnlyIcon": { "showOnlyIcon": {
"label": "Показати тільки іконку" "label": ""
}, },
"topReleases": { "topReleases": {
"label": "", "label": "",
@@ -3229,7 +3229,7 @@
"openReleasePage": "", "openReleasePage": "",
"releaseDescription": "", "releaseDescription": "",
"projectDescription": "", "projectDescription": "",
"created": "Створено", "created": "",
"error": { "error": {
"label": "", "label": "",
"messages": { "messages": {
@@ -3350,7 +3350,7 @@
"label": "" "label": ""
} }
}, },
"latestResult": "Останній результат", "latestResult": "",
"averages": "", "averages": "",
"tests": "", "tests": "",
"recentResults": "", "recentResults": "",
@@ -3437,7 +3437,7 @@
"description": "" "description": ""
}, },
"maxNowPlayingItems": { "maxNowPlayingItems": {
"label": "Максимум елементів для відтворення", "label": "",
"description": "" "description": ""
}, },
"showLibraryCount": { "showLibraryCount": {
@@ -50,7 +50,6 @@ import {
} from "@homarr/definitions"; } from "@homarr/definitions";
import { findBestIconMatch, IconPicker } from "@homarr/forms-collection"; import { findBestIconMatch, IconPicker } from "@homarr/forms-collection";
import { createModal, useModalAction } from "@homarr/modals"; import { createModal, useModalAction } from "@homarr/modals";
import { showErrorNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client"; import { useScopedI18n } from "@homarr/translation/client";
import { MaskedImage } from "@homarr/ui"; import { MaskedImage } from "@homarr/ui";
@@ -270,24 +269,8 @@ const providersWithAuth: ReleaseProviderKind[] = [
const ProviderTokensSection = ({ itemId, repositories }: { itemId: string; repositories: ReleasesRepository[] }) => { const ProviderTokensSection = ({ itemId, repositories }: { itemId: string; repositories: ReleasesRepository[] }) => {
const tRepository = useScopedI18n("widget.releases.option.repositories"); const tRepository = useScopedI18n("widget.releases.option.repositories");
const { data: configuredKinds = [], refetch } = clientApi.widget.secrets.getConfiguredKinds.useQuery({ itemId }); const { data: configuredKinds = [], refetch } = clientApi.widget.secrets.getConfiguredKinds.useQuery({ itemId });
const setSecret = clientApi.widget.secrets.setSecret.useMutation({ const setSecret = clientApi.widget.secrets.setSecret.useMutation({ onSuccess: () => refetch() });
onSuccess: () => refetch(), const deleteSecret = clientApi.widget.secrets.deleteSecret.useMutation({ onSuccess: () => refetch() });
onError: (error) => {
showErrorNotification({
title: "Failed to save token",
message: error.message,
});
},
});
const deleteSecret = clientApi.widget.secrets.deleteSecret.useMutation({
onSuccess: () => refetch(),
onError: (error) => {
showErrorNotification({
title: "Failed to delete token",
message: error.message,
});
},
});
const authProviders = useMemo(() => { const authProviders = useMemo(() => {
const usedProviders = repositories.map((r) => r.provider).filter((p): p is ReleaseProviderKind => p !== undefined); const usedProviders = repositories.map((r) => r.provider).filter((p): p is ReleaseProviderKind => p !== undefined);
@@ -6,6 +6,7 @@ import { clientApi } from "@homarr/api/client";
import { humanFileSize } from "@homarr/common"; import { humanFileSize } from "@homarr/common";
import { getIconUrl } from "@homarr/definitions"; import { getIconUrl } from "@homarr/definitions";
import { WidgetEmptyState } from "../common/empty-state";
import type { WidgetComponentProps } from "../definition"; import type { WidgetComponentProps } from "../definition";
export default function ArchiveTeamWarriorWidget({ export default function ArchiveTeamWarriorWidget({
@@ -28,7 +29,9 @@ const ArchiveTeamWarriorWidgetContent = ({
integrationId: string; integrationId: string;
options: WidgetComponentProps<"archiveTeamWarrior">["options"]; options: WidgetComponentProps<"archiveTeamWarrior">["options"];
}) => { }) => {
const [data] = clientApi.widget.archiveTeamWarrior.getStatus.useSuspenseQuery({ integrationId }); const { data } = clientApi.widget.archiveTeamWarrior.getStatus.useQuery({ integrationId });
if (!data) return <WidgetEmptyState />;
const status = data.status; const status = data.status;
const projectName = status.project?.title ?? status.selectedProject ?? "No project selected"; const projectName = status.project?.title ?? status.selectedProject ?? "No project selected";
@@ -46,7 +46,7 @@ export function AudioStatsContent({ backend, stats, options, width }: AudioStats
}; };
const navidromeStats = navidromeStatsByBackend[backend]; const navidromeStats = navidromeStatsByBackend[backend];
const showNowPlayingSection = const showNowPlayingSection =
navidromeStats !== null && Boolean(options.showNowPlaying) && navidromeStats.nowPlaying.length > 0; navidromeStats !== null && Boolean(options.showNowPlaying) && (navidromeStats.nowPlaying ?? []).length > 0;
const nowPlayingLimitByListVisibility = { const nowPlayingLimitByListVisibility = {
true: options.maxNowPlayingItems ?? 3, true: options.maxNowPlayingItems ?? 3,
@@ -54,7 +54,7 @@ export function AudioStatsContent({ backend, stats, options, width }: AudioStats
} as const; } as const;
const nowPlayingTracks = const nowPlayingTracks =
navidromeStats?.nowPlaying.slice( (navidromeStats?.nowPlaying ?? []).slice(
0, 0,
nowPlayingLimitByListVisibility[ nowPlayingLimitByListVisibility[
String(options.showNowPlayingList) as keyof typeof nowPlayingLimitByListVisibility String(options.showNowPlayingList) as keyof typeof nowPlayingLimitByListVisibility
@@ -54,12 +54,12 @@ export default function BeszelAlertsWidget({
}, [results]); }, [results]);
const alerts = useMemo( const alerts = useMemo(
() => results.flatMap((r) => r.alerts.map((a) => ({ ...a, _key: `${r.integrationId}:${a.id}` }))), () => results.flatMap((r) => (r.alerts ?? []).map((a) => ({ ...a, _key: `${r.integrationId}:${a.id}` }))),
[results], [results],
); );
const history = useMemo(() => { const history = useMemo(() => {
const all = results.flatMap((r) => r.history.map((h) => ({ ...h, _key: `${r.integrationId}:${h.id}` }))); const all = results.flatMap((r) => (r.history ?? []).map((h) => ({ ...h, _key: `${r.integrationId}:${h.id}` })));
return all return all
.toSorted((a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()) .toSorted((a, b) => new Date(b.created).getTime() - new Date(a.created).getTime())
.slice(0, options.maxHistoryItems); .slice(0, options.maxHistoryItems);
@@ -70,7 +70,7 @@ export default function BeszelSystemStatsWidget({
} = clientApi.widget.beszel.getSystems.useQuery({ integrationIds }); } = clientApi.widget.beszel.getSystems.useQuery({ integrationIds });
const systems = useMemo( const systems = useMemo(
() => systemsResult.flatMap((r) => r.systems.map((s) => ({ value: s.id, label: s.name }))), () => systemsResult.flatMap((r) => (r.systems ?? []).map((s) => ({ value: s.id, label: s.name }))),
[systemsResult], [systemsResult],
); );
@@ -29,7 +29,7 @@ export const { definition, componentLoader } = createWidgetDefinition("beszelSys
isPending, isPending,
isError, isError,
} = clientApi.widget.beszel.getSystems.useQuery({ integrationIds }, { enabled: integrationIds.length > 0 }); } = clientApi.widget.beszel.getSystems.useQuery({ integrationIds }, { enabled: integrationIds.length > 0 });
const selectData = data.flatMap((r) => r.systems.map((s) => ({ value: s.id, label: s.name }))); const selectData = data.flatMap((r) => (r.systems ?? []).map((s) => ({ value: s.id, label: s.name })));
return { data: selectData, isPending, isError }; return { data: selectData, isPending, isError };
}, },
}), }),
@@ -187,7 +187,7 @@ export const useDockerChartData = (
const { fmt, ordered } = prepareRecords(containerStats, timePeriod); const { fmt, ordered } = prepareRecords(containerStats, timePeriod);
const mapped = ordered.map((record) => { const mapped = ordered.map((record) => {
const point: Record<string, unknown> = { time: fmt(record.created), rawTime: record.created }; const point: Record<string, unknown> = { time: fmt(record.created), rawTime: record.created };
const byName = new Map(record.stats.map((c) => [c.n, c])); const byName = new Map((record.stats ?? []).map((c) => [c.n, c]));
for (const name of containerNames) { for (const name of containerNames) {
point[name] = extract(byName.get(name)); point[name] = extract(byName.get(name));
} }
+2 -2
View File
@@ -13,8 +13,8 @@ export const useBeszelFilteredSystems = (
const allSystems = useMemo( const allSystems = useMemo(
() => () =>
results results
.flatMap((r) => r.systems.map((s) => ({ ...s, _key: `${r.integrationId}:${s.id}` }))) .flatMap((r) => (r.systems ?? []).map((s) => ({ ...s, _key: `${r.integrationId}:${s.id}` })))
.toSorted((a, b) => a.name.localeCompare(b.name)), .toSorted((a, b) => (a.name ?? "").localeCompare(b.name ?? "")),
[results], [results],
); );
+1 -1
View File
@@ -137,7 +137,7 @@ const CalendarBase = ({ isEditMode, events, month, setMonth, options }: Calendar
.filter( .filter(
(event) => event.metadata?.type !== "radarr" || options.releaseType.includes(event.metadata.releaseType), (event) => event.metadata?.type !== "radarr" || options.releaseType.includes(event.metadata.releaseType),
) )
.toSorted((eventA, eventB) => eventA.startDate.getTime() - eventB.startDate.getTime()); .toSorted((eventA, eventB) => new Date(eventA.startDate).getTime() - new Date(eventB.startDate).getTime());
return ( return (
<CalendarDay <CalendarDay
+17 -31
View File
@@ -32,22 +32,18 @@ export function InstanceCard({ instance, options, isTiny, widgetKey }: InstanceC
defaultValue: ["applications"], defaultValue: ["applications"],
}); });
const serverResourceCounts = buildServerResourceCounts( const servers = instance.instanceInfo.servers ?? [];
instance.instanceInfo.servers, const applications = instance.instanceInfo.applications ?? [];
instance.instanceInfo.applications, const services = instance.instanceInfo.services ?? [];
instance.instanceInfo.services,
); const serverResourceCounts = buildServerResourceCounts(servers, applications, services);
const baseUrl = instance.integrationUrl.replace(/\/+$/, ""); const baseUrl = instance.integrationUrl.replace(/\/+$/, "");
const relativeTime = useTimeAgo(instance.updatedAt); const relativeTime = useTimeAgo(instance.updatedAt);
const onlineServers = instance.instanceInfo.servers.filter((s) => s.is_reachable !== false).length; const onlineServers = servers.filter((s) => s.is_reachable !== false).length;
const runningApps = instance.instanceInfo.applications.filter( const runningApps = applications.filter((a) => parseStatus(a.status ?? "") === "running").length;
(a) => parseStatus(a.status ?? "") === "running", const runningServices = services.filter((s) => parseStatus(s.status ?? "") === "running").length;
).length;
const runningServices = instance.instanceInfo.services.filter(
(s) => parseStatus(s.status ?? "") === "running",
).length;
return ( return (
<Card p={0} radius="sm"> <Card p={0} radius="sm">
@@ -65,26 +61,18 @@ export function InstanceCard({ instance, options, isTiny, widgetKey }: InstanceC
</Group> </Group>
<Group gap={4} wrap="nowrap"> <Group gap={4} wrap="nowrap">
{options.showServers && ( {options.showServers && (
<Badge variant="dot" color={getBadgeColor(onlineServers, instance.instanceInfo.servers.length)} size="xs"> <Badge variant="dot" color={getBadgeColor(onlineServers, servers.length)} size="xs">
{onlineServers}/{instance.instanceInfo.servers.length} {onlineServers}/{servers.length}
</Badge> </Badge>
)} )}
{options.showApplications && ( {options.showApplications && (
<Badge <Badge variant="dot" color={getBadgeColor(runningApps, applications.length)} size="xs">
variant="dot" {runningApps}/{applications.length}
color={getBadgeColor(runningApps, instance.instanceInfo.applications.length)}
size="xs"
>
{runningApps}/{instance.instanceInfo.applications.length}
</Badge> </Badge>
)} )}
{options.showServices && ( {options.showServices && (
<Badge <Badge variant="dot" color={getBadgeColor(runningServices, services.length)} size="xs">
variant="dot" {runningServices}/{services.length}
color={getBadgeColor(runningServices, instance.instanceInfo.services.length)}
size="xs"
>
{runningServices}/{instance.instanceInfo.services.length}
</Badge> </Badge>
)} )}
</Group> </Group>
@@ -93,7 +81,7 @@ export function InstanceCard({ instance, options, isTiny, widgetKey }: InstanceC
<Accordion variant="filled" chevronPosition="right" multiple value={openSections} onChange={setOpenSections}> <Accordion variant="filled" chevronPosition="right" multiple value={openSections} onChange={setOpenSections}>
{options.showServers && ( {options.showServers && (
<ServersSection <ServersSection
servers={instance.instanceInfo.servers} servers={servers}
serverResourceCounts={serverResourceCounts} serverResourceCounts={serverResourceCounts}
baseUrl={baseUrl} baseUrl={baseUrl}
isTiny={isTiny} isTiny={isTiny}
@@ -102,11 +90,9 @@ export function InstanceCard({ instance, options, isTiny, widgetKey }: InstanceC
/> />
)} )}
{options.showApplications && ( {options.showApplications && (
<ApplicationsSection applications={instance.instanceInfo.applications} baseUrl={baseUrl} isTiny={isTiny} /> <ApplicationsSection applications={applications} baseUrl={baseUrl} isTiny={isTiny} />
)}
{options.showServices && (
<ServicesSection services={instance.instanceInfo.services} baseUrl={baseUrl} isTiny={isTiny} />
)} )}
{options.showServices && <ServicesSection services={services} baseUrl={baseUrl} isTiny={isTiny} />}
</Accordion> </Accordion>
<Group justify="space-between" p={4} style={{ borderTop: "1px solid var(--mantine-color-dark-4)" }}> <Group justify="space-between" p={4} style={{ borderTop: "1px solid var(--mantine-color-dark-4)" }}>
@@ -31,11 +31,11 @@ export function SingleInstanceLayout({ instance, options, isTiny, widgetKey }: S
defaultValue: ["applications"], defaultValue: ["applications"],
}); });
const serverResourceCounts = buildServerResourceCounts( const servers = instance.instanceInfo.servers ?? [];
instance.instanceInfo.servers, const applications = instance.instanceInfo.applications ?? [];
instance.instanceInfo.applications, const services = instance.instanceInfo.services ?? [];
instance.instanceInfo.services,
); const serverResourceCounts = buildServerResourceCounts(servers, applications, services);
const baseUrl = instance.integrationUrl.replace(/\/+$/, ""); const baseUrl = instance.integrationUrl.replace(/\/+$/, "");
const displayUrl = baseUrl.replace(/^https?:\/\//, ""); const displayUrl = baseUrl.replace(/^https?:\/\//, "");
@@ -59,7 +59,7 @@ export function SingleInstanceLayout({ instance, options, isTiny, widgetKey }: S
<Accordion variant="contained" chevronPosition="right" multiple value={openSections} onChange={setOpenSections}> <Accordion variant="contained" chevronPosition="right" multiple value={openSections} onChange={setOpenSections}>
{options.showServers && ( {options.showServers && (
<ServersSection <ServersSection
servers={instance.instanceInfo.servers} servers={servers}
serverResourceCounts={serverResourceCounts} serverResourceCounts={serverResourceCounts}
baseUrl={baseUrl} baseUrl={baseUrl}
isTiny={isTiny} isTiny={isTiny}
@@ -68,11 +68,9 @@ export function SingleInstanceLayout({ instance, options, isTiny, widgetKey }: S
/> />
)} )}
{options.showApplications && ( {options.showApplications && (
<ApplicationsSection applications={instance.instanceInfo.applications} baseUrl={baseUrl} isTiny={isTiny} /> <ApplicationsSection applications={applications} baseUrl={baseUrl} isTiny={isTiny} />
)}
{options.showServices && (
<ServicesSection services={instance.instanceInfo.services} baseUrl={baseUrl} isTiny={isTiny} />
)} )}
{options.showServices && <ServicesSection services={services} baseUrl={baseUrl} isTiny={isTiny} />}
</Accordion> </Accordion>
<Group <Group
+5 -3
View File
@@ -104,7 +104,9 @@ export default function DownloadClientsWidget({
const [quickFilters, setQuickFilters] = useState<QuickFilter>({ integrationKinds: [], statuses: [] }); const [quickFilters, setQuickFilters] = useState<QuickFilter>({ integrationKinds: [], statuses: [] });
const availableStatuses = useMemo<QuickFilter["statuses"]>(() => { const availableStatuses = useMemo<QuickFilter["statuses"]>(() => {
//Redefine list of available statuses from current items //Redefine list of available statuses from current items
const statuses = Array.from(new Set(currentItems.flatMap(({ data }) => data.items.map(({ state }) => state)))); const statuses = Array.from(
new Set(currentItems.flatMap(({ data }) => (data.items ?? []).map(({ state }) => state))),
);
//Reset user filters accordingly to remove unavailable statuses //Reset user filters accordingly to remove unavailable statuses
setQuickFilters(({ integrationKinds: names, statuses: prevStatuses }) => { setQuickFilters(({ integrationKinds: names, statuses: prevStatuses }) => {
return { integrationKinds: names, statuses: prevStatuses.filter((status) => statuses.includes(status)) }; return { integrationKinds: names, statuses: prevStatuses.filter((status) => statuses.includes(status)) };
@@ -127,7 +129,7 @@ export default function DownloadClientsWidget({
//Construct normalized items list //Construct normalized items list
.flatMap((pair) => .flatMap((pair) =>
//Apply user white/black list //Apply user white/black list
pair.data.items (pair.data.items ?? [])
.filter( .filter(
({ category }) => ({ category }) =>
options.filterIsWhitelist === options.filterIsWhitelist ===
@@ -202,7 +204,7 @@ export default function DownloadClientsWidget({
const interact = integrationsWithInteractions.includes(integration.id); const interact = integrationsWithInteractions.includes(integration.id);
const isTorrent = getIntegrationKindsByCategory("torrent").some((kind) => kind === integration.kind); const isTorrent = getIntegrationKindsByCategory("torrent").some((kind) => kind === integration.kind);
/** Derived from current items */ /** Derived from current items */
const { totalUp, totalDown } = data.items const { totalUp, totalDown } = (data.items ?? [])
.filter( .filter(
({ category }) => ({ category }) =>
!options.applyFilterToRatio || !options.applyFilterToRatio ||
@@ -41,19 +41,21 @@ export const ClusterHealthMonitoring = ({
if (!healthData) return <WidgetEmptyState />; if (!healthData) return <WidgetEmptyState />;
const activeNodes = healthData.nodes.reduce(running, 0); const nodes = healthData.nodes ?? [];
const activeVMs = healthData.vms.reduce(running, 0); const vms = healthData.vms ?? [];
const activeLXCs = healthData.lxcs.reduce(running, 0); const lxcs = healthData.lxcs ?? [];
const activeStorage = healthData.storages.reduce(running, 0); const storages = healthData.storages ?? [];
const usedMem = healthData.nodes.reduce((sum, item) => (item.isRunning ? item.memory.used + sum : sum), 0); const activeNodes = nodes.reduce(running, 0);
const maxMem = healthData.nodes.reduce((sum, item) => (item.isRunning ? item.memory.total + sum : sum), 0); const activeVMs = vms.reduce(running, 0);
const maxCpu = healthData.nodes.reduce((sum, item) => (item.isRunning ? item.cpu.cores + sum : sum), 0); const activeLXCs = lxcs.reduce(running, 0);
const usedCpu = healthData.nodes.reduce( const activeStorage = storages.reduce(running, 0);
(sum, item) => (item.isRunning ? item.cpu.utilization * item.cpu.cores + sum : sum),
0, const usedMem = nodes.reduce((sum, item) => (item.isRunning ? item.memory.used + sum : sum), 0);
); const maxMem = nodes.reduce((sum, item) => (item.isRunning ? item.memory.total + sum : sum), 0);
const uptime = healthData.nodes.reduce((sum, { uptime }) => (sum > uptime ? sum : uptime), 0); const maxCpu = nodes.reduce((sum, item) => (item.isRunning ? item.cpu.cores + sum : sum), 0);
const usedCpu = nodes.reduce((sum, item) => (item.isRunning ? item.cpu.utilization * item.cpu.cores + sum : sum), 0);
const uptime = nodes.reduce((sum, { uptime }) => (sum > uptime ? sum : uptime), 0);
const cpuPercent = maxCpu ? (usedCpu / maxCpu) * 100 : 0; const cpuPercent = maxCpu ? (usedCpu / maxCpu) * 100 : 0;
const memPercent = maxMem ? (usedMem / maxMem) * 100 : 0; const memPercent = maxMem ? (usedMem / maxMem) * 100 : 0;
@@ -89,12 +91,12 @@ export const ClusterHealthMonitoring = ({
icon={IconServer} icon={IconServer}
badge={addBadgeColor({ badge={addBadgeColor({
activeCount: activeNodes, activeCount: activeNodes,
totalCount: healthData.nodes.length, totalCount: nodes.length,
sectionIndicatorRequirement: options.sectionIndicatorRequirement, sectionIndicatorRequirement: options.sectionIndicatorRequirement,
})} })}
isTiny={isTiny} isTiny={isTiny}
> >
<ResourceTable type="node" data={healthData.nodes} isTiny={isTiny} /> <ResourceTable type="node" data={nodes} isTiny={isTiny} />
</ResourceAccordionItem> </ResourceAccordionItem>
)} )}
@@ -105,12 +107,12 @@ export const ClusterHealthMonitoring = ({
icon={IconDeviceLaptop} icon={IconDeviceLaptop}
badge={addBadgeColor({ badge={addBadgeColor({
activeCount: activeVMs, activeCount: activeVMs,
totalCount: healthData.vms.length, totalCount: vms.length,
sectionIndicatorRequirement: options.sectionIndicatorRequirement, sectionIndicatorRequirement: options.sectionIndicatorRequirement,
})} })}
isTiny={isTiny} isTiny={isTiny}
> >
<ResourceTable type="qemu" data={healthData.vms} isTiny={isTiny} /> <ResourceTable type="qemu" data={vms} isTiny={isTiny} />
</ResourceAccordionItem> </ResourceAccordionItem>
)} )}
@@ -121,12 +123,12 @@ export const ClusterHealthMonitoring = ({
icon={IconCube} icon={IconCube}
badge={addBadgeColor({ badge={addBadgeColor({
activeCount: activeLXCs, activeCount: activeLXCs,
totalCount: healthData.lxcs.length, totalCount: lxcs.length,
sectionIndicatorRequirement: options.sectionIndicatorRequirement, sectionIndicatorRequirement: options.sectionIndicatorRequirement,
})} })}
isTiny={isTiny} isTiny={isTiny}
> >
<ResourceTable type="lxc" data={healthData.lxcs} isTiny={isTiny} /> <ResourceTable type="lxc" data={lxcs} isTiny={isTiny} />
</ResourceAccordionItem> </ResourceAccordionItem>
)} )}
@@ -137,12 +139,12 @@ export const ClusterHealthMonitoring = ({
icon={IconDatabase} icon={IconDatabase}
badge={addBadgeColor({ badge={addBadgeColor({
activeCount: activeStorage, activeCount: activeStorage,
totalCount: healthData.storages.length, totalCount: storages.length,
sectionIndicatorRequirement: options.sectionIndicatorRequirement, sectionIndicatorRequirement: options.sectionIndicatorRequirement,
})} })}
isTiny={isTiny} isTiny={isTiny}
> >
<ResourceTable type="storage" data={healthData.storages} isTiny={isTiny} /> <ResourceTable type="storage" data={storages} isTiny={isTiny} />
</ResourceAccordionItem> </ResourceAccordionItem>
)} )}
</Accordion> </Accordion>
@@ -65,7 +65,7 @@ export const SystemHealthMonitoring = ({
return ( return (
<Stack h="100%" gap="sm" className="health-monitoring"> <Stack h="100%" gap="sm" className="health-monitoring">
{healthData.map(({ integrationId, integrationName, healthInfo }) => { {healthData.map(({ integrationId, integrationName, healthInfo }) => {
const disksData = matchFileSystemAndSmart(healthInfo.fileSystem, healthInfo.smart); const disksData = matchFileSystemAndSmart(healthInfo.fileSystem ?? [], healthInfo.smart ?? []);
const memoryUsage = formatMemoryUsage(healthInfo.memAvailableInBytes, healthInfo.memUsedInBytes); const memoryUsage = formatMemoryUsage(healthInfo.memAvailableInBytes, healthInfo.memUsedInBytes);
return ( return (
<Stack <Stack
@@ -165,7 +165,7 @@ export const SystemHealthMonitoring = ({
/> />
)} )}
{options.gpu && {options.gpu &&
healthInfo.gpu.map((gpu) => ( (healthInfo.gpu ?? []).map((gpu) => (
<GpuRing key={gpu.gpuId} gpu={gpu} isTiny={isTiny} fahrenheit={options.fahrenheit} /> <GpuRing key={gpu.gpuId} gpu={gpu} isTiny={isTiny} fahrenheit={options.fahrenheit} />
))} ))}
</Flex> </Flex>
@@ -301,5 +301,5 @@ export const matchFileSystemAndSmart = (fileSystems: FileSystem[], smartData: Sm
overallStatus: smartDisk?.overallStatus ?? "", overallStatus: smartDisk?.overallStatus ?? "",
}; };
}) })
.toSorted((fileSystemA, fileSystemB) => fileSystemA.deviceName.localeCompare(fileSystemB.deviceName)); .toSorted((fileSystemA, fileSystemB) => (fileSystemA.deviceName ?? "").localeCompare(fileSystemB.deviceName ?? ""));
}; };
@@ -65,7 +65,7 @@ export default function IndexerManagerWidget({
<ScrollArea className="indexer-manager-list-scroll-area" h="100%" scrollbars="y"> <ScrollArea className="indexer-manager-list-scroll-area" h="100%" scrollbars="y">
{indexersData.map(({ integrationId, indexers }) => ( {indexersData.map(({ integrationId, indexers }) => (
<Stack gap={4} className={`indexer-manager-${integrationId}-list-container`} p={0} key={integrationId}> <Stack gap={4} className={`indexer-manager-${integrationId}-list-container`} p={0} key={integrationId}>
{indexers.map((indexer) => ( {(indexers ?? []).map((indexer) => (
<Group <Group
className={`indexer-manager-line indexer-manager-${indexer.name}`} className={`indexer-manager-line indexer-manager-${indexer.name}`}
key={indexer.id} key={indexer.id}
@@ -80,7 +80,7 @@ const Item = ({ item, options }: ItemProps) => {
top={0} top={0}
left={0} left={0}
style={{ style={{
backgroundImage: `url(${item.imageUrls.backdrop})`, backgroundImage: `url(${item.imageUrls?.backdrop})`,
borderRadius: 8, borderRadius: 8,
backgroundRepeat: "no-repeat", backgroundRepeat: "no-repeat",
backgroundSize: "cover", backgroundSize: "cover",
@@ -91,7 +91,7 @@ const Item = ({ item, options }: ItemProps) => {
)} )}
<Group justify="space-between" h="100%" wrap="nowrap"> <Group justify="space-between" h="100%" wrap="nowrap">
<Group align="start" wrap="nowrap" style={{ zIndex: 0 }}> <Group align="start" wrap="nowrap" style={{ zIndex: 0 }}>
{options.layout === "poster" && <Image w={60} src={item.imageUrls.poster} alt={item.title} />} {options.layout === "poster" && <Image w={60} src={item.imageUrls?.poster} alt={item.title} />}
<Stack gap={4}> <Stack gap={4}>
<Stack gap={0}> <Stack gap={0}>
<Text size="sm" fw="bold" lineClamp={2}> <Text size="sm" fw="bold" lineClamp={2}>
@@ -130,7 +130,7 @@ const Item = ({ item, options }: ItemProps) => {
</> </>
)} )}
</Group> </Group>
{item.tags.length > 0 && ( {(item.tags ?? []).length > 0 && (
<OverflowBadge <OverflowBadge
size="xs" size="xs"
groupGap={4} groupGap={4}
@@ -43,48 +43,49 @@ export default function MediaServerWidget({
const board = useRequiredBoard(); const board = useRequiredBoard();
if (!requestStats) return <WidgetEmptyState />; if (!requestStats) return <WidgetEmptyState />;
if (requestStats.users.length === 0 && requestStats.stats.length === 0) throw new NoIntegrationDataError(); if ((requestStats.users ?? []).length === 0 && (requestStats.stats ?? []).length === 0)
throw new NoIntegrationDataError();
const data = [ const data = [
{ {
name: "approved", name: "approved",
icon: IconThumbUp, icon: IconThumbUp,
number: requestStats.stats.reduce((count, { approved }) => count + approved, 0), number: (requestStats.stats ?? []).reduce((count, { approved }) => count + approved, 0),
}, },
{ {
name: "pending", name: "pending",
icon: IconHourglass, icon: IconHourglass,
number: requestStats.stats.reduce((count, { pending }) => count + pending, 0), number: (requestStats.stats ?? []).reduce((count, { pending }) => count + pending, 0),
}, },
{ {
name: "processing", name: "processing",
icon: IconLoaderQuarter, icon: IconLoaderQuarter,
number: requestStats.stats.reduce((count, { processing }) => count + processing, 0), number: (requestStats.stats ?? []).reduce((count, { processing }) => count + processing, 0),
}, },
{ {
name: "declined", name: "declined",
icon: IconThumbDown, icon: IconThumbDown,
number: requestStats.stats.reduce((count, { declined }) => count + declined, 0), number: (requestStats.stats ?? []).reduce((count, { declined }) => count + declined, 0),
}, },
{ {
name: "available", name: "available",
icon: IconPlayerPlay, icon: IconPlayerPlay,
number: requestStats.stats.reduce((count, { available }) => count + available, 0), number: (requestStats.stats ?? []).reduce((count, { available }) => count + available, 0),
}, },
{ {
name: "tv", name: "tv",
icon: IconDeviceTv, icon: IconDeviceTv,
number: requestStats.stats.reduce((count, { tv }) => count + tv, 0), number: (requestStats.stats ?? []).reduce((count, { tv }) => count + tv, 0),
}, },
{ {
name: "movie", name: "movie",
icon: IconMovie, icon: IconMovie,
number: requestStats.stats.reduce((count, { movie }) => count + movie, 0), number: (requestStats.stats ?? []).reduce((count, { movie }) => count + movie, 0),
}, },
{ {
name: "total", name: "total",
icon: IconReceipt, icon: IconReceipt,
number: requestStats.stats.reduce((count, { total }) => count + total, 0), number: (requestStats.stats ?? []).reduce((count, { total }) => count + total, 0),
}, },
] satisfies { name: keyof RequestStats; icon: Icon; number: number }[]; ] satisfies { name: keyof RequestStats; icon: Icon; number: number }[];
@@ -132,7 +133,7 @@ export default function MediaServerWidget({
{t("titles.users.main")} ({t("titles.users.requests")}) {t("titles.users.main")} ({t("titles.users.requests")})
</Text> </Text>
<Stack className="mediaRequests-stats-users-wrapper" flex={1} w="100%" gap={4} style={{ overflow: "hidden" }}> <Stack className="mediaRequests-stats-users-wrapper" flex={1} w="100%" gap={4} style={{ overflow: "hidden" }}>
{requestStats.users.slice(0, 10).map((user) => ( {(requestStats.users ?? []).slice(0, 10).map((user) => (
<Card <Card
component="a" component="a"
href={user.link} href={user.link}
@@ -76,7 +76,7 @@ export default function MediaServerWidget({ options, integrationIds }: WidgetCom
const flatSessions = useMemo( const flatSessions = useMemo(
() => () =>
currentStreams.flatMap((pair) => currentStreams.flatMap((pair) =>
pair.sessions.map((session) => ({ (pair.sessions ?? []).map((session) => ({
...session, ...session,
integrationKind: pair.integrationKind, integrationKind: pair.integrationKind,
integrationName: integrationDefs[pair.integrationKind].name, integrationName: integrationDefs[pair.integrationKind].name,
@@ -27,7 +27,7 @@ export function QueuePanel(props: QueuePanelProps) {
const t = useI18n("widget.mediaTranscoding.panel.queue"); const t = useI18n("widget.mediaTranscoding.panel.queue");
if (queue.array.length === 0) { if ((queue.array ?? []).length === 0) {
return ( return (
<Center style={{ flex: "1" }}> <Center style={{ flex: "1" }}>
<Title order={6}>{t("empty")}</Title> <Title order={6}>{t("empty")}</Title>
@@ -53,7 +53,7 @@ export function QueuePanel(props: QueuePanelProps) {
</TableTr> </TableTr>
</TableThead> </TableThead>
<TableTbody> <TableTbody>
{queue.array.map((item) => ( {(queue.array ?? []).map((item) => (
<TableTr key={item.id}> <TableTr key={item.id}>
<TableTd py={2}> <TableTd py={2}>
<Group gap={4} wrap="nowrap"> <Group gap={4} wrap="nowrap">
@@ -26,7 +26,7 @@ interface WorkersPanelProps {
export function WorkersPanel(props: WorkersPanelProps) { export function WorkersPanel(props: WorkersPanelProps) {
const t = useI18n("widget.mediaTranscoding.panel.workers"); const t = useI18n("widget.mediaTranscoding.panel.workers");
if (props.workers.length === 0) { if ((props.workers ?? []).length === 0) {
return ( return (
<Center style={{ flex: "1" }}> <Center style={{ flex: "1" }}>
<Title order={6}>{t("empty")}</Title> <Title order={6}>{t("empty")}</Title>
@@ -25,19 +25,19 @@ export default function NetworkControllerNetworkStatusWidget({
integrationIds, integrationIds,
}); });
const data = useMemo(() => summaries.flatMap(({ summary }) => summary), [summaries]); const data = useMemo(() => summaries.flatMap(({ summary }) => (summary ? [summary] : [])), [summaries]);
return ( return (
<Box p={"sm"}> <Box p={"sm"}>
{options.content === "wifi" ? ( {options.content === "wifi" ? (
<WifiVariant <WifiVariant
countGuests={data.reduce((sum, summary) => sum + summary.wifi.guests, 0)} countGuests={data.reduce((sum, summary) => sum + (summary.wifi?.guests ?? 0), 0)}
countUsers={data.reduce((sum, summary) => sum + summary.wifi.users, 0)} countUsers={data.reduce((sum, summary) => sum + (summary.wifi?.users ?? 0), 0)}
/> />
) : ( ) : (
<WiredVariant <WiredVariant
countGuests={data.reduce((sum, summary) => sum + summary.lan.guests, 0)} countGuests={data.reduce((sum, summary) => sum + (summary.lan?.guests ?? 0), 0)}
countUsers={data.reduce((sum, summary) => sum + summary.lan.users, 0)} countUsers={data.reduce((sum, summary) => sum + (summary.lan?.users ?? 0), 0)}
/> />
)} )}
</Box> </Box>
@@ -24,8 +24,8 @@ export default function NotificationsWidget({ options, integrationIds }: WidgetC
const sortedNotifications = useMemo( const sortedNotifications = useMemo(
() => () =>
notificationIntegrations notificationIntegrations
.flatMap((integration) => integration.data) .flatMap((integration) => integration.data ?? [])
.sort((entryA, entryB) => entryB.time.getTime() - entryA.time.getTime()), .sort((a, b) => (b.time?.getTime?.() ?? 0) - (a.time?.getTime?.() ?? 0)),
[notificationIntegrations], [notificationIntegrations],
); );
@@ -24,7 +24,7 @@ export default function SpeedtestTrackerWidget({ options, integrationIds }: Widg
(acc, item) => ({ (acc, item) => ({
latestResult: item.dashboard.latestResult ?? acc.latestResult, latestResult: item.dashboard.latestResult ?? acc.latestResult,
stats: mergeStats(acc.stats, item.dashboard.stats), stats: mergeStats(acc.stats, item.dashboard.stats),
recentResults: [...acc.recentResults, ...item.dashboard.recentResults], recentResults: [...acc.recentResults, ...(item.dashboard.recentResults ?? [])],
}), }),
{ latestResult: null, stats: null, recentResults: [] }, { latestResult: null, stats: null, recentResults: [] },
), ),
@@ -32,7 +32,9 @@ export default function SpeedtestTrackerWidget({ options, integrationIds }: Widg
); );
const twelveHoursAgo = Date.now() - 12 * 60 * 60 * 1000; const twelveHoursAgo = Date.now() - 12 * 60 * 60 * 1000;
const recentFiltered = combined.recentResults.filter((result) => result.created_at.getTime() > twelveHoursAgo); const recentFiltered = combined.recentResults.filter(
(result) => new Date(result.created_at).getTime() > twelveHoursAgo,
);
const hasStatSection = const hasStatSection =
(options.showLatestResult && combined.latestResult !== null) || (options.showStats && combined.stats !== null); (options.showLatestResult && combined.latestResult !== null) || (options.showStats && combined.stats !== null);
@@ -40,7 +40,7 @@ function buildXAxisTicks(data: { ts: number }[]): XAxisTicks {
return { return {
midnightTs: foundMidnight, midnightTs: foundMidnight,
xTicks: Array.from(tickSet).sort((tsA, tsB) => tsA - tsB), xTicks: Array.from(tickSet).toSorted((tsA, tsB) => tsA - tsB),
topDateTicks: topTicks, topDateTicks: topTicks,
}; };
} }
@@ -161,10 +161,10 @@ function SpeedHistoryChart({ results, height }: { results: SpeedtestTrackerResul
const data = useMemo( const data = useMemo(
() => () =>
[...results] [...results]
.sort((resultA, resultB) => resultA.created_at.getTime() - resultB.created_at.getTime()) .toSorted((resultA, resultB) => new Date(resultA.created_at).getTime() - new Date(resultB.created_at).getTime())
.filter((result) => (result.download_bits ?? 0) > 0) .filter((result) => (result.download_bits ?? 0) > 0)
.map((result) => ({ .map((result) => ({
ts: result.created_at.getTime(), ts: new Date(result.created_at).getTime(),
Download: parseFloat(((result.download_bits ?? 0) / 1_000_000).toFixed(2)), Download: parseFloat(((result.download_bits ?? 0) / 1_000_000).toFixed(2)),
Upload: Upload:
result.upload_bits != null && result.upload_bits > 0 result.upload_bits != null && result.upload_bits > 0
@@ -273,12 +273,12 @@ function PingHistoryChart({ results, height }: { results: SpeedtestTrackerResult
const data = useMemo( const data = useMemo(
() => () =>
[...results] [...results]
.sort((resultA, resultB) => resultA.created_at.getTime() - resultB.created_at.getTime()) .toSorted((resultA, resultB) => new Date(resultA.created_at).getTime() - new Date(resultB.created_at).getTime())
.map((result) => .map((result) =>
result.ping === null result.ping === null
? null ? null
: { : {
ts: result.created_at.getTime(), ts: new Date(result.created_at).getTime(),
Ping: result.ping, Ping: result.ping,
}, },
) )
+3 -2
View File
@@ -35,8 +35,9 @@ export default function StockPriceWidget({ options, width, height }: WidgetCompo
calculateChangePercentage(data.priceHistory.at(-1) ?? 0, data.previousClose), calculateChangePercentage(data.priceHistory.at(-1) ?? 0, data.previousClose),
); );
const stockValuesMin = Math.min(...data.priceHistory); const priceHistory = data.priceHistory ?? [];
const stockGraphValues = data.priceHistory.map((value) => value - stockValuesMin + 50); const stockValuesMin = priceHistory.length > 0 ? Math.min(...priceHistory) : 0;
const stockGraphValues = priceHistory.map((value) => value - stockValuesMin + 50);
const trendColor = stockValuesChange > 0 ? "green.7" : stockValuesChange < 0 ? "red.7" : "gray.6"; const trendColor = stockValuesChange > 0 ? "green.7" : stockValuesChange < 0 ? "red.7" : "gray.6";
return ( return (
+1 -1
View File
@@ -34,7 +34,7 @@ const TimetableWidgetInner = ({ station, baseUrl }: TimetableWidgetInnerProps) =
<Stack w="100%" gap="xs" p="sm"> <Stack w="100%" gap="xs" p="sm">
<Text fw="bold">{t("title", { station: station.label })}</Text> <Text fw="bold">{t("title", { station: station.label })}</Text>
{(timetable?.entries ?? []).map((entry) => ( {(timetable?.entries ?? []).map((entry) => (
<Group key={`${entry.timestamp.toISOString()}-${entry.location}`} justify="space-between" w="100%"> <Group key={`${new Date(entry.timestamp).toISOString()}-${entry.location}`} justify="space-between" w="100%">
<Group gap="sm"> <Group gap="sm">
{entry.line && ( {entry.line && (
<Badge <Badge
+16 -12
View File
@@ -37,24 +37,28 @@ function TracearrContent({ integrationIds, options, width }: TracearrContentProp
const { stats, streams, violations, recentActivity } = item.dashboard; const { stats, streams, violations, recentActivity } = item.dashboard;
const vData = violations ?? { data: [], meta: { total: 0, page: 1, pageSize: 5 } }; const vData = violations ?? { data: [], meta: { total: 0, page: 1, pageSize: 5 } };
const aData = recentActivity ?? { data: [], meta: { total: 0, page: 1, pageSize: 5 } }; const aData = recentActivity ?? { data: [], meta: { total: 0, page: 1, pageSize: 5 } };
const sData = streams ?? {
data: [],
summary: { total: 0, transcodes: 0, directStreams: 0, directPlays: 0, totalBitrate: "0", byServer: [] },
};
return { return {
stats: { stats: {
activeStreams: acc.stats.activeStreams + stats.activeStreams, activeStreams: acc.stats.activeStreams + (stats?.activeStreams ?? 0),
totalUsers: acc.stats.totalUsers + stats.totalUsers, totalUsers: acc.stats.totalUsers + (stats?.totalUsers ?? 0),
totalSessions: acc.stats.totalSessions + stats.totalSessions, totalSessions: acc.stats.totalSessions + (stats?.totalSessions ?? 0),
recentViolations: acc.stats.recentViolations + stats.recentViolations, recentViolations: acc.stats.recentViolations + (stats?.recentViolations ?? 0),
timestamp: stats.timestamp, timestamp: stats?.timestamp ?? "",
}, },
streams: { streams: {
data: [...acc.streams.data, ...streams.data], data: [...acc.streams.data, ...(sData.data ?? [])],
summary: { summary: {
total: acc.streams.summary.total + streams.summary.total, total: acc.streams.summary.total + (sData.summary?.total ?? 0),
transcodes: acc.streams.summary.transcodes + streams.summary.transcodes, transcodes: acc.streams.summary.transcodes + (sData.summary?.transcodes ?? 0),
directStreams: acc.streams.summary.directStreams + streams.summary.directStreams, directStreams: acc.streams.summary.directStreams + (sData.summary?.directStreams ?? 0),
directPlays: acc.streams.summary.directPlays + streams.summary.directPlays, directPlays: acc.streams.summary.directPlays + (sData.summary?.directPlays ?? 0),
totalBitrate: streams.summary.totalBitrate, totalBitrate: sData.summary?.totalBitrate ?? "0",
byServer: [...acc.streams.summary.byServer, ...streams.summary.byServer], byServer: [...acc.streams.summary.byServer, ...(sData.summary?.byServer ?? [])],
}, },
}, },
violations: { violations: {
+3 -3
View File
@@ -57,7 +57,7 @@ export function UmamiContent({
); );
const multiEventTotal = multiEventSeries const multiEventTotal = multiEventSeries
? multiEventSeries.flatMap(({ dataPoints }) => dataPoints).reduce((sum, { y }) => sum + y, 0) ? multiEventSeries.flatMap(({ dataPoints }) => dataPoints ?? []).reduce((sum, { y }) => sum + y, 0)
: undefined; : undefined;
const firstResult = results[0]; const firstResult = results[0];
@@ -73,13 +73,13 @@ export function UmamiContent({
const { visitorStats } = firstResult; const { visitorStats } = firstResult;
const chartData = visitorStats.dataPoints.map((point: UmamiVisitorStats["dataPoints"][number]) => ({ const chartData = (visitorStats.dataPoints ?? []).map((point: UmamiVisitorStats["dataPoints"][number]) => ({
label: formatXLabel(point.timestamp, timeFrame), label: formatXLabel(point.timestamp, timeFrame),
visitors: point.visitors, visitors: point.visitors,
...(point.events !== undefined ? { events: point.events } : {}), ...(point.events !== undefined ? { events: point.events } : {}),
})); }));
const hasEventSeries = visitorStats.dataPoints.some(({ events }) => events !== undefined); const hasEventSeries = (visitorStats.dataPoints ?? []).some(({ events }) => events !== undefined);
const series = [ const series = [
{ name: "visitors", color: "blue.5" }, { name: "visitors", color: "blue.5" },
...(hasEventSeries ? [{ name: "events", color: "orange.5" }] : []), ...(hasEventSeries ? [{ name: "events", color: "orange.5" }] : []),
@@ -45,14 +45,14 @@ export function UmamiEventsContent({
// Collect all unique timestamps across all series // Collect all unique timestamps across all series
const allTimestamps = Array.from( const allTimestamps = Array.from(
new Set(series.flatMap(({ dataPoints }) => dataPoints.map(({ x: xPoint }) => xPoint))), new Set(series.flatMap(({ dataPoints }) => (dataPoints ?? []).map(({ x: xPoint }) => xPoint))),
).toSorted(); ).toSorted();
// Build per-event lookup by timestamp string // Build per-event lookup by timestamp string
const byEvent = new Map( const byEvent = new Map(
series.map((serie: UmamiEventSeries) => [ series.map((serie: UmamiEventSeries) => [
serie.eventName, serie.eventName,
new Map(serie.dataPoints.map((point) => [point.x, point.y])), new Map((serie.dataPoints ?? []).map((point) => [point.x, point.y])),
]), ]),
); );
+1 -1
View File
@@ -44,7 +44,7 @@ function UpsContent({ integrationIds, options, width }: UpsContentProps) {
if (!data) return <WidgetEmptyState />; if (!data) return <WidgetEmptyState />;
const devices = data.flatMap((instance) => const devices = data.flatMap((instance) =>
instance.summaries.map((summary) => ({ key: `${instance.integrationId}:${summary.id}`, summary })), (instance.summaries ?? []).map((summary) => ({ key: `${instance.integrationId}:${summary.id}`, summary })),
); );
if (devices.length === 0) { if (devices.length === 0) {
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff. Show more