Compare commits
359 commits
graphite-b
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c1f0c52d5 | ||
|
|
2318b6bdd0 | ||
|
|
34fc4f0cbb | ||
|
|
68002b0308 | ||
|
|
4bba2c2493 | ||
|
|
9d63f7cb2d | ||
|
|
4a4e5c0abe | ||
|
|
885ea10f2a | ||
|
|
edab1b231b | ||
|
|
333c11986d | ||
|
|
be3182793d | ||
|
|
a279129ad8 | ||
|
|
027c6efb32 | ||
|
|
755cbe4dae | ||
|
|
111a5843ef | ||
|
|
49e3977199 | ||
|
|
ca325a01c5 | ||
|
|
25f60db703 | ||
|
|
478a5fcba3 | ||
|
|
bf69fc5f65 | ||
|
|
0fd88b2cdf | ||
|
|
8302893233 | ||
|
|
1526e3d441 | ||
|
|
dfd787c8ae | ||
|
|
a488bbc754 | ||
|
|
ce23bded90 | ||
|
|
c793785e30 | ||
|
|
036382d82d | ||
|
|
756ecbddcd | ||
|
|
648ccae5fc | ||
|
|
62cdf5dcca | ||
|
|
00d1dac515 | ||
|
|
d479bfaddc | ||
|
|
8fedeef4d1 | ||
|
|
2d877cee5a | ||
|
|
0a2c6bca0c | ||
|
|
d4436b0cdc | ||
|
|
ddf7cab503 | ||
|
|
74ddf574a8 | ||
|
|
d502b96509 | ||
|
|
dee3bb098a | ||
|
|
5ee65bf0af | ||
|
|
7b5c53bb7d | ||
|
|
17a8838569 | ||
|
|
25b2f71b24 | ||
|
|
008296238b | ||
|
|
2f78c4a1fb | ||
|
|
20d202c20e | ||
|
|
47f8f2f03a | ||
|
|
4ea9f34154 | ||
|
|
e4898b97ea | ||
|
|
98338e80c3 | ||
|
|
273408cdb8 | ||
|
|
0589fd63b1 | ||
|
|
6bcb0bef71 | ||
|
|
705b8eb748 | ||
|
|
05073e667e | ||
|
|
970a7fa42f | ||
|
|
575e01cab9 | ||
|
|
eb36621b30 | ||
|
|
da1d4d30b2 | ||
|
|
68a7b0beb1 | ||
|
|
4d5a5d399b | ||
|
|
f82494abab | ||
|
|
4dcafa0708 | ||
|
|
c071596151 | ||
|
|
4b66ad73a7 | ||
|
|
4a06891db9 | ||
|
|
3b9f2086ee | ||
|
|
94f6d0529f | ||
|
|
b292f94186 | ||
|
|
66ebc249ca | ||
|
|
0f5a6823ec | ||
|
|
419204d587 | ||
|
|
11dacd7c71 | ||
|
|
19a0781667 | ||
|
|
3142cb026a | ||
|
|
2a1351382f | ||
|
|
0dccd00539 | ||
|
|
ecbf407058 | ||
|
|
18a91d9b78 | ||
|
|
a58fe82d48 | ||
|
|
aa7da321ba | ||
|
|
2ada5acd5a | ||
|
|
2062beac68 | ||
|
|
df4b668560 | ||
|
|
5e4742488f | ||
|
|
cda008a53e | ||
|
|
e91df3eab0 | ||
|
|
3c7eb65c7c | ||
|
|
b13b6d606a | ||
|
|
66cd9e185b | ||
|
|
1ca1598c58 | ||
|
|
89ae52d036 | ||
|
|
700fa1cd4a | ||
|
|
e65a135676 | ||
|
|
e981211a2d | ||
|
|
cd69eea27f | ||
|
|
b1ae85e2c1 | ||
|
|
497a0e8bee | ||
|
|
147f266929 | ||
|
|
0351d5e0b9 | ||
|
|
f0ac9fe35c | ||
|
|
17d6ec85c3 | ||
|
|
e7b9b118a8 | ||
|
|
8772d4796e | ||
|
|
38f5a669ae | ||
|
|
7be7c9edae | ||
|
|
f83b765d04 | ||
|
|
3d5a0a9b75 | ||
|
|
d19d827496 | ||
|
|
35dd49d7ac | ||
|
|
94d7fdc9a8 | ||
|
|
8fd54383a8 | ||
|
|
220e2d2801 | ||
|
|
1cf96c5292 | ||
|
|
11e9fbcc44 | ||
|
|
6728271a98 | ||
|
|
82e027d872 | ||
|
|
f3eb072182 | ||
|
|
eafcf2dd1f | ||
|
|
c216fb1430 | ||
|
|
d567dd9867 | ||
|
|
2000ebd254 | ||
|
|
a5d47eac5a | ||
|
|
e506047415 | ||
|
|
7b3b7583c0 | ||
|
|
f078e006c1 | ||
|
|
3adc722cca | ||
|
|
c64862f604 | ||
|
|
26203cca59 | ||
|
|
6ae5a33acd | ||
|
|
4631655c3e | ||
|
|
10eb9a84fb | ||
|
|
e2c9ef0518 | ||
|
|
04973849a0 | ||
|
|
a0c34ee48d | ||
|
|
3f92dace6c | ||
|
|
16085a5fed | ||
|
|
d2a0f75e2e | ||
|
|
c22af17fa6 | ||
|
|
f967450eea | ||
|
|
694f1c212f | ||
|
|
8ece1ef187 | ||
|
|
c95cc305f8 | ||
|
|
63b08a4b71 | ||
|
|
96609fc328 | ||
|
|
927097a902 | ||
|
|
cbc874df0d | ||
|
|
e19776a2b8 | ||
|
|
c5e35cf8b1 | ||
|
|
ff9decb54b | ||
|
|
0224afae4a | ||
|
|
72c2f89cc8 | ||
|
|
6f0617492b | ||
|
|
dd912b8246 | ||
|
|
d56ee35b06 | ||
|
|
2619da9c5f | ||
|
|
d2f65716fe | ||
|
|
497fa474a7 | ||
|
|
28b89036f1 | ||
|
|
308d9916ba | ||
|
|
95006a7471 | ||
|
|
5b728b8144 | ||
|
|
1e98013e45 | ||
|
|
e059c35fbb | ||
|
|
d10a3d2d65 | ||
|
|
33601dde24 | ||
|
|
7fb5e6d65d | ||
|
|
b25ccdc6b2 | ||
|
|
5497cadb56 | ||
|
|
2ecd4b8eb6 | ||
|
|
76ac78c40c | ||
|
|
97b4ce42c4 | ||
|
|
832425025f | ||
|
|
7ea9899385 | ||
|
|
ed046f284d | ||
|
|
cb22e34215 | ||
|
|
8765c5e705 | ||
|
|
11bb95db92 | ||
|
|
5d8c2925d8 | ||
|
|
61396625f1 | ||
|
|
b2728cb09a | ||
|
|
0476dcebb8 | ||
|
|
b1cd1a4220 | ||
|
|
79b7733e1e | ||
|
|
7e9b1fafa3 | ||
|
|
feb69ef7a7 | ||
|
|
4520335ebc | ||
|
|
c25eacad05 | ||
|
|
73ae5c41b5 | ||
|
|
1f4f94b3a5 | ||
|
|
d213d3546a | ||
|
|
28ba8657f9 | ||
|
|
863fbfc5cc | ||
|
|
70c7de1efc | ||
|
|
595a29056d | ||
|
|
4872029b87 | ||
|
|
979e494e75 | ||
|
|
5bcc3acc56 | ||
|
|
8a4a06f888 | ||
|
|
f9027033e5 | ||
|
|
8c14a2742c | ||
|
|
c371676ad0 | ||
|
|
3169627b79 | ||
|
|
049becb900 | ||
|
|
ad8a83e60e | ||
|
|
f11e3b7f82 | ||
|
|
74d20d5be3 | ||
|
|
7add3dd517 | ||
|
|
9e7f1bf138 | ||
|
|
43d9cb837f | ||
|
|
1cb1a66ef1 | ||
|
|
a4e54ac527 | ||
|
|
bae43c0d90 | ||
|
|
afc77f55b8 | ||
|
|
95aadf6e73 | ||
|
|
731ebad1ee | ||
|
|
475bfb59ae | ||
|
|
e77723164b | ||
|
|
4bf1463406 | ||
|
|
d6e80b71d7 | ||
|
|
a6d402b915 | ||
|
|
0baf4677e7 | ||
|
|
d3da24c916 | ||
|
|
f7324db5fc | ||
|
|
4305057185 | ||
|
|
e265f7d478 | ||
|
|
add0f2788f | ||
|
|
63e12868b1 | ||
|
|
ca38f7ca69 | ||
|
|
915b96c218 | ||
|
|
3acf565ccd | ||
|
|
aa7eaa0929 | ||
|
|
c9451d90dd | ||
|
|
d600102d46 | ||
|
|
e55ffccd21 | ||
|
|
f89b8c3b52 | ||
|
|
2a219ac042 | ||
|
|
611640b32b | ||
|
|
866a3c63e8 | ||
|
|
6354705626 | ||
|
|
b4668e23c7 | ||
|
|
7ef211ddd5 | ||
|
|
4c928cbc33 | ||
|
|
5a83d6ae86 | ||
|
|
8acca9ef4a | ||
|
|
c93b076bf6 | ||
|
|
4fec2777ce | ||
|
|
dd1aca7e30 | ||
|
|
27b1789657 | ||
|
|
05dd440dea | ||
|
|
962ab01ea4 | ||
|
|
fa8e57a589 | ||
|
|
3c9620f973 | ||
|
|
618f37e250 | ||
|
|
aa23967329 | ||
|
|
03739f9799 | ||
|
|
94cd52dec7 | ||
|
|
bad5f78991 | ||
|
|
a039bb478e | ||
|
|
f6f17cd61c | ||
|
|
429b69ec92 | ||
|
|
e39220c024 | ||
|
|
ee73f89863 | ||
|
|
4356ace665 | ||
|
|
59fcce7e40 | ||
|
|
a671b17b4f | ||
|
|
2d10da72f6 | ||
|
|
959cb21d83 | ||
|
|
5f7f2005fa | ||
|
|
a2d34a027e | ||
|
|
e58f82d7ed | ||
|
|
1be83ccf4c | ||
|
|
1b5f9bf62d | ||
|
|
b298524663 | ||
|
|
7473c29948 | ||
|
|
9632c77177 | ||
|
|
8fdf858dcb | ||
|
|
b2a8bdaa42 | ||
|
|
bb7d650bcd | ||
|
|
66f95dcd8e | ||
|
|
469f0d6c4e | ||
|
|
1fb4f90d50 | ||
|
|
d74f516336 | ||
|
|
f7f56c6c83 | ||
|
|
2923bf9f27 | ||
|
|
2da4823ee7 | ||
|
|
b132ad6df5 | ||
|
|
a1b2d97dbc | ||
|
|
332e5bffda | ||
|
|
9e616ca35a | ||
|
|
4e29295f68 | ||
|
|
d07be16fc6 | ||
|
|
f6169ab27e | ||
|
|
b156d6154e | ||
|
|
e8eae7dce6 | ||
|
|
d59677e322 | ||
|
|
55dbcf0eb3 | ||
|
|
b35a20f43d | ||
|
|
a4cc82f526 | ||
|
|
bdea445e4f | ||
|
|
49e98d522f | ||
|
|
b72d0af17d | ||
|
|
1b948ed41e | ||
|
|
d640ad88b2 | ||
|
|
3fa793bef6 | ||
|
|
7fde07f107 | ||
|
|
19b827c049 | ||
|
|
ab25cc915e | ||
|
|
df312cd419 | ||
|
|
dd8f471d60 | ||
|
|
8a10266960 | ||
|
|
3131d140fa | ||
|
|
1776bd85d8 | ||
|
|
57313fee9b | ||
|
|
d660c8e2e4 | ||
|
|
3d2900ab69 | ||
|
|
938680bb80 | ||
|
|
4d8a0b28ca | ||
|
|
2adec5a999 | ||
|
|
2ccaf724bf | ||
|
|
8e24c6a8d8 | ||
|
|
d5da6d4562 | ||
|
|
3e50e37e02 | ||
|
|
c2ed9e3693 | ||
|
|
c1e8036323 | ||
|
|
6769f5fa6c | ||
|
|
addeab0e30 | ||
|
|
3b94794aa3 | ||
|
|
6f560ecae9 | ||
|
|
e8ae8812ff | ||
|
|
157be2d6ab | ||
|
|
0c20473e30 | ||
|
|
2f253d4999 | ||
|
|
fc11432b87 | ||
|
|
371ca270fa | ||
|
|
a24c6d825e | ||
|
|
10303b6596 | ||
|
|
235706b230 | ||
|
|
4ed554c039 | ||
|
|
5f6409e0a5 | ||
|
|
1724429fb0 | ||
|
|
1da4671133 | ||
|
|
c606099104 | ||
|
|
e0eb490636 | ||
|
|
d07306cb86 | ||
|
|
4a032d744b | ||
|
|
8691cf8c1f | ||
|
|
c5aacd30e3 | ||
|
|
812533394b | ||
|
|
7881f818ae | ||
|
|
58fee9914b | ||
|
|
70352e9f91 | ||
|
|
12454ee401 | ||
|
|
29db09bb5b | ||
|
|
4a601d157d | ||
|
|
7dc017f4b6 | ||
|
|
ef51d665c8 |
707 changed files with 85777 additions and 14600 deletions
|
|
@ -3,6 +3,7 @@
|
|||
!bun.lock
|
||||
!package.json
|
||||
!.gitignore
|
||||
!bunfig.toml
|
||||
|
||||
!**/package.json
|
||||
!**/bun.lock
|
||||
|
|
@ -11,6 +12,8 @@
|
|||
!**/components.json
|
||||
|
||||
!app/**
|
||||
!apps/agent/**
|
||||
!packages/**
|
||||
!public/**
|
||||
|
||||
# License files and attributions
|
||||
|
|
@ -21,3 +24,4 @@
|
|||
node_modules/**
|
||||
dist/**
|
||||
.output/**
|
||||
app/test/integration/artifacts/**
|
||||
|
|
|
|||
|
|
@ -4,5 +4,6 @@ RESTIC_CACHE_DIR=./data/restic/cache
|
|||
ZEROBYTE_REPOSITORIES_DIR=./data/repositories
|
||||
ZEROBYTE_VOLUMES_DIR=./data/volumes
|
||||
APP_SECRET=<openssl rand -hex 32>
|
||||
BASE_URL=http://localhost:300
|
||||
BASE_URL=http://*.localhost
|
||||
TRUST_PROXY=false
|
||||
PORT=3000
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
ZEROBYTE_DATABASE_URL=:memory:
|
||||
APP_SECRET=8b9acd4456dd5db0a4a3c4f4e1240b2c3ae08bb59690167197425e4a25dd9a69
|
||||
BASE_URL=http://localhost:4096
|
||||
ENABLE_LOCAL_AGENT=true
|
||||
|
|
|
|||
13
.fallowrc.json
Normal file
13
.fallowrc.json
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
{
|
||||
"entry": [
|
||||
"app/client.tsx",
|
||||
"app/router.tsx",
|
||||
"app/server.ts",
|
||||
"app/server/plugins/bootstrap.ts",
|
||||
"openapi-ts.config.ts",
|
||||
"scripts/create-test-files.ts",
|
||||
"scripts/patch-api-client.ts"
|
||||
],
|
||||
"ignorePatterns": ["node_modules/**", ".output/**", "**/api-client/**", "**/routeTree.gen.ts", "apps/docs/**"],
|
||||
"ignoreDependencies": ["@tailwindcss/typography", "babel-plugin-react-compiler"]
|
||||
}
|
||||
22
.github/actions/install-dependencies/action.yml
vendored
22
.github/actions/install-dependencies/action.yml
vendored
|
|
@ -1,15 +1,31 @@
|
|||
name: Install dependencies
|
||||
|
||||
description: Install dependencies
|
||||
inputs:
|
||||
workingDirectory:
|
||||
description: "The working directory to install dependencies in"
|
||||
required: false
|
||||
default: "."
|
||||
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
- uses: socketdev/action@937f824ec476dfd164d4a4d9995751427b0be143 # v1
|
||||
with:
|
||||
mode: firewall
|
||||
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
|
||||
name: Install Bun
|
||||
with:
|
||||
bun-version: "1.3.6"
|
||||
bun-version: "1.3.14"
|
||||
|
||||
- uses: voidzero-dev/setup-vp@ca1c46663915d6c1042ae23bd39ab85718bfb0fa # v1
|
||||
with:
|
||||
node-version: '24'
|
||||
cache: true
|
||||
|
||||
- name: Install dependencies
|
||||
shell: bash
|
||||
run: bun install --frozen-lockfile
|
||||
run: |
|
||||
cd ${{ inputs.workingDirectory }}
|
||||
sfw vp install --frozen-lockfile
|
||||
|
|
|
|||
18
.github/dependabot.yml
vendored
18
.github/dependabot.yml
vendored
|
|
@ -1,18 +0,0 @@
|
|||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "bun"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
rebase-strategy: 'auto'
|
||||
groups:
|
||||
minor-patch:
|
||||
update-types:
|
||||
- minor
|
||||
- patch
|
||||
|
||||
- package-ecosystem: 'github-actions'
|
||||
directory: '/'
|
||||
schedule:
|
||||
interval: 'daily'
|
||||
rebase-strategy: 'auto'
|
||||
19
.github/renovate.json
vendored
Normal file
19
.github/renovate.json
vendored
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": ["config:recommended", "helpers:pinGitHubActionDigests"],
|
||||
"enabledManagers": ["bun", "github-actions"],
|
||||
"minimumReleaseAge": "3 days",
|
||||
"rangeStrategy": "bump",
|
||||
"packageRules": [
|
||||
{
|
||||
"matchManagers": ["github-actions"],
|
||||
"matchUpdateTypes": ["digest", "pinDigest"],
|
||||
"minimumReleaseAge": null
|
||||
},
|
||||
{
|
||||
"matchManagers": ["bun"],
|
||||
"matchUpdateTypes": ["minor", "patch"],
|
||||
"groupName": "bun minor and patch dependencies"
|
||||
}
|
||||
]
|
||||
}
|
||||
17
.github/workflows/checks.yml
vendored
17
.github/workflows/checks.yml
vendored
|
|
@ -20,24 +20,23 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Install dependencies
|
||||
uses: "./.github/actions/install-dependencies"
|
||||
|
||||
- uses: oxc-project/oxlint-action@latest
|
||||
with:
|
||||
config: .oxlintrc.json
|
||||
deny-warnings: true
|
||||
- name: Run lint
|
||||
shell: bash
|
||||
run: vp lint --type-aware --deny-warnings
|
||||
|
||||
typecheck:
|
||||
timeout-minutes: 10
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
|
|
@ -53,7 +52,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
|
|
@ -69,7 +68,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
|
|
@ -85,7 +84,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
|
|
|
|||
41
.github/workflows/docs-deploy.yml
vendored
Normal file
41
.github/workflows/docs-deploy.yml
vendored
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
name: Docs deploy
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "apps/docs/**"
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
name: Deploy docs
|
||||
if: github.event.repository.default_branch == github.ref_name
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Install dependencies
|
||||
uses: "./.github/actions/install-dependencies"
|
||||
|
||||
- name: Build docs
|
||||
working-directory: apps/docs
|
||||
run: bun run build
|
||||
|
||||
- name: Build and deploy docs
|
||||
uses: cloudflare/wrangler-action@ebbaa1584979971c8614a24965b4405ff95890e0 # v4
|
||||
with:
|
||||
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
workingDirectory: apps/docs
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
28
.github/workflows/e2e.yml
vendored
28
.github/workflows/e2e.yml
vendored
|
|
@ -12,7 +12,7 @@ jobs:
|
|||
timeout-minutes: 20
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Install dependencies
|
||||
uses: "./.github/actions/install-dependencies"
|
||||
|
|
@ -26,7 +26,7 @@ jobs:
|
|||
|
||||
- name: Cache Playwright Browsers
|
||||
id: playwright-cache
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: ${{ runner.os }}-playwright-${{ steps.playwright-version.outputs.version }}
|
||||
|
|
@ -46,27 +46,37 @@ jobs:
|
|||
mkdir -p data
|
||||
mkdir -p playwright/temp
|
||||
mkdir -p playwright/data
|
||||
mkdir -p playwright/tinyauth/app-data
|
||||
mkdir -p playwright/tinyauth/caddy-data
|
||||
chmod -R 777 playwright/temp
|
||||
touch .env.local
|
||||
echo "SERVER_IP=localhost" >> .env.local
|
||||
echo "ZEROBYTE_DATABASE_URL=./data/zerobyte.db" >> .env.local
|
||||
echo "BASE_URL=http://localhost:4096" >> .env.local
|
||||
echo "E2E_DEX_ORIGIN=http://dex:5557" >> .env.local
|
||||
echo "E2E_TINYAUTH_ORIGIN=https://tinyauth.example.com:5557" >> .env.local
|
||||
echo "TZ=Europe/Zurich" >> .env.local
|
||||
|
||||
- name: Start zerobyte-e2e service
|
||||
run: bun run start:e2e -- -d
|
||||
|
||||
- name: Check CLI version
|
||||
run: |
|
||||
expected_version=$(docker exec zerobyte printenv APP_VERSION)
|
||||
cli_version=$(docker exec zerobyte bun run --silent cli --version)
|
||||
echo "$cli_version"
|
||||
test "$cli_version" = "$expected_version"
|
||||
|
||||
- name: Wait for zerobyte to be ready
|
||||
run: |
|
||||
timeout 30s bash -c 'until curl -f http://localhost:4096/api/healthcheck; do echo "Waiting for server..." && sleep 2; done'
|
||||
|
||||
- name: Wait for Dex to be ready
|
||||
- name: Wait for Tinyauth to be ready
|
||||
run: |
|
||||
timeout 30s bash -c 'until curl -sf http://localhost:5557/dex/.well-known/openid-configuration; do echo "Waiting for Dex..." && sleep 2; done'
|
||||
timeout 30s bash -c 'until curl -skf https://localhost:5557/.well-known/openid-configuration; do echo "Waiting for Tinyauth..." && sleep 2; done'
|
||||
|
||||
- name: Print docker logs if failed to start
|
||||
if: failure()
|
||||
run: docker compose logs zerobyte-e2e dex || true
|
||||
run: docker compose logs zerobyte-e2e tinyauth tinyauth-app || true
|
||||
|
||||
- name: Make playwright directory writable
|
||||
run: sudo chmod 777 playwright/data/zerobyte.db
|
||||
|
|
@ -77,16 +87,16 @@ jobs:
|
|||
- name: Dump container logs in playwright-report folder
|
||||
if: always()
|
||||
run: |
|
||||
tree playwright
|
||||
tree playwright || true
|
||||
docker compose logs zerobyte-e2e > playwright-report/container-logs.txt || true
|
||||
docker compose logs dex > playwright-report/dex-logs.txt || true
|
||||
docker compose logs tinyauth tinyauth-app > playwright-report/tinyauth-logs.txt || true
|
||||
|
||||
- name: Debug - print content of /test-data in container
|
||||
if: failure()
|
||||
run: |
|
||||
docker exec zerobyte /bin/ash -c "ls -la /test-data" || true
|
||||
|
||||
- uses: actions/upload-artifact@v7
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
if: always()
|
||||
with:
|
||||
name: playwright-report
|
||||
|
|
|
|||
35
.github/workflows/integration.yml
vendored
Normal file
35
.github/workflows/integration.yml
vendored
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
name: Integration Tests
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
workflow_call:
|
||||
|
||||
jobs:
|
||||
integration:
|
||||
name: Integration
|
||||
timeout-minutes: 30
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install dependencies
|
||||
uses: "./.github/actions/install-dependencies"
|
||||
|
||||
- name: Run integration tests
|
||||
env:
|
||||
SKIP_VOLUME_MOUNT_INTEGRATION_TESTS: "true"
|
||||
run: bun run test:integration
|
||||
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
if: failure()
|
||||
with:
|
||||
name: integration-artifacts
|
||||
path: |
|
||||
app/test/integration/artifacts/compose.log
|
||||
app/test/integration/artifacts/docker-output.log
|
||||
app/test/integration/artifacts/runs/**
|
||||
retention-days: 5
|
||||
17
.github/workflows/nightly.yml
vendored
17
.github/workflows/nightly.yml
vendored
|
|
@ -6,31 +6,34 @@ on:
|
|||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
packages: write
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
timeout-minutes: 15
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4
|
||||
with:
|
||||
driver: cloud
|
||||
endpoint: "meienberger/runtipi-builder"
|
||||
install: true
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
|
|
@ -38,14 +41,14 @@ jobs:
|
|||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
uses: docker/metadata-action@80c7e94dd9b9319bd5eb7a0e0fe9291e23a2a2e9 # v6
|
||||
with:
|
||||
images: ghcr.io/${{ github.repository_owner }}/zerobyte
|
||||
tags: |
|
||||
type=raw,value=nightly
|
||||
|
||||
- name: Push images to GitHub Container Registry
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7
|
||||
with:
|
||||
context: .
|
||||
target: production
|
||||
|
|
|
|||
77
.github/workflows/release.yml
vendored
77
.github/workflows/release.yml
vendored
|
|
@ -8,16 +8,16 @@ on:
|
|||
- "v*.*.*-alpha.*"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
security-events: write
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
determine-release-type:
|
||||
runs-on: ubuntu-latest
|
||||
permissions: {}
|
||||
outputs:
|
||||
release_type: ${{ steps.set-type.outputs.release_type }}
|
||||
tagname: ${{ github.ref_name }}
|
||||
is_minor_release: ${{ steps.set-type.outputs.is_minor_release }}
|
||||
steps:
|
||||
- name: Set release type
|
||||
id: set-type
|
||||
|
|
@ -31,74 +31,60 @@ jobs:
|
|||
echo "release_type=release" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
if [[ $TAG =~ ^v[0-9]+\.[0-9]+\.0$ ]]; then
|
||||
echo "is_minor_release=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "is_minor_release=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
checks:
|
||||
uses: ./.github/workflows/checks.yml
|
||||
|
||||
e2e-tests:
|
||||
uses: ./.github/workflows/e2e.yml
|
||||
|
||||
integration-tests:
|
||||
uses: ./.github/workflows/integration.yml
|
||||
|
||||
build-images:
|
||||
environment: release
|
||||
timeout-minutes: 15
|
||||
needs: [determine-release-type, checks, e2e-tests]
|
||||
needs: [determine-release-type, checks, e2e-tests, integration-tests]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
security-events: write
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.ref }}
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4
|
||||
with:
|
||||
driver: cloud
|
||||
endpoint: "meienberger/runtipi-builder"
|
||||
install: true
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build docker image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
target: production
|
||||
platforms: linux/amd64
|
||||
push: false
|
||||
load: true
|
||||
tags: local/zerobyte:ci
|
||||
build-args: |
|
||||
APP_VERSION=${{ needs.determine-release-type.outputs.tagname }}
|
||||
|
||||
- name: Scan new image for vulnerabilities
|
||||
if: needs.determine-release-type.outputs.release_type == 'release'
|
||||
uses: anchore/scan-action@v7
|
||||
id: scan
|
||||
with:
|
||||
image: local/zerobyte:ci
|
||||
fail-build: false
|
||||
only-fixed: true
|
||||
severity-cutoff: critical
|
||||
|
||||
- name: upload Anchore scan report
|
||||
if: needs.determine-release-type.outputs.release_type == 'release'
|
||||
uses: github/codeql-action/upload-sarif@v4
|
||||
with:
|
||||
sarif_file: ${{ steps.scan.outputs.sarif }}
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
uses: docker/metadata-action@80c7e94dd9b9319bd5eb7a0e0fe9291e23a2a2e9 # v6
|
||||
with:
|
||||
images: ghcr.io/${{ github.repository_owner }}/zerobyte
|
||||
tags: |
|
||||
|
|
@ -110,7 +96,7 @@ jobs:
|
|||
latest=${{ needs.determine-release-type.outputs.release_type == 'release' }}
|
||||
|
||||
- name: Push images to GitHub Container Registry
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7
|
||||
with:
|
||||
context: .
|
||||
target: production
|
||||
|
|
@ -125,12 +111,14 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
needs: [build-images, determine-release-type]
|
||||
if: needs.determine-release-type.outputs.release_type == 'release'
|
||||
permissions:
|
||||
contents: write
|
||||
outputs:
|
||||
id: ${{ steps.create_release.outputs.id }}
|
||||
steps:
|
||||
- name: Create GitHub release
|
||||
id: create_release
|
||||
uses: softprops/action-gh-release@v2
|
||||
uses: softprops/action-gh-release@b4309332981a82ec1c5618f44dd2e27cc8bfbfda # v3
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
|
|
@ -140,4 +128,13 @@ jobs:
|
|||
name: ${{ needs.determine-release-type.outputs.tagname }}
|
||||
draft: false
|
||||
prerelease: true
|
||||
files: cli/runtipi-cli-*
|
||||
|
||||
request-docs-version-update:
|
||||
uses: ./.github/workflows/request-docs-version-update.yml
|
||||
needs: [publish-release, determine-release-type]
|
||||
if: needs.determine-release-type.outputs.release_type == 'release' && needs.determine-release-type.outputs.is_minor_release == 'true'
|
||||
with:
|
||||
release_tag: ${{ needs.determine-release-type.outputs.tagname }}
|
||||
base_branch: ${{ github.event.repository.default_branch }}
|
||||
secrets:
|
||||
COPILOT_ASSIGNMENT_TOKEN: ${{ secrets.COPILOT_ASSIGNMENT_TOKEN }}
|
||||
|
|
|
|||
122
.github/workflows/request-docs-version-update.yml
vendored
Normal file
122
.github/workflows/request-docs-version-update.yml
vendored
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
name: Request docs version update
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: Minor release tag, for example v0.35.0
|
||||
required: true
|
||||
type: string
|
||||
base_branch:
|
||||
description: Branch Copilot should branch from
|
||||
required: false
|
||||
default: main
|
||||
type: string
|
||||
workflow_call:
|
||||
inputs:
|
||||
release_tag:
|
||||
required: true
|
||||
type: string
|
||||
base_branch:
|
||||
required: false
|
||||
default: main
|
||||
type: string
|
||||
secrets:
|
||||
COPILOT_ASSIGNMENT_TOKEN:
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
request-docs-version-update:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Create Copilot issue
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
|
||||
with:
|
||||
github-token: ${{ secrets.COPILOT_ASSIGNMENT_TOKEN }}
|
||||
script: |
|
||||
if (!process.env.COPILOT_ASSIGNMENT_TOKEN) {
|
||||
core.setFailed("COPILOT_ASSIGNMENT_TOKEN is required to assign issues to GitHub Copilot.");
|
||||
return;
|
||||
}
|
||||
|
||||
const releaseTag = process.env.RELEASE_TAG;
|
||||
const baseBranch = process.env.BASE_BRANCH;
|
||||
const minorRelease = releaseTag.match(/^(v\d+\.\d+)\.0$/);
|
||||
if (!minorRelease) {
|
||||
core.setFailed(`Docs version updates only run for minor release tags like v0.35.0. Received: ${releaseTag}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const docsVersion = minorRelease[1];
|
||||
const { owner, repo } = context.repo;
|
||||
const targetRepo = `${owner}/${repo}`;
|
||||
const releaseUrl = `https://github.com/${targetRepo}/releases/tag/${releaseTag}`;
|
||||
const title = `Update Docker Compose examples to ${docsVersion}`;
|
||||
const bodyLines = [
|
||||
`A new Zerobyte release was published: ${releaseTag}`,
|
||||
"",
|
||||
`Release: ${releaseUrl}`,
|
||||
"",
|
||||
"Please create a pull request that updates Docker Compose documentation examples to use:",
|
||||
"",
|
||||
"```yaml",
|
||||
`image: ghcr.io/nicotsx/zerobyte:${docsVersion}`,
|
||||
"```",
|
||||
"",
|
||||
"Scope:",
|
||||
"",
|
||||
"- Update Docker image tags in `README.md`.",
|
||||
"- Update Docker image tags in `apps/docs/`.",
|
||||
"- Only update Zerobyte image versions in Docker Compose examples.",
|
||||
"- Do not change unrelated prose, formatting, or code.",
|
||||
"",
|
||||
"Verification:",
|
||||
"",
|
||||
"- Search for stale `ghcr.io/nicotsx/zerobyte:v...` references in `README.md` and `apps/docs/`.",
|
||||
"- Run any formatting or documentation checks that are appropriate for the touched files.",
|
||||
];
|
||||
|
||||
const issue = await github.rest.issues.create({
|
||||
owner,
|
||||
repo,
|
||||
title,
|
||||
body: bodyLines.join("\n"),
|
||||
});
|
||||
|
||||
await github.rest.issues.update({
|
||||
owner,
|
||||
repo,
|
||||
issue_number: issue.data.number,
|
||||
body: [
|
||||
...bodyLines,
|
||||
"",
|
||||
"Pull request requirement:",
|
||||
"",
|
||||
`- Include \`Closes #${issue.data.number}\` in the pull request body.`,
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
await github.request("POST /repos/{owner}/{repo}/issues/{issue_number}/assignees", {
|
||||
owner,
|
||||
repo,
|
||||
issue_number: issue.data.number,
|
||||
assignees: ["copilot-swe-agent[bot]"],
|
||||
agent_assignment: {
|
||||
target_repo: targetRepo,
|
||||
base_branch: baseBranch,
|
||||
custom_instructions: "Create a focused documentation-only PR for the release version update.",
|
||||
custom_agent: "",
|
||||
model: "",
|
||||
},
|
||||
headers: {
|
||||
accept: "application/vnd.github+json",
|
||||
"X-GitHub-Api-Version": "2022-11-28",
|
||||
},
|
||||
});
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
BASE_BRANCH: ${{ inputs.base_branch }}
|
||||
COPILOT_ASSIGNMENT_TOKEN: ${{ secrets.COPILOT_ASSIGNMENT_TOKEN }}
|
||||
41
.github/workflows/scorecard.yml
vendored
Normal file
41
.github/workflows/scorecard.yml
vendored
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
name: Scorecard analysis
|
||||
on:
|
||||
branch_protection_rule:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
|
||||
permissions: read-all
|
||||
|
||||
jobs:
|
||||
analysis:
|
||||
name: Scorecard analysis
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event.repository.default_branch == github.ref_name || github.event_name == 'pull_request'
|
||||
permissions:
|
||||
security-events: write
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Run analysis
|
||||
uses: ossf/scorecard-action@f49aabe0b5af0936a0987cfb85d86b75731b0186
|
||||
with:
|
||||
results_file: results.sarif
|
||||
results_format: sarif
|
||||
publish_results: true
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1
|
||||
with:
|
||||
name: SARIF file
|
||||
path: results.sarif
|
||||
retention-days: 5
|
||||
|
||||
- name: Upload to code-scanning
|
||||
uses: github/codeql-action/upload-sarif@9e0d7b8d25671d64c341c19c0152d693099fb5ba # v4
|
||||
with:
|
||||
sarif_file: results.sarif
|
||||
13
.gitignore
vendored
13
.gitignore
vendored
|
|
@ -15,7 +15,7 @@ notes.md
|
|||
smb-password.txt
|
||||
cache.db
|
||||
|
||||
data/
|
||||
/data
|
||||
|
||||
.env*
|
||||
!.env.example
|
||||
|
|
@ -28,12 +28,17 @@ node_modules/
|
|||
/blob-report/
|
||||
/playwright/.cache/
|
||||
/playwright/.auth/
|
||||
/playwright/restic.pass
|
||||
/playwright/*.pass
|
||||
/playwright/tinyauth/app-data/
|
||||
/playwright/tinyauth/caddy-data/
|
||||
|
||||
playwright/.auth
|
||||
playwright/temp
|
||||
playwright/data
|
||||
|
||||
.idea/
|
||||
.deepsec/
|
||||
.codex/
|
||||
|
||||
# OpenAPI error logs
|
||||
openapi-ts-error-*.log
|
||||
|
|
@ -41,3 +46,7 @@ openapi-ts-error-*.log
|
|||
tmp/
|
||||
qa-output
|
||||
|
||||
.worktrees/
|
||||
.turbo
|
||||
.superset
|
||||
.fallow
|
||||
|
|
|
|||
|
|
@ -1,7 +0,0 @@
|
|||
{
|
||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||
"printWidth": 120,
|
||||
"useTabs": true,
|
||||
"endOfLine": "lf",
|
||||
"ignorePatterns": ["*.gen.ts"]
|
||||
}
|
||||
160
.oxlintrc.json
160
.oxlintrc.json
|
|
@ -1,160 +0,0 @@
|
|||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["eslint", "unicorn", "typescript", "oxc", "import", "react", "react-perf", "node", "jsx-a11y"],
|
||||
"categories": {},
|
||||
"rules": {
|
||||
"constructor-super": "warn",
|
||||
"for-direction": "warn",
|
||||
"no-async-promise-executor": "warn",
|
||||
"no-caller": "warn",
|
||||
"no-class-assign": "warn",
|
||||
"no-compare-neg-zero": "warn",
|
||||
"no-cond-assign": "warn",
|
||||
"no-const-assign": "warn",
|
||||
"no-constant-binary-expression": "warn",
|
||||
"no-constant-condition": "warn",
|
||||
"no-control-regex": "warn",
|
||||
"no-debugger": "warn",
|
||||
"no-delete-var": "warn",
|
||||
"no-dupe-class-members": "warn",
|
||||
"no-dupe-else-if": "warn",
|
||||
"no-dupe-keys": "warn",
|
||||
"no-duplicate-case": "warn",
|
||||
"no-empty-character-class": "warn",
|
||||
"no-empty-pattern": "warn",
|
||||
"no-empty-static-block": "warn",
|
||||
"no-eval": "warn",
|
||||
"no-ex-assign": "warn",
|
||||
"no-extra-boolean-cast": "warn",
|
||||
"no-func-assign": "warn",
|
||||
"no-global-assign": "warn",
|
||||
"no-import-assign": "warn",
|
||||
"no-invalid-regexp": "warn",
|
||||
"no-irregular-whitespace": "warn",
|
||||
"no-loss-of-precision": "warn",
|
||||
"no-new-native-nonconstructor": "warn",
|
||||
"no-nonoctal-decimal-escape": "warn",
|
||||
"no-obj-calls": "warn",
|
||||
"no-self-assign": "warn",
|
||||
"no-setter-return": "warn",
|
||||
"no-shadow-restricted-names": "warn",
|
||||
"no-sparse-arrays": "warn",
|
||||
"no-this-before-super": "warn",
|
||||
"no-unassigned-vars": "warn",
|
||||
"no-unsafe-finally": "warn",
|
||||
"no-unsafe-negation": "warn",
|
||||
"no-unsafe-optional-chaining": "warn",
|
||||
"no-unused-expressions": "warn",
|
||||
"no-unused-labels": "warn",
|
||||
"no-unused-private-class-members": "warn",
|
||||
"no-unused-vars": [
|
||||
"warn",
|
||||
{
|
||||
"caughtErrorsIgnorePattern": "^_",
|
||||
"argsIgnorePattern": "^_"
|
||||
}
|
||||
],
|
||||
"no-useless-backreference": "warn",
|
||||
"no-useless-catch": "warn",
|
||||
"no-useless-escape": "warn",
|
||||
"no-useless-rename": "warn",
|
||||
"no-with": "warn",
|
||||
"require-yield": "warn",
|
||||
"use-isnan": "warn",
|
||||
"valid-typeof": "warn",
|
||||
"oxc/bad-array-method-on-arguments": "warn",
|
||||
"oxc/bad-char-at-comparison": "warn",
|
||||
"oxc/bad-comparison-sequence": "warn",
|
||||
"oxc/bad-min-max-func": "warn",
|
||||
"oxc/bad-object-literal-comparison": "warn",
|
||||
"oxc/bad-replace-all-arg": "warn",
|
||||
"oxc/const-comparisons": "warn",
|
||||
"oxc/double-comparisons": "warn",
|
||||
"oxc/erasing-op": "warn",
|
||||
"oxc/missing-throw": "warn",
|
||||
"oxc/number-arg-out-of-range": "warn",
|
||||
"oxc/only-used-in-recursion": "warn",
|
||||
"oxc/uninvoked-array-callback": "warn",
|
||||
"typescript/await-thenable": "warn",
|
||||
"typescript/no-array-delete": "warn",
|
||||
"typescript/no-base-to-string": "warn",
|
||||
"typescript/no-duplicate-enum-values": "warn",
|
||||
"typescript/no-duplicate-type-constituents": "warn",
|
||||
"typescript/no-extra-non-null-assertion": "warn",
|
||||
"typescript/no-floating-promises": "warn",
|
||||
"typescript/no-for-in-array": "warn",
|
||||
"typescript/no-implied-eval": "warn",
|
||||
"typescript/no-meaningless-void-operator": "warn",
|
||||
"typescript/no-misused-new": "warn",
|
||||
"typescript/no-misused-spread": "warn",
|
||||
"typescript/no-non-null-asserted-optional-chain": "warn",
|
||||
"typescript/no-redundant-type-constituents": "warn",
|
||||
"typescript/no-this-alias": "warn",
|
||||
"typescript/no-unnecessary-parameter-property-assignment": "warn",
|
||||
"typescript/no-unsafe-declaration-merging": "warn",
|
||||
"typescript/no-unsafe-unary-minus": "warn",
|
||||
"typescript/no-useless-empty-export": "warn",
|
||||
"typescript/no-wrapper-object-types": "warn",
|
||||
"typescript/prefer-as-const": "warn",
|
||||
"typescript/require-array-sort-compare": "warn",
|
||||
"typescript/restrict-template-expressions": "warn",
|
||||
"typescript/triple-slash-reference": "warn",
|
||||
"typescript/unbound-method": "warn",
|
||||
"unicorn/no-await-in-promise-methods": "warn",
|
||||
"unicorn/no-empty-file": "warn",
|
||||
"unicorn/no-invalid-fetch-options": "warn",
|
||||
"unicorn/no-invalid-remove-event-listener": "warn",
|
||||
"unicorn/no-new-array": "warn",
|
||||
"unicorn/no-single-promise-in-promise-methods": "warn",
|
||||
"unicorn/no-thenable": "warn",
|
||||
"unicorn/no-unnecessary-await": "warn",
|
||||
"unicorn/no-useless-fallback-in-spread": "warn",
|
||||
"unicorn/no-useless-length-check": "warn",
|
||||
"unicorn/no-useless-spread": "warn",
|
||||
"unicorn/prefer-set-size": "warn",
|
||||
"unicorn/prefer-string-starts-ends-with": "warn",
|
||||
"import/no-cycle": "error",
|
||||
"eslint/no-console": ["warn", { "allow": ["warn", "error", "info"] }]
|
||||
},
|
||||
"settings": {
|
||||
"jsx-a11y": {
|
||||
"polymorphicPropName": null,
|
||||
"components": {},
|
||||
"attributes": {}
|
||||
},
|
||||
"next": {
|
||||
"rootDir": []
|
||||
},
|
||||
"react": {
|
||||
"formComponents": [],
|
||||
"linkComponents": [],
|
||||
"version": null
|
||||
},
|
||||
"jsdoc": {
|
||||
"ignorePrivate": false,
|
||||
"ignoreInternal": false,
|
||||
"ignoreReplacesDocs": true,
|
||||
"overrideReplacesDocs": true,
|
||||
"augmentsExtendsReplacesDocs": false,
|
||||
"implementsReplacesDocs": false,
|
||||
"exemptDestructuredRootsFromChecks": false,
|
||||
"tagNamePreference": {}
|
||||
},
|
||||
"vitest": {
|
||||
"typecheck": false
|
||||
}
|
||||
},
|
||||
"env": {
|
||||
"builtin": true
|
||||
},
|
||||
"globals": {},
|
||||
"ignorePatterns": ["**/api-client/**"],
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["**/*.test.ts", "**/*.test.tsx"],
|
||||
"rules": {
|
||||
"typescript/await-thenable": "off"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
1
.vite-hooks/pre-commit
Executable file
1
.vite-hooks/pre-commit
Executable file
|
|
@ -0,0 +1 @@
|
|||
vp staged
|
||||
3
.vscode/settings.json
vendored
Normal file
3
.vscode/settings.json
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode"
|
||||
}
|
||||
21
AGENTS.md
21
AGENTS.md
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
- Never create migration files manually. Always use the provided command to generate migrations
|
||||
- If you realize an automated migration is incorrect, make sure to remove all the associated entries from the `_journal.json` and the newly created files located in `app/drizzle/` before re-generating the migration
|
||||
- The dev server is running at http://localhost:3000. Username is `admin` and password is `password`
|
||||
- The dev server runs through Portless. Start it with `bun run dev`, then use `portless get zerobyte` to get the current worktree-specific URL. Do not assume a fixed port like `3000` or `4096`. Username is `admin` and password is `password`
|
||||
- The repo is https://github.com/nicotsx/zerobyte
|
||||
- If you need to run a specific restic command on a repository, you can open and use the dev panel with `Meta+Shift+D`
|
||||
|
||||
|
|
@ -10,6 +10,21 @@
|
|||
|
||||
Zerobyte is a backup automation tool built on top of Restic that provides a web interface for scheduling, managing, and monitoring encrypted backups. It supports multiple volume backends (NFS, SMB, WebDAV, SFTP, local directories) and repository backends (S3, Azure, GCS, local, and rclone-based storage).
|
||||
|
||||
### Development Server
|
||||
|
||||
```bash
|
||||
# Start the dev server through Portless
|
||||
bun run dev
|
||||
|
||||
# Get the current app URL for this worktree
|
||||
portless get zerobyte
|
||||
|
||||
# Inspect active Portless routes if needed
|
||||
portless list
|
||||
```
|
||||
|
||||
Portless applies git worktree prefixes automatically, so linked worktrees may return URLs like `https://branch-name.zerobyte.localhost`. Use the Portless URL for browser testing and manual verification.
|
||||
|
||||
### Type Checking
|
||||
|
||||
```bash
|
||||
|
|
@ -24,7 +39,7 @@ bun run tsc
|
|||
bun run test
|
||||
|
||||
# Run a specific test file
|
||||
bunx dotenv-cli -e .env.test -- bun test --preload ./app/test/setup.ts path/to/test.ts
|
||||
bunx dotenv-cli -e .env.test -- bunx --bun vitest run --project server path/to/test.ts
|
||||
```
|
||||
|
||||
### Building
|
||||
|
|
@ -55,7 +70,7 @@ bun run gen:api-client
|
|||
|
||||
```bash
|
||||
# Format
|
||||
bunx oxfmt format --write <path>
|
||||
vp fmt <path> --write
|
||||
|
||||
# Lint
|
||||
bun run lint
|
||||
|
|
|
|||
45
Dockerfile
45
Dockerfile
|
|
@ -1,10 +1,8 @@
|
|||
ARG BUN_VERSION="1.3.6"
|
||||
|
||||
FROM oven/bun:${BUN_VERSION}-alpine AS base
|
||||
FROM oven/bun:1.3.14-alpine@sha256:5acc90a93e91ff07bf72aa90a7c9f0fa189765aec90b47bdbf2152d2196383c0 AS base
|
||||
|
||||
ARG RESTIC_VERSION="0.18.1"
|
||||
ARG RCLONE_VERSION="1.73.1"
|
||||
ARG SHOUTRRR_VERSION="0.13.2"
|
||||
ARG RCLONE_VERSION="1.74.2"
|
||||
ARG SHOUTRRR_VERSION="0.15.1"
|
||||
|
||||
ENV VITE_RESTIC_VERSION=${RESTIC_VERSION} \
|
||||
VITE_RCLONE_VERSION=${RCLONE_VERSION} \
|
||||
|
|
@ -12,7 +10,7 @@ ENV VITE_RESTIC_VERSION=${RESTIC_VERSION} \
|
|||
|
||||
RUN apk update --no-cache && \
|
||||
apk upgrade --no-cache && \
|
||||
apk add --no-cache davfs2=1.6.1-r2 openssh-client fuse3 sshfs tini
|
||||
apk add --no-cache acl attr cifs-utils davfs2=1.6.1-r2 openssh-client fuse3 sshfs tini tzdata
|
||||
|
||||
ENTRYPOINT ["/sbin/tini", "-s", "--"]
|
||||
|
||||
|
|
@ -31,21 +29,30 @@ RUN apk add --no-cache curl bzip2 unzip tar
|
|||
|
||||
RUN echo "Building for ${TARGETARCH}"
|
||||
RUN if [ "${TARGETARCH}" = "arm64" ]; then \
|
||||
curl -L -o restic.bz2 "https://github.com/restic/restic/releases/download/v${RESTIC_VERSION}/restic_${RESTIC_VERSION}_linux_arm64.bz2"; \
|
||||
curl -L -o rclone.zip "https://github.com/rclone/rclone/releases/download/v${RCLONE_VERSION}/rclone-v${RCLONE_VERSION}-linux-arm64.zip"; \
|
||||
curl -fL -o restic.bz2 "https://github.com/restic/restic/releases/download/v${RESTIC_VERSION}/restic_${RESTIC_VERSION}_linux_arm64.bz2"; \
|
||||
curl -fL -o rclone.zip "https://github.com/rclone/rclone/releases/download/v${RCLONE_VERSION}/rclone-v${RCLONE_VERSION}-linux-arm64.zip"; \
|
||||
unzip rclone.zip; \
|
||||
curl -L -o shoutrrr.tar.gz "https://github.com/nicholas-fedor/shoutrrr/releases/download/v${SHOUTRRR_VERSION}/shoutrrr_linux_arm64v8_${SHOUTRRR_VERSION}.tar.gz"; \
|
||||
curl -fL -o shoutrrr.tar.gz "https://github.com/nicholas-fedor/shoutrrr/releases/download/v${SHOUTRRR_VERSION}/shoutrrr_linux_arm64v8_${SHOUTRRR_VERSION}.tar.gz"; \
|
||||
elif [ "${TARGETARCH}" = "amd64" ]; then \
|
||||
curl -L -o restic.bz2 "https://github.com/restic/restic/releases/download/v${RESTIC_VERSION}/restic_${RESTIC_VERSION}_linux_amd64.bz2"; \
|
||||
curl -L -o rclone.zip "https://github.com/rclone/rclone/releases/download/v${RCLONE_VERSION}/rclone-v${RCLONE_VERSION}-linux-amd64.zip"; \
|
||||
curl -fL -o restic.bz2 "https://github.com/restic/restic/releases/download/v${RESTIC_VERSION}/restic_${RESTIC_VERSION}_linux_amd64.bz2"; \
|
||||
curl -fL -o rclone.zip "https://github.com/rclone/rclone/releases/download/v${RCLONE_VERSION}/rclone-v${RCLONE_VERSION}-linux-amd64.zip"; \
|
||||
unzip rclone.zip; \
|
||||
curl -L -o shoutrrr.tar.gz "https://github.com/nicholas-fedor/shoutrrr/releases/download/v$SHOUTRRR_VERSION/shoutrrr_linux_amd64_${SHOUTRRR_VERSION}.tar.gz"; \
|
||||
curl -fL -o shoutrrr.tar.gz "https://github.com/nicholas-fedor/shoutrrr/releases/download/v$SHOUTRRR_VERSION/shoutrrr_linux_amd64_${SHOUTRRR_VERSION}.tar.gz"; \
|
||||
fi
|
||||
|
||||
RUN bzip2 -d restic.bz2 && chmod +x restic
|
||||
RUN mv rclone-v*-linux-*/rclone /deps/rclone && chmod +x /deps/rclone
|
||||
RUN tar -xzf shoutrrr.tar.gz && chmod +x shoutrrr
|
||||
|
||||
# ------------------------------
|
||||
# RUNTIME TOOLS
|
||||
# ------------------------------
|
||||
FROM base AS runtime-tools
|
||||
|
||||
COPY --from=deps /deps/restic /usr/local/bin/restic
|
||||
COPY --from=deps /deps/rclone /usr/local/bin/rclone
|
||||
COPY --from=deps /deps/shoutrrr /usr/local/bin/shoutrrr
|
||||
|
||||
# ------------------------------
|
||||
# DEVELOPMENT
|
||||
# ------------------------------
|
||||
|
|
@ -63,8 +70,12 @@ COPY --from=deps /deps/rclone /usr/local/bin/rclone
|
|||
COPY --from=deps /deps/shoutrrr /usr/local/bin/shoutrrr
|
||||
|
||||
COPY ./package.json ./bun.lock ./
|
||||
COPY ./packages/core/package.json ./packages/core/package.json
|
||||
COPY ./packages/contracts/package.json ./packages/contracts/package.json
|
||||
COPY ./apps/agent/package.json ./apps/agent/package.json
|
||||
COPY ./apps/docs/package.json ./apps/docs/package.json
|
||||
|
||||
RUN bun install --frozen-lockfile --ignore-scripts
|
||||
RUN VITE_GIT_HOOKS=0 bun install --frozen-lockfile --ignore-scripts
|
||||
|
||||
COPY . .
|
||||
|
||||
|
|
@ -84,11 +95,17 @@ ENV PORT=4096
|
|||
WORKDIR /app
|
||||
|
||||
COPY ./package.json ./bun.lock ./
|
||||
RUN bun install --frozen-lockfile
|
||||
COPY ./packages/core/package.json ./packages/core/package.json
|
||||
COPY ./packages/contracts/package.json ./packages/contracts/package.json
|
||||
COPY ./apps/agent/package.json ./apps/agent/package.json
|
||||
COPY ./apps/docs/package.json ./apps/docs/package.json
|
||||
|
||||
RUN VITE_GIT_HOOKS=0 bun install --frozen-lockfile
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN bun run build
|
||||
RUN bun build apps/agent/src/index.ts --outfile .output/agent/index.mjs --target bun
|
||||
|
||||
FROM base AS production
|
||||
|
||||
|
|
|
|||
162
README.md
162
README.md
|
|
@ -15,23 +15,33 @@
|
|||
</figure>
|
||||
</div>
|
||||
|
||||
#### Join the community
|
||||
|
||||
[](https://discord.gg/XjgVyXrcEH)
|
||||
|
||||
> [!WARNING]
|
||||
> Zerobyte is still in version 0.x.x and is subject to major changes from version to version. I am developing the core features and collecting feedbacks. Expect bugs! Please open issues or feature requests
|
||||
> Zerobyte is still in version 0.x.x and is subject to major changes from version to version. I am developing the core features and collecting feedback. Please open issues for bugs or feature requests.
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.buymeacoffee.com/nicotsx" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
|
||||
</p>
|
||||
|
||||
## Intro
|
||||
## Introduction
|
||||
|
||||
Zerobyte is a backup automation tool that helps you save your data across multiple storage backends. Built on top of Restic, it provides an modern web interface to schedule, manage, and monitor encrypted backups of your remote storage.
|
||||
|
||||
## Documentation
|
||||
|
||||
The official documentation website is available at [zerobyte.app](https://zerobyte.app).
|
||||
|
||||
It contains up-to-date setup guides, configuration reference, and usage documentation for running Zerobyte in production.
|
||||
|
||||
### Features
|
||||
|
||||
- **Automated backups** with encryption, compression and retention policies powered by Restic
|
||||
- **Flexible scheduling** For automated backup jobs with fine-grained retention policies
|
||||
- **End-to-end encryption** ensuring your data is always protected
|
||||
- **Multi-protocol support**: Backup from NFS, SMB, WebDAV, SFTP, or local directories
|
||||
- **Automated backups** with encryption, compression, and retention policies, powered by Restic
|
||||
- **Flexible scheduling** for automated backup jobs with fine-grained retention policies
|
||||
- **End-to-end encryption** will ensure your data is always protected
|
||||
- **Multi-protocol support** for backup from NFS, SMB, WebDAV, SFTP, or local directories
|
||||
|
||||
## Installation
|
||||
|
||||
|
|
@ -40,7 +50,7 @@ In order to run Zerobyte, you need to have Docker and Docker Compose installed o
|
|||
```yaml
|
||||
services:
|
||||
zerobyte:
|
||||
image: ghcr.io/nicotsx/zerobyte:v0.29
|
||||
image: ghcr.io/nicotsx/zerobyte:v0.38
|
||||
container_name: zerobyte
|
||||
restart: unless-stopped
|
||||
cap_add:
|
||||
|
|
@ -50,7 +60,7 @@ services:
|
|||
devices:
|
||||
- /dev/fuse:/dev/fuse
|
||||
environment:
|
||||
- TZ=Europe/Paris # Set your timezone here
|
||||
- TZ=Europe/Zurich # Set your timezone here
|
||||
- BASE_URL=http://localhost:4096 # URL you will use to access Zerobyte
|
||||
- APP_SECRET=94bad46...c66e25d5c2b # Generate your own secret with `openssl rand -hex 32`
|
||||
volumes:
|
||||
|
|
@ -59,10 +69,10 @@ services:
|
|||
```
|
||||
|
||||
> [!WARNING]
|
||||
> It is highly discouraged to run Zerobyte on a server that is accessible from the internet (VPS or home server with port forwarding) If you do, make sure to change the port mapping to "127.0.0.1:4096:4096" and use a secure tunnel (SSH tunnel, Cloudflare Tunnel, etc.) with authentication.
|
||||
> It is highly discouraged to run Zerobyte on a server that is accessible from the internet (VPS or home server with port forwarding). If you do, make sure to change the port mapping to "127.0.0.1:4096:4096" and use a secure tunnel (SSH tunnel, Cloudflare Tunnel, etc.) with authentication.
|
||||
|
||||
> [!WARNING]
|
||||
> Do not try to point `/var/lib/zerobyte` on a network share. You will face permission issues and strong performance degradation.
|
||||
> Do not try to point `/var/lib/zerobyte` to a network share. You will face permission issues and strong performance degradation.
|
||||
|
||||
> [!NOTE]
|
||||
> **TrueNAS Users:** The host path `/var/lib` is ephemeral on TrueNAS and will be reset during system upgrades. Instead of using `/var/lib/zerobyte:/var/lib/zerobyte`, create a dedicated ZFS dataset (e.g., `tank/docker/zerobyte`) and mount it instead:
|
||||
|
|
@ -87,44 +97,72 @@ Once the container is running, you can access the web interface at `http://<your
|
|||
|
||||
Zerobyte can be customized using environment variables. Below are the available options:
|
||||
|
||||
### Environment Variables
|
||||
### Environment variables
|
||||
|
||||
| Variable | Description | Default |
|
||||
| :-------------------- | :---------------------------------------------------------------------------------------------------------------------------------------- | :--------------------- |
|
||||
| `BASE_URL` | **Required.** The base URL of your Zerobyte instance (e.g., `https://zerobyte.example.com`). See [Authentication](#authentication) below. | (none) |
|
||||
| `APP_SECRET` | **Required.** A random secret key (32+ chars) used to encrypt sensitive data in the database. Generate with `openssl rand -hex 32`. | (none) |
|
||||
| `PORT` | The port the web interface and API will listen on. | `4096` |
|
||||
| `RESTIC_HOSTNAME` | The hostname used by Restic when creating snapshots. Automatically detected if a custom hostname is set in Docker. | `zerobyte` |
|
||||
| `TZ` | Timezone for the container (e.g., `Europe/Paris`). **Crucial for accurate backup scheduling.** | `UTC` |
|
||||
| `TRUSTED_ORIGINS` | Comma-separated list of extra trusted origins for CORS (e.g., `http://localhost:3000,http://example.com`). | (none) |
|
||||
| `LOG_LEVEL` | Logging verbosity. Options: `debug`, `info`, `warn`, `error`. | `info` |
|
||||
| `SERVER_IDLE_TIMEOUT` | Idle timeout for the server in seconds. | `60` |
|
||||
| `RCLONE_CONFIG_DIR` | Path to the rclone config directory inside the container. Change this if running as a non-root user. | `/root/.config/rclone` |
|
||||
| Variable | Description | Default |
|
||||
| :------------------------ | :---------------------------------------------------------------------------------------------------------------------------------------- | :--------------------- |
|
||||
| `BASE_URL` | **Required.** The base URL of your Zerobyte instance (e.g., `https://zerobyte.example.com`). See [Authentication](#authentication) below. | (none) |
|
||||
| `APP_SECRET` | **Required.** A random secret key (32+ chars) used to encrypt sensitive data in the database. Generate with `openssl rand -hex 32`. | (none) |
|
||||
| `APP_SECRET_FILE` | Path to a file containing `APP_SECRET`, useful with Docker or Kubernetes secrets. Mutually exclusive with `APP_SECRET`. | (none) |
|
||||
| `PORT` | The port the web interface and API will listen on. | `4096` |
|
||||
| `RESTIC_HOSTNAME` | The hostname used by Restic when creating snapshots. Automatically detected if a custom hostname is set in Docker. | `zerobyte` |
|
||||
| `TZ` | Timezone for the container (e.g., `Europe/Zurich`). **Crucial for accurate backup scheduling.** | `UTC` |
|
||||
| `TRUST_PROXY` | When `true`, trust an existing `X-Forwarded-For` header from your reverse proxy. Leave `false` for direct deployments. | `false` |
|
||||
| `TRUSTED_ORIGINS` | Comma-separated list of extra trusted origins for CORS (e.g., `http://localhost:3000,http://example.com`). | (none) |
|
||||
| `WEBHOOK_ALLOWED_ORIGINS` | Comma-separated list of HTTP origins allowed for backup webhooks and outbound HTTP notification destinations. | (none) |
|
||||
| `WEBHOOK_TIMEOUT` | Timeout for backup webhook requests in seconds. | `60` |
|
||||
| `LOG_LEVEL` | Logging verbosity. Options: `debug`, `info`, `warn`, `error`. | `info` |
|
||||
| `SERVER_IDLE_TIMEOUT` | Idle timeout for the server in seconds. | `60` |
|
||||
| `RCLONE_CONFIG_DIR` | Path to the directory containing `rclone.conf` inside the container. Change this if running as a non-root user. | `/root/.config/rclone` |
|
||||
| `PROVISIONING_PATH` | Path to a JSON file with operator-managed repositories and volumes to sync at startup. | (none) |
|
||||
|
||||
### Secret References
|
||||
### Webhook and notification network policy
|
||||
|
||||
For enhanced security, Zerobyte supports dynamic secret resolution for sensitive fields (like passwords, access keys, etc.) in volume and repository configurations. Instead of storing the encrypted secret in the database, you can use one of the following prefixes:
|
||||
Backup webhooks and outbound notification destinations that can target arbitrary network hosts are restricted by `WEBHOOK_ALLOWED_ORIGINS`.
|
||||
|
||||
- `env://VAR_NAME`: Reads the secret from the environment variable `VAR_NAME`.
|
||||
- `file://SECRET_NAME`: Reads the secret from `/run/secrets/SECRET_NAME` (standard Docker Secrets path).
|
||||
The allowlist matches exact origins only: scheme, host, and port must match. Paths are ignored, so `https://hooks.example.com/backups` allows any path on `https://hooks.example.com`, but it does not allow `http://hooks.example.com`, `https://hooks.example.com:8443`, or `https://other.example.com`.
|
||||
|
||||
**Example:**
|
||||
When configuring an S3 repository, you can set the Secret Access Key to `env://S3_SECRET_KEY` and then provide that variable in your `docker-compose.yml`.
|
||||
This policy applies to:
|
||||
|
||||
### Simplified setup (No remote mounts)
|
||||
- backup pre/post webhook URLs
|
||||
- Generic HTTP notification URLs
|
||||
- Gotify server URLs
|
||||
- self-hosted ntfy server URLs
|
||||
- custom Shoutrrr URLs that point at generic HTTP or SMTP network targets
|
||||
|
||||
If you only need to back up locally mounted folders and don't require remote share mounting capabilities, you can remove the `SYS_ADMIN` capability and FUSE device from your `docker-compose.yml`:
|
||||
The public ntfy.sh service and fixed-provider notification services such as Slack, Discord, Pushover, and Telegram do not need `WEBHOOK_ALLOWED_ORIGINS`.
|
||||
|
||||
Backup webhooks do not follow redirects. Add the final destination origin to `WEBHOOK_ALLOWED_ORIGINS` and configure that final URL directly.
|
||||
|
||||
Webhook headers are stored as plain text and must use one `Key: Value` header per line. `WEBHOOK_TIMEOUT` controls backup pre/post webhook request timeouts; notification delivery uses the underlying provider sender behavior.
|
||||
|
||||
### Provisioned resources
|
||||
|
||||
Zerobyte can sync operator-managed repositories and volumes from a JSON file at startup. This is useful when you want credentials or connection details to live in deployment-time configuration instead of being entered through the UI.
|
||||
|
||||
Provisioned resources:
|
||||
|
||||
- appear in the normal repositories and volumes screens
|
||||
- can resolve credential fields from environment variables or `/run/secrets/*` during startup sync
|
||||
|
||||
The complete provisioning documentation is available at [zerobyte.app/docs/guides/provisioning](https://zerobyte.app/docs/guides/provisioning).
|
||||
|
||||
See `examples/provisioned-resources/README.md` for a full example.
|
||||
|
||||
### Simplified setup (no remote mounts)
|
||||
|
||||
If you only need to back up locally-mounted folders and don't require remote share mounting capabilities, you can remove the `SYS_ADMIN` capability and FUSE device from your `docker-compose.yml`:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
zerobyte:
|
||||
image: ghcr.io/nicotsx/zerobyte:v0.29
|
||||
image: ghcr.io/nicotsx/zerobyte:v0.38
|
||||
container_name: zerobyte
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "4096:4096"
|
||||
environment:
|
||||
- TZ=Europe/Paris # Set your timezone here
|
||||
- TZ=Europe/Zurich # Set your timezone here
|
||||
- BASE_URL=http://localhost:4096 # Change this to your actual URL (use https:// for secure cookies)
|
||||
- APP_SECRET=94bad46...c66e25d5c2b # Generate your own secret with `openssl rand -hex 32`
|
||||
volumes:
|
||||
|
|
@ -136,8 +174,8 @@ services:
|
|||
**Trade-offs:**
|
||||
|
||||
- ✅ Improved security by reducing container capabilities
|
||||
- ✅ Support for local directories
|
||||
- ✅ Keep support all repository types (local, S3, GCS, Azure, rclone)
|
||||
- ✅ Support for local directories as backup sources
|
||||
- ✅ Support all repository types, local and remote (S3, GCS, Azure, rclone)
|
||||
- ❌ Cannot mount NFS, SMB, WebDAV, or SFTP shares directly from Zerobyte
|
||||
|
||||
If you need remote mount capabilities, keep the original configuration with `cap_add: SYS_ADMIN` and `devices: /dev/fuse:/dev/fuse`.
|
||||
|
|
@ -152,12 +190,12 @@ Zerobyte supports multiple volume backends including NFS, SMB, WebDAV, SFTP, and
|
|||
|
||||
To add your first volume, navigate to the "Volumes" section in the web interface and click on "Create volume". Fill in the required details such as volume name, type, and connection settings.
|
||||
|
||||
If you want to track a local directory on the same server where Zerobyte is running, you'll first need to mount that directory into the Zerobyte container. You can do this by adding a volume mapping in your `docker-compose.yml` file. For example, to mount `/path/to/your/directory` from the host to `/mydata` in the container, you would add the following line under the `volumes` section:
|
||||
If you want to backup a local directory on the same host where Zerobyte is running, you'll first need to mount that directory into the Zerobyte container. You can do this by adding a volume mapping in your `docker-compose.yml` file. For example, to mount `/path/to/your/directory` from the host to `/mydata` in the container, you would add the following line under the `volumes` section:
|
||||
|
||||
```diff
|
||||
services:
|
||||
zerobyte:
|
||||
image: ghcr.io/nicotsx/zerobyte:v0.29
|
||||
image: ghcr.io/nicotsx/zerobyte:v0.38
|
||||
container_name: zerobyte
|
||||
restart: unless-stopped
|
||||
cap_add:
|
||||
|
|
@ -167,7 +205,7 @@ services:
|
|||
devices:
|
||||
- /dev/fuse:/dev/fuse
|
||||
environment:
|
||||
- TZ=Europe/Paris
|
||||
- TZ=Europe/Zurich
|
||||
- BASE_URL=http://localhost:4096 # URL you will use to access Zerobyte
|
||||
- APP_SECRET=94bad46...c66e25d5c2b # Generate your own secret with `openssl rand -hex 32`
|
||||
volumes:
|
||||
|
|
@ -185,17 +223,17 @@ docker compose up -d
|
|||
|
||||
Now, when adding a new volume in the Zerobyte web interface, you can select "Directory" as the volume type and search for your mounted path (e.g., `/mydata`) as the source path.
|
||||
|
||||

|
||||

|
||||
|
||||
## Creating a repository
|
||||
|
||||
A repository is where your backups will be securely stored encrypted. Zerobyte supports multiple storage backends for your backup repositories:
|
||||
|
||||
- **Local directories** - Store backups on local disk subfolder of `/var/lib/zerobyte/repositories/` or any other (mounted) path
|
||||
- **S3-compatible storage** - Amazon S3, MinIO, Wasabi, DigitalOcean Spaces, etc.
|
||||
- **Google Cloud Storage** - Google's cloud storage service
|
||||
- **Azure Blob Storage** - Microsoft Azure storage
|
||||
- **rclone remotes** - 40+ cloud storage providers via rclone (see below)
|
||||
- **Local directories**: Store backups on local disk subfolders in `/var/lib/zerobyte/repositories/` or any other (mounted) path
|
||||
- **S3-compatible storage**: Amazon S3, MinIO, Wasabi, DigitalOcean Spaces, etc.
|
||||
- **Google Cloud Storage**: Google's cloud storage service
|
||||
- **Azure Blob Storage**: Microsoft Azure storage
|
||||
- **rclone remotes**: 40+ cloud storage providers via rclone (see below)
|
||||
|
||||
Repositories are optimized for storage efficiency and data integrity, leveraging Restic's deduplication and encryption features.
|
||||
|
||||
|
|
@ -232,7 +270,7 @@ Zerobyte can use [rclone](https://rclone.org/) to support 40+ cloud storage prov
|
|||
```diff
|
||||
services:
|
||||
zerobyte:
|
||||
image: ghcr.io/nicotsx/zerobyte:v0.29
|
||||
image: ghcr.io/nicotsx/zerobyte:v0.38
|
||||
container_name: zerobyte
|
||||
restart: unless-stopped
|
||||
cap_add:
|
||||
|
|
@ -242,7 +280,7 @@ Zerobyte can use [rclone](https://rclone.org/) to support 40+ cloud storage prov
|
|||
devices:
|
||||
- /dev/fuse:/dev/fuse
|
||||
environment:
|
||||
- TZ=Europe/Paris
|
||||
- TZ=Europe/Zurich
|
||||
- BASE_URL=http://localhost:4096 # URL you will use to access Zerobyte
|
||||
volumes:
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
|
|
@ -250,7 +288,7 @@ Zerobyte can use [rclone](https://rclone.org/) to support 40+ cloud storage prov
|
|||
+ - ~/.config/rclone:/root/.config/rclone:ro
|
||||
```
|
||||
|
||||
> **Note for non-root users:** If your container runs as a different user (e.g., TrueNAS apps), mount your config to the appropriate location and set `RCLONE_CONF_DIR`:
|
||||
> **Note for non-root users:** If your container runs as a different user (e.g., TrueNAS apps), mount your config to the appropriate location and set `RCLONE_CONFIG_DIR`:
|
||||
>
|
||||
> ```yaml
|
||||
> environment:
|
||||
|
|
@ -286,24 +324,30 @@ When creating a backup job, you can specify the following settings:
|
|||
After configuring the backup job, save it and Zerobyte will automatically execute the backup according to the defined schedule.
|
||||
You can monitor the progress and status of your backup jobs in the "Backups" section of the web interface.
|
||||
|
||||

|
||||

|
||||
|
||||
## Restoring data
|
||||
|
||||
Zerobyte allows you to easily restore your data from backups. To restore data, navigate to the "Backups" section and select the backup job from which you want to restore data. You can then choose a specific backup snapshot and select the files or directories you wish to restore. The data you select will be restored to their original location.
|
||||
|
||||

|
||||

|
||||
|
||||
## Authentication
|
||||
|
||||
Zerobyte uses [better-auth](https://github.com/better-auth/better-auth) for authentication and session management. The authentication system automatically adapts to your deployment scenario:
|
||||
|
||||
### Cookie Security
|
||||
### Users and roles
|
||||
|
||||
- **IP Address / HTTP access**: Set `BASE_URL=http://192.168.1.50:4096` (or your IP). Cookies will use `Secure: false`, allowing immediate login without SSL.
|
||||
- **Domain / HTTPS access**: Set `BASE_URL=https://zerobyte.example.com`. Cookies will automatically use `Secure: true` for protected sessions.
|
||||
Zerobyte does not currently provide fine-grained RBAC for backup operations. Authenticated organization members are trusted operators for repositories, volumes, backup schedules, restores, and notification destinations in their organization.
|
||||
|
||||
### Reverse Proxy Setup
|
||||
Organization roles mainly restrict organization-management and instance-management actions. For example, normal members cannot manage members, SSO settings, invitations, registration, or global users, but they can still operate backup resources. Only add users to an organization if you are comfortable with them using the storage, volume, and notification capabilities configured for the instance.
|
||||
|
||||
### Cookie security
|
||||
|
||||
- **IP Address/HTTP access**: Set `BASE_URL=http://192.168.1.50:4096` (or your IP). Cookies will use `Secure: false`, allowing immediate login without SSL.
|
||||
- **Domain/HTTPS access**: Set `BASE_URL=https://zerobyte.example.com`. Cookies will automatically use `Secure: true` for protected sessions.
|
||||
|
||||
### Reverse proxy setup
|
||||
|
||||
If you're running Zerobyte behind a reverse proxy (Nginx, Traefik, Caddy, etc.):
|
||||
|
||||
|
|
@ -311,16 +355,18 @@ If you're running Zerobyte behind a reverse proxy (Nginx, Traefik, Caddy, etc.):
|
|||
2. The app will automatically enable secure cookies based on the `https://` prefix
|
||||
3. Ensure your proxy passes the `X-Forwarded-Proto` header
|
||||
|
||||
### Important Notes
|
||||
### Important notes
|
||||
|
||||
- The `BASE_URL` must start with `https://` for secure cookies to be enabled
|
||||
- Local IP addresses (e.g., `http://192.168.x.x`) are **not** treated as secure contexts by browsers, so secure cookies are disabled automatically
|
||||
- `TRUSTED_ORIGINS` only allows additional origins for auth-related requests. It does not disable secure cookies or make authenticated HTTP access work when `BASE_URL` is HTTPS.
|
||||
- If `BASE_URL` is HTTPS, browsers will only send Zerobyte's auth cookies over HTTPS. Plain HTTP access may still show the login page, but authenticated flows will fail because no session cookie is available.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
For troubleshooting common issues, please refer to the [TROUBLESHOOTING.md](TROUBLESHOOTING.md) file.
|
||||
|
||||
## Third-Party Software
|
||||
## Third-party software
|
||||
|
||||
This project includes the following third-party software components:
|
||||
|
||||
|
|
@ -341,10 +387,10 @@ Contributions by anyone are welcome! If you find a bug or have a feature request
|
|||
|
||||
## Development (no Docker)
|
||||
|
||||
You can run Zerobyte locally during development without Docker:
|
||||
After installing Vite+ globally, you can run Zerobyte locally during development without Docker:
|
||||
|
||||
```bash
|
||||
bun install
|
||||
vp install
|
||||
bun run dev
|
||||
```
|
||||
|
||||
|
|
@ -358,10 +404,10 @@ RESTIC_PASS_FILE=./data/restic.pass
|
|||
RESTIC_CACHE_DIR=./data/restic/cache
|
||||
ZEROBYTE_REPOSITORIES_DIR=./data/repositories
|
||||
ZEROBYTE_VOLUMES_DIR=./data/volumes
|
||||
BASE_URL=http://localhost:4096
|
||||
BASE_URL=https://*.localhost
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- Remote mount backends (NFS/SMB/WebDAV/SFTP) rely on Linux mount tooling and `CAP_SYS_ADMIN`; on macOS they are expected to be unavailable.
|
||||
- To actually run backups/repository checks, install `restic` on your machine (e.g. via Homebrew). If `restic` is not installed, the app still starts but backup operations will fail with a clear error.
|
||||
- To actually run backups/repository checks, install `restic` on your machine (e.g., via Homebrew). If `restic` is not installed, the app still starts but backup operations will fail with a clear error.
|
||||
|
|
|
|||
75
SECURITY.md
Normal file
75
SECURITY.md
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
# Security Policy
|
||||
|
||||
Thank you for helping keep Zerobyte and its users secure.
|
||||
|
||||
Zerobyte is currently in `0.x`, and releases may include breaking changes between versions. For that reason, security fixes are only guaranteed for the most recent stable release line.
|
||||
|
||||
## Supported Versions
|
||||
|
||||
| Version | Supported |
|
||||
| --------------------------------------------- | ------------------ |
|
||||
| Latest stable `0.x` release | :white_check_mark: |
|
||||
| Older stable `0.x` releases | :x: |
|
||||
| Pre-release builds (`-alpha`, `-beta`, `-rc`) | :x: |
|
||||
| Development snapshots from `main` | :x: |
|
||||
|
||||
Security fixes are generally released in the latest stable version only. If you are running an older release, you may be asked to upgrade before a fix is provided.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Please do **not** report security vulnerabilities through public GitHub issues, discussions, or pull requests.
|
||||
|
||||
Use one of these private channels instead:
|
||||
|
||||
1. Preferred: GitHub private vulnerability reporting
|
||||
https://github.com/nicotsx/zerobyte/security/advisories/new
|
||||
2. Alternative: contact the maintainer directly by email if an address is listed in the repository or GitHub profile
|
||||
|
||||
When reporting, include as much of the following as you can:
|
||||
|
||||
- affected Zerobyte version
|
||||
- deployment details, including whether you are using Docker, reverse proxies, or exposed ports
|
||||
- clear reproduction steps or a proof of concept
|
||||
- impact assessment and what an attacker could do
|
||||
- any relevant logs, screenshots, or configuration excerpts with secrets removed
|
||||
|
||||
### What to expect
|
||||
|
||||
- We aim to acknowledge new reports within 7 days.
|
||||
- We aim to provide status updates at least every 7 days while the report is being investigated.
|
||||
- If the report is accepted, we will work on a fix, coordinate disclosure, and publish a security advisory when appropriate.
|
||||
- If the report is declined, out of scope, or cannot be reproduced, we will explain why when possible.
|
||||
|
||||
Please avoid public disclosure until a fix has been released and maintainers have had reasonable time to notify users.
|
||||
|
||||
## Trust model baseline
|
||||
|
||||
Zerobyte is a self-hosted operator tool. Treat any authenticated user as a trusted machine/operator user with intentional access to:
|
||||
|
||||
- Browse/select host directories for volumes
|
||||
- Configure local, network, and cloud storage backends
|
||||
- Trigger mounts/unmounts, backups, restores, and Restic maintenance
|
||||
- Read/write files through intended backup/restore workflows
|
||||
- Access repository/volume metadata needed to operate backups
|
||||
|
||||
Do **not** report these as vulnerabilities by themselves:
|
||||
|
||||
- Authenticated host filesystem browsing
|
||||
- Local directory volume pointing to broad host paths
|
||||
- Backing up arbitrary readable host paths
|
||||
- Restoring snapshots to arbitrary writable host paths
|
||||
- Authenticated Restic/mount/rclone execution through intended UI flows
|
||||
- Information disclosure to authenticated operators about filesystem paths or backend errors
|
||||
|
||||
Only report issues when they violate this trust model, for example:
|
||||
|
||||
- Unauthenticated access to operator features
|
||||
- CSRF/cross-origin abuse causing a trusted operator’s browser to perform actions
|
||||
- Shell/command injection beyond intended argument-based execution
|
||||
- Path traversal that escapes a deliberately configured root/volume/repository boundary
|
||||
- Secret leakage to logs, unauthenticated users, or non-operator contexts
|
||||
- Cross-organization data access despite authenticated trust
|
||||
- Privilege bypass between global admin/org admin/member where the product explicitly distinguishes roles
|
||||
- Unsafe dev-only features enabled without the documented gate
|
||||
- Vulnerabilities in parsing untrusted external data from repositories/backends/notifications
|
||||
- Persistence corruption, data loss, or workflow bypass not intended by operator actions
|
||||
|
|
@ -283,9 +283,8 @@ If you're experiencing rclone issues, verify all of the following:
|
|||
**Diagnosis:**
|
||||
|
||||
```bash
|
||||
# Check if config is accessible inside container
|
||||
docker exec zerobyte ls -la /root/.config/rclone/
|
||||
docker exec zerobyte cat /root/.config/rclone/rclone.conf
|
||||
# Check which config file rclone will use inside the container
|
||||
docker exec zerobyte sh -lc 'echo HOME=$HOME; rclone config file'
|
||||
```
|
||||
|
||||
**Solutions:**
|
||||
|
|
|
|||
90
app/app.css
90
app/app.css
|
|
@ -37,7 +37,6 @@ body {
|
|||
}
|
||||
|
||||
body {
|
||||
@apply bg-[#131313];
|
||||
min-height: 100dvh;
|
||||
}
|
||||
|
||||
|
|
@ -67,6 +66,8 @@ body {
|
|||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-destructive-foreground: var(--destructive-foreground);
|
||||
--color-success: var(--success);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
|
|
@ -88,38 +89,40 @@ body {
|
|||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--card-header: oklch(0.922 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--background: oklch(0.98 0.002 250);
|
||||
--foreground: oklch(0.20 0.01 260);
|
||||
--card: #ffffff;
|
||||
--card-foreground: oklch(0.20 0.01 260);
|
||||
--card-header: oklch(0.99 0.001 260);
|
||||
--popover: #ffffff;
|
||||
--popover-foreground: oklch(0.20 0.01 260);
|
||||
--primary: oklch(0.20 0.01 260);
|
||||
--primary-foreground: #ffffff;
|
||||
--secondary: oklch(0.96 0.005 260);
|
||||
--secondary-foreground: oklch(0.20 0.01 260);
|
||||
--muted: oklch(0.95 0.005 260);
|
||||
--muted-foreground: oklch(0.45 0.01 260);
|
||||
--accent: oklch(0.96 0.005 260);
|
||||
--accent-foreground: oklch(0.20 0.01 260);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
--destructive-foreground: #fff;
|
||||
--success: oklch(0.57 0.16 148);
|
||||
--border: oklch(0.90 0.01 260);
|
||||
--input: oklch(0.90 0.01 260);
|
||||
--ring: oklch(0.7 0.01 260);
|
||||
--chart-1: oklch(0.55 0.22 260);
|
||||
--chart-2: oklch(0.6 0.15 200);
|
||||
--chart-3: oklch(0.45 0.12 280);
|
||||
--chart-4: oklch(0.7 0.15 190);
|
||||
--chart-5: oklch(0.55 0.18 300);
|
||||
--sidebar: #ffffff;
|
||||
--sidebar-foreground: oklch(0.35 0.01 260);
|
||||
--sidebar-primary: oklch(0.20 0.01 260);
|
||||
--sidebar-primary-foreground: #ffffff;
|
||||
--sidebar-accent: oklch(0.97 0.005 260);
|
||||
--sidebar-accent-foreground: oklch(0.20 0.01 260);
|
||||
--sidebar-border: oklch(0.90 0.01 260);
|
||||
--sidebar-ring: oklch(0.7 0.01 260);
|
||||
--strong-accent: #ff543a;
|
||||
}
|
||||
|
||||
|
|
@ -144,6 +147,8 @@ body {
|
|||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: #ff543a;
|
||||
--destructive-foreground: #fff;
|
||||
--success: oklch(0.696 0.17 162.48);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
|
|
@ -174,11 +179,11 @@ body {
|
|||
|
||||
@layer base {
|
||||
:root {
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--chart-1: oklch(0.55 0.22 260);
|
||||
--chart-2: oklch(0.6 0.15 200);
|
||||
--chart-3: oklch(0.45 0.12 280);
|
||||
--chart-4: oklch(0.7 0.15 190);
|
||||
--chart-5: oklch(0.55 0.18 300);
|
||||
}
|
||||
|
||||
.dark {
|
||||
|
|
@ -190,6 +195,17 @@ body {
|
|||
}
|
||||
}
|
||||
|
||||
.snapshot-scrollable::-webkit-scrollbar {
|
||||
height: 6px;
|
||||
}
|
||||
.snapshot-scrollable::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
.snapshot-scrollable::-webkit-scrollbar-thumb {
|
||||
background: var(--border);
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
/* Hide built-in password reveal/clear controls (notably in Edge on Windows) */
|
||||
[data-secret-input] input[type="password"]::-ms-reveal,
|
||||
[data-secret-input] input[type="password"]::-ms-clear {
|
||||
|
|
|
|||
20
app/client.tsx
Normal file
20
app/client.tsx
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import { StrictMode, startTransition } from "react";
|
||||
import { hydrateRoot } from "react-dom/client";
|
||||
import { StartClient } from "@tanstack/react-start/client";
|
||||
import { parseError } from "./client/lib/errors";
|
||||
|
||||
startTransition(() => {
|
||||
hydrateRoot(
|
||||
document,
|
||||
<StrictMode>
|
||||
<StartClient />
|
||||
</StrictMode>,
|
||||
{
|
||||
onRecoverableError: (error, errorInfo) => {
|
||||
console.error(
|
||||
`[react-recoverable-error] ${parseError(error)?.message}${errorInfo.componentStack ? `\n${errorInfo.componentStack.trim()}` : ""}`,
|
||||
);
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
|
|
@ -4,8 +4,8 @@
|
|||
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
|
||||
|
||||
import { client } from '../client.gen';
|
||||
import { browseFilesystem, cancelDoctor, createBackupSchedule, createNotificationDestination, createRepository, createVolume, deleteBackupSchedule, deleteNotificationDestination, deleteRepository, deleteSnapshot, deleteSnapshots, deleteSsoInvitation, deleteSsoProvider, deleteUserAccount, deleteVolume, devPanelExec, downloadResticPassword, dumpSnapshot, getAdminUsers, getBackupProgress, getBackupSchedule, getBackupScheduleForVolume, getDevPanel, getMirrorCompatibility, getNotificationDestination, getOrgMembers, getPublicSsoProviders, getRegistrationStatus, getRepository, getRepositoryStats, getScheduleMirrors, getScheduleNotifications, getSnapshotDetails, getSsoSettings, getStatus, getSystemInfo, getUpdates, getUserDeletionImpact, getVolume, healthCheckVolume, listBackupSchedules, listFiles, listNotificationDestinations, listRcloneRemotes, listRepositories, listSnapshotFiles, listSnapshots, listVolumes, mountVolume, type Options, refreshSnapshots, removeOrgMember, reorderBackupSchedules, restoreSnapshot, runBackupNow, runForget, setRegistrationStatus, startDoctor, stopBackup, tagSnapshots, testConnection, testNotificationDestination, unlockRepository, unmountVolume, updateBackupSchedule, updateMemberRole, updateNotificationDestination, updateRepository, updateScheduleMirrors, updateScheduleNotifications, updateSsoProviderAutoLinking, updateVolume } from '../sdk.gen';
|
||||
import type { BrowseFilesystemData, BrowseFilesystemResponse, CancelDoctorData, CancelDoctorResponse, CreateBackupScheduleData, CreateBackupScheduleResponse, CreateNotificationDestinationData, CreateNotificationDestinationResponse, CreateRepositoryData, CreateRepositoryResponse, CreateVolumeData, CreateVolumeResponse, DeleteBackupScheduleData, DeleteBackupScheduleResponse, DeleteNotificationDestinationData, DeleteNotificationDestinationResponse, DeleteRepositoryData, DeleteRepositoryResponse, DeleteSnapshotData, DeleteSnapshotResponse, DeleteSnapshotsData, DeleteSnapshotsResponse, DeleteSsoInvitationData, DeleteSsoProviderData, DeleteUserAccountData, DeleteVolumeData, DeleteVolumeResponse, DevPanelExecData, DevPanelExecResponse, DownloadResticPasswordData, DownloadResticPasswordResponse, DumpSnapshotData, DumpSnapshotResponse, GetAdminUsersData, GetAdminUsersResponse, GetBackupProgressData, GetBackupProgressResponse, GetBackupScheduleData, GetBackupScheduleForVolumeData, GetBackupScheduleForVolumeResponse, GetBackupScheduleResponse, GetDevPanelData, GetDevPanelResponse, GetMirrorCompatibilityData, GetMirrorCompatibilityResponse, GetNotificationDestinationData, GetNotificationDestinationResponse, GetOrgMembersData, GetOrgMembersResponse, GetPublicSsoProvidersData, GetPublicSsoProvidersResponse, GetRegistrationStatusData, GetRegistrationStatusResponse, GetRepositoryData, GetRepositoryResponse, GetRepositoryStatsData, GetRepositoryStatsResponse, GetScheduleMirrorsData, GetScheduleMirrorsResponse, GetScheduleNotificationsData, GetScheduleNotificationsResponse, GetSnapshotDetailsData, GetSnapshotDetailsResponse, GetSsoSettingsData, GetSsoSettingsResponse, GetStatusData, GetStatusResponse, GetSystemInfoData, GetSystemInfoResponse, GetUpdatesData, GetUpdatesResponse, GetUserDeletionImpactData, GetUserDeletionImpactResponse, GetVolumeData, GetVolumeResponse, HealthCheckVolumeData, HealthCheckVolumeResponse, ListBackupSchedulesData, ListBackupSchedulesResponse, ListFilesData, ListFilesResponse, ListNotificationDestinationsData, ListNotificationDestinationsResponse, ListRcloneRemotesData, ListRcloneRemotesResponse, ListRepositoriesData, ListRepositoriesResponse, ListSnapshotFilesData, ListSnapshotFilesResponse, ListSnapshotsData, ListSnapshotsResponse, ListVolumesData, ListVolumesResponse, MountVolumeData, MountVolumeResponse, RefreshSnapshotsData, RefreshSnapshotsResponse, RemoveOrgMemberData, ReorderBackupSchedulesData, ReorderBackupSchedulesResponse, RestoreSnapshotData, RestoreSnapshotResponse, RunBackupNowData, RunBackupNowResponse, RunForgetData, RunForgetResponse, SetRegistrationStatusData, SetRegistrationStatusResponse, StartDoctorData, StartDoctorResponse, StopBackupData, StopBackupResponse, TagSnapshotsData, TagSnapshotsResponse, TestConnectionData, TestConnectionResponse, TestNotificationDestinationData, TestNotificationDestinationResponse, UnlockRepositoryData, UnlockRepositoryResponse, UnmountVolumeData, UnmountVolumeResponse, UpdateBackupScheduleData, UpdateBackupScheduleResponse, UpdateMemberRoleData, UpdateNotificationDestinationData, UpdateNotificationDestinationResponse, UpdateRepositoryData, UpdateRepositoryResponse, UpdateScheduleMirrorsData, UpdateScheduleMirrorsResponse, UpdateScheduleNotificationsData, UpdateScheduleNotificationsResponse, UpdateSsoProviderAutoLinkingData, UpdateVolumeData, UpdateVolumeResponse } from '../types.gen';
|
||||
import { browseFilesystem, cancelDoctor, createBackupSchedule, createNotificationDestination, createRepository, createVolume, deleteBackupSchedule, deleteNotificationDestination, deleteRepository, deleteSnapshot, deleteSnapshots, deleteSsoInvitation, deleteSsoProvider, deleteUserAccount, deleteVolume, downloadResticPassword, dumpSnapshot, getAdminUsers, getBackupProgress, getBackupSchedule, getBackupScheduleForVolume, getDevPanel, getMirrorCompatibility, getMirrorSyncStatus, getNotificationDestination, getOrgMembers, getPublicSsoProviders, getRegistrationStatus, getRepository, getRepositoryStats, getScheduleMirrors, getScheduleNotifications, getSnapshotDetails, getSsoSettings, getStatus, getSystemInfo, getUpdates, getUserDeletionImpact, getVolume, healthCheckVolume, listBackupSchedules, listFiles, listNotificationDestinations, listRcloneRemotes, listRepositories, listSnapshotFiles, listSnapshots, listVolumes, mountVolume, type Options, refreshRepositoryStats, refreshSnapshots, removeOrgMember, reorderBackupSchedules, restoreSnapshot, runBackupNow, runForget, setRegistrationStatus, startDoctor, stopBackup, syncMirror, tagSnapshots, testConnection, testNotificationDestination, unlockRepository, unmountVolume, updateBackupSchedule, updateMemberRole, updateNotificationDestination, updateRepository, updateScheduleMirrors, updateScheduleNotifications, updateSsoProviderAutoLinking, updateVolume } from '../sdk.gen';
|
||||
import type { BrowseFilesystemData, BrowseFilesystemResponse, CancelDoctorData, CancelDoctorResponse, CreateBackupScheduleData, CreateBackupScheduleResponse, CreateNotificationDestinationData, CreateNotificationDestinationResponse, CreateRepositoryData, CreateRepositoryResponse, CreateVolumeData, CreateVolumeResponse, DeleteBackupScheduleData, DeleteBackupScheduleResponse, DeleteNotificationDestinationData, DeleteNotificationDestinationResponse, DeleteRepositoryData, DeleteRepositoryResponse, DeleteSnapshotData, DeleteSnapshotResponse, DeleteSnapshotsData, DeleteSnapshotsResponse, DeleteSsoInvitationData, DeleteSsoProviderData, DeleteUserAccountData, DeleteVolumeData, DeleteVolumeResponse, DownloadResticPasswordData, DownloadResticPasswordResponse, DumpSnapshotData, DumpSnapshotResponse, GetAdminUsersData, GetAdminUsersResponse, GetBackupProgressData, GetBackupProgressResponse, GetBackupScheduleData, GetBackupScheduleForVolumeData, GetBackupScheduleForVolumeResponse, GetBackupScheduleResponse, GetDevPanelData, GetDevPanelResponse, GetMirrorCompatibilityData, GetMirrorCompatibilityResponse, GetMirrorSyncStatusData, GetMirrorSyncStatusResponse, GetNotificationDestinationData, GetNotificationDestinationResponse, GetOrgMembersData, GetOrgMembersResponse, GetPublicSsoProvidersData, GetPublicSsoProvidersResponse, GetRegistrationStatusData, GetRegistrationStatusResponse, GetRepositoryData, GetRepositoryResponse, GetRepositoryStatsData, GetRepositoryStatsResponse, GetScheduleMirrorsData, GetScheduleMirrorsResponse, GetScheduleNotificationsData, GetScheduleNotificationsResponse, GetSnapshotDetailsData, GetSnapshotDetailsResponse, GetSsoSettingsData, GetSsoSettingsResponse, GetStatusData, GetStatusResponse, GetSystemInfoData, GetSystemInfoResponse, GetUpdatesData, GetUpdatesResponse, GetUserDeletionImpactData, GetUserDeletionImpactResponse, GetVolumeData, GetVolumeResponse, HealthCheckVolumeData, HealthCheckVolumeResponse, ListBackupSchedulesData, ListBackupSchedulesResponse, ListFilesData, ListFilesResponse, ListNotificationDestinationsData, ListNotificationDestinationsResponse, ListRcloneRemotesData, ListRcloneRemotesResponse, ListRepositoriesData, ListRepositoriesResponse, ListSnapshotFilesData, ListSnapshotFilesResponse, ListSnapshotsData, ListSnapshotsResponse, ListVolumesData, ListVolumesResponse, MountVolumeData, MountVolumeResponse, RefreshRepositoryStatsData, RefreshRepositoryStatsResponse, RefreshSnapshotsData, RefreshSnapshotsResponse, RemoveOrgMemberData, ReorderBackupSchedulesData, ReorderBackupSchedulesResponse, RestoreSnapshotData, RestoreSnapshotResponse, RunBackupNowData, RunBackupNowResponse, RunForgetData, RunForgetResponse, SetRegistrationStatusData, SetRegistrationStatusResponse, StartDoctorData, StartDoctorResponse, StopBackupData, StopBackupResponse, SyncMirrorData, SyncMirrorResponse, TagSnapshotsData, TagSnapshotsResponse, TestConnectionData, TestConnectionResponse, TestNotificationDestinationData, TestNotificationDestinationResponse, UnlockRepositoryData, UnlockRepositoryResponse, UnmountVolumeData, UnmountVolumeResponse, UpdateBackupScheduleData, UpdateBackupScheduleResponse, UpdateMemberRoleData, UpdateNotificationDestinationData, UpdateNotificationDestinationResponse, UpdateRepositoryData, UpdateRepositoryResponse, UpdateScheduleMirrorsData, UpdateScheduleMirrorsResponse, UpdateScheduleNotificationsData, UpdateScheduleNotificationsResponse, UpdateSsoProviderAutoLinkingData, UpdateVolumeData, UpdateVolumeResponse } from '../types.gen';
|
||||
|
||||
export type QueryKey<TOptions extends Options> = [
|
||||
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
|
||||
|
|
@ -58,93 +58,6 @@ export const getStatusOptions = (options?: Options<GetStatusData>) => queryOptio
|
|||
queryKey: getStatusQueryKey(options)
|
||||
});
|
||||
|
||||
export const getPublicSsoProvidersQueryKey = (options?: Options<GetPublicSsoProvidersData>) => createQueryKey('getPublicSsoProviders', options);
|
||||
|
||||
/**
|
||||
* Get public SSO providers for the instance
|
||||
*/
|
||||
export const getPublicSsoProvidersOptions = (options?: Options<GetPublicSsoProvidersData>) => queryOptions<GetPublicSsoProvidersResponse, DefaultError, GetPublicSsoProvidersResponse, ReturnType<typeof getPublicSsoProvidersQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getPublicSsoProviders({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getPublicSsoProvidersQueryKey(options)
|
||||
});
|
||||
|
||||
export const getSsoSettingsQueryKey = (options?: Options<GetSsoSettingsData>) => createQueryKey('getSsoSettings', options);
|
||||
|
||||
/**
|
||||
* Get SSO providers and invitations for the active organization
|
||||
*/
|
||||
export const getSsoSettingsOptions = (options?: Options<GetSsoSettingsData>) => queryOptions<GetSsoSettingsResponse, DefaultError, GetSsoSettingsResponse, ReturnType<typeof getSsoSettingsQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getSsoSettings({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getSsoSettingsQueryKey(options)
|
||||
});
|
||||
|
||||
/**
|
||||
* Delete an SSO provider
|
||||
*/
|
||||
export const deleteSsoProviderMutation = (options?: Partial<Options<DeleteSsoProviderData>>): UseMutationOptions<unknown, DefaultError, Options<DeleteSsoProviderData>> => {
|
||||
const mutationOptions: UseMutationOptions<unknown, DefaultError, Options<DeleteSsoProviderData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await deleteSsoProvider({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* Update whether SSO sign-in can auto-link existing accounts by email
|
||||
*/
|
||||
export const updateSsoProviderAutoLinkingMutation = (options?: Partial<Options<UpdateSsoProviderAutoLinkingData>>): UseMutationOptions<unknown, DefaultError, Options<UpdateSsoProviderAutoLinkingData>> => {
|
||||
const mutationOptions: UseMutationOptions<unknown, DefaultError, Options<UpdateSsoProviderAutoLinkingData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await updateSsoProviderAutoLinking({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* Delete an SSO invitation
|
||||
*/
|
||||
export const deleteSsoInvitationMutation = (options?: Partial<Options<DeleteSsoInvitationData>>): UseMutationOptions<unknown, DefaultError, Options<DeleteSsoInvitationData>> => {
|
||||
const mutationOptions: UseMutationOptions<unknown, DefaultError, Options<DeleteSsoInvitationData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await deleteSsoInvitation({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
export const getAdminUsersQueryKey = (options?: Options<GetAdminUsersData>) => createQueryKey('getAdminUsers', options);
|
||||
|
||||
/**
|
||||
|
|
@ -250,6 +163,93 @@ export const removeOrgMemberMutation = (options?: Partial<Options<RemoveOrgMembe
|
|||
return mutationOptions;
|
||||
};
|
||||
|
||||
export const getPublicSsoProvidersQueryKey = (options?: Options<GetPublicSsoProvidersData>) => createQueryKey('getPublicSsoProviders', options);
|
||||
|
||||
/**
|
||||
* Get public SSO providers for the instance
|
||||
*/
|
||||
export const getPublicSsoProvidersOptions = (options?: Options<GetPublicSsoProvidersData>) => queryOptions<GetPublicSsoProvidersResponse, DefaultError, GetPublicSsoProvidersResponse, ReturnType<typeof getPublicSsoProvidersQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getPublicSsoProviders({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getPublicSsoProvidersQueryKey(options)
|
||||
});
|
||||
|
||||
export const getSsoSettingsQueryKey = (options?: Options<GetSsoSettingsData>) => createQueryKey('getSsoSettings', options);
|
||||
|
||||
/**
|
||||
* Get SSO providers and invitations for the active organization
|
||||
*/
|
||||
export const getSsoSettingsOptions = (options?: Options<GetSsoSettingsData>) => queryOptions<GetSsoSettingsResponse, DefaultError, GetSsoSettingsResponse, ReturnType<typeof getSsoSettingsQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getSsoSettings({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getSsoSettingsQueryKey(options)
|
||||
});
|
||||
|
||||
/**
|
||||
* Delete an SSO provider
|
||||
*/
|
||||
export const deleteSsoProviderMutation = (options?: Partial<Options<DeleteSsoProviderData>>): UseMutationOptions<unknown, DefaultError, Options<DeleteSsoProviderData>> => {
|
||||
const mutationOptions: UseMutationOptions<unknown, DefaultError, Options<DeleteSsoProviderData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await deleteSsoProvider({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* Update whether SSO sign-in can auto-link existing accounts by email
|
||||
*/
|
||||
export const updateSsoProviderAutoLinkingMutation = (options?: Partial<Options<UpdateSsoProviderAutoLinkingData>>): UseMutationOptions<unknown, DefaultError, Options<UpdateSsoProviderAutoLinkingData>> => {
|
||||
const mutationOptions: UseMutationOptions<unknown, DefaultError, Options<UpdateSsoProviderAutoLinkingData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await updateSsoProviderAutoLinking({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* Delete an SSO invitation
|
||||
*/
|
||||
export const deleteSsoInvitationMutation = (options?: Partial<Options<DeleteSsoInvitationData>>): UseMutationOptions<unknown, DefaultError, Options<DeleteSsoInvitationData>> => {
|
||||
const mutationOptions: UseMutationOptions<unknown, DefaultError, Options<DeleteSsoInvitationData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await deleteSsoInvitation({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
export const listVolumesQueryKey = (options?: Options<ListVolumesData>) => createQueryKey('listVolumes', options);
|
||||
|
||||
/**
|
||||
|
|
@ -457,7 +457,7 @@ export const listFilesInfiniteQueryKey = (options: Options<ListFilesData>): Quer
|
|||
/**
|
||||
* List files in a volume directory
|
||||
*/
|
||||
export const listFilesInfiniteOptions = (options: Options<ListFilesData>) => infiniteQueryOptions<ListFilesResponse, DefaultError, InfiniteData<ListFilesResponse>, QueryKey<Options<ListFilesData>>, string | Pick<QueryKey<Options<ListFilesData>>[0], 'body' | 'headers' | 'path' | 'query'>>(
|
||||
export const listFilesInfiniteOptions = (options: Options<ListFilesData>) => infiniteQueryOptions<ListFilesResponse, DefaultError, InfiniteData<ListFilesResponse>, QueryKey<Options<ListFilesData>>, number | Pick<QueryKey<Options<ListFilesData>>[0], 'body' | 'headers' | 'path' | 'query'>>(
|
||||
// @ts-ignore
|
||||
{
|
||||
queryFn: async ({ pageParam, queryKey, signal }) => {
|
||||
|
|
@ -620,6 +620,23 @@ export const getRepositoryStatsOptions = (options: Options<GetRepositoryStatsDat
|
|||
queryKey: getRepositoryStatsQueryKey(options)
|
||||
});
|
||||
|
||||
/**
|
||||
* Refresh repository storage and compression statistics
|
||||
*/
|
||||
export const refreshRepositoryStatsMutation = (options?: Partial<Options<RefreshRepositoryStatsData>>): UseMutationOptions<RefreshRepositoryStatsResponse, DefaultError, Options<RefreshRepositoryStatsData>> => {
|
||||
const mutationOptions: UseMutationOptions<RefreshRepositoryStatsResponse, DefaultError, Options<RefreshRepositoryStatsData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await refreshRepositoryStats({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* Delete multiple snapshots from a repository
|
||||
*/
|
||||
|
|
@ -730,7 +747,7 @@ export const listSnapshotFilesInfiniteQueryKey = (options: Options<ListSnapshotF
|
|||
/**
|
||||
* List files and directories in a snapshot
|
||||
*/
|
||||
export const listSnapshotFilesInfiniteOptions = (options: Options<ListSnapshotFilesData>) => infiniteQueryOptions<ListSnapshotFilesResponse, DefaultError, InfiniteData<ListSnapshotFilesResponse>, QueryKey<Options<ListSnapshotFilesData>>, string | Pick<QueryKey<Options<ListSnapshotFilesData>>[0], 'body' | 'headers' | 'path' | 'query'>>(
|
||||
export const listSnapshotFilesInfiniteOptions = (options: Options<ListSnapshotFilesData>) => infiniteQueryOptions<ListSnapshotFilesResponse, DefaultError, InfiniteData<ListSnapshotFilesResponse>, QueryKey<Options<ListSnapshotFilesData>>, number | Pick<QueryKey<Options<ListSnapshotFilesData>>[0], 'body' | 'headers' | 'path' | 'query'>>(
|
||||
// @ts-ignore
|
||||
{
|
||||
queryFn: async ({ pageParam, queryKey, signal }) => {
|
||||
|
|
@ -855,23 +872,6 @@ export const tagSnapshotsMutation = (options?: Partial<Options<TagSnapshotsData>
|
|||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* Execute a restic command against a repository (dev panel only)
|
||||
*/
|
||||
export const devPanelExecMutation = (options?: Partial<Options<DevPanelExecData>>): UseMutationOptions<DevPanelExecResponse, DefaultError, Options<DevPanelExecData>> => {
|
||||
const mutationOptions: UseMutationOptions<DevPanelExecResponse, DefaultError, Options<DevPanelExecData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await devPanelExec({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
export const listBackupSchedulesQueryKey = (options?: Options<ListBackupSchedulesData>) => createQueryKey('listBackupSchedules', options);
|
||||
|
||||
/**
|
||||
|
|
@ -1098,6 +1098,41 @@ export const updateScheduleMirrorsMutation = (options?: Partial<Options<UpdateSc
|
|||
return mutationOptions;
|
||||
};
|
||||
|
||||
export const getMirrorSyncStatusQueryKey = (options: Options<GetMirrorSyncStatusData>) => createQueryKey('getMirrorSyncStatus', options);
|
||||
|
||||
/**
|
||||
* Get sync status for a specific mirror, including missing snapshots
|
||||
*/
|
||||
export const getMirrorSyncStatusOptions = (options: Options<GetMirrorSyncStatusData>) => queryOptions<GetMirrorSyncStatusResponse, DefaultError, GetMirrorSyncStatusResponse, ReturnType<typeof getMirrorSyncStatusQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getMirrorSyncStatus({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getMirrorSyncStatusQueryKey(options)
|
||||
});
|
||||
|
||||
/**
|
||||
* Sync selected snapshots to a specific mirror repository
|
||||
*/
|
||||
export const syncMirrorMutation = (options?: Partial<Options<SyncMirrorData>>): UseMutationOptions<SyncMirrorResponse, DefaultError, Options<SyncMirrorData>> => {
|
||||
const mutationOptions: UseMutationOptions<SyncMirrorResponse, DefaultError, Options<SyncMirrorData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await syncMirror({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
export const getMirrorCompatibilityQueryKey = (options: Options<GetMirrorCompatibilityData>) => createQueryKey('getMirrorCompatibility', options);
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -32,20 +32,24 @@ export const createClient = (config: Config = {}): Client => {
|
|||
|
||||
const interceptors = createInterceptors<Request, Response, unknown, ResolvedRequestOptions>();
|
||||
|
||||
const beforeRequest = async (options: RequestOptions) => {
|
||||
const beforeRequest = async <
|
||||
TData = unknown,
|
||||
TResponseStyle extends 'data' | 'fields' = 'fields',
|
||||
ThrowOnError extends boolean = boolean,
|
||||
Url extends string = string,
|
||||
>(
|
||||
options: RequestOptions<TData, TResponseStyle, ThrowOnError, Url>,
|
||||
) => {
|
||||
const opts = {
|
||||
..._config,
|
||||
...options,
|
||||
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
|
||||
headers: mergeHeaders(_config.headers, options.headers),
|
||||
serializedBody: undefined,
|
||||
serializedBody: undefined as string | undefined,
|
||||
};
|
||||
|
||||
if (opts.security) {
|
||||
await setAuthParams({
|
||||
...opts,
|
||||
security: opts.security,
|
||||
});
|
||||
await setAuthParams(opts);
|
||||
}
|
||||
|
||||
if (opts.requestValidator) {
|
||||
|
|
@ -53,7 +57,7 @@ export const createClient = (config: Config = {}): Client => {
|
|||
}
|
||||
|
||||
if (opts.body !== undefined && opts.bodySerializer) {
|
||||
opts.serializedBody = opts.bodySerializer(opts.body);
|
||||
opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined;
|
||||
}
|
||||
|
||||
// remove Content-Type header if body is empty to avoid sending invalid requests
|
||||
|
|
@ -61,178 +65,162 @@ export const createClient = (config: Config = {}): Client => {
|
|||
opts.headers.delete('Content-Type');
|
||||
}
|
||||
|
||||
const url = buildUrl(opts);
|
||||
const resolvedOpts = opts as typeof opts &
|
||||
ResolvedRequestOptions<TResponseStyle, ThrowOnError, Url>;
|
||||
const url = buildUrl(resolvedOpts);
|
||||
|
||||
return { opts, url };
|
||||
return { opts: resolvedOpts, url };
|
||||
};
|
||||
|
||||
const request: Client['request'] = async (options) => {
|
||||
// @ts-expect-error
|
||||
const { opts, url } = await beforeRequest(options);
|
||||
const requestInit: ReqInit = {
|
||||
redirect: 'follow',
|
||||
...opts,
|
||||
body: getValidRequestBody(opts),
|
||||
};
|
||||
const throwOnError = options.throwOnError ?? _config.throwOnError;
|
||||
const responseStyle = options.responseStyle ?? _config.responseStyle;
|
||||
|
||||
let request = new Request(url, requestInit);
|
||||
|
||||
for (const fn of interceptors.request.fns) {
|
||||
if (fn) {
|
||||
request = await fn(request, opts);
|
||||
}
|
||||
}
|
||||
|
||||
// fetch must be assigned here, otherwise it would throw the error:
|
||||
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
|
||||
const _fetch = opts.fetch!;
|
||||
let response: Response;
|
||||
let request: Request | undefined;
|
||||
let response: Response | undefined;
|
||||
|
||||
try {
|
||||
response = await _fetch(request);
|
||||
} catch (error) {
|
||||
// Handle fetch exceptions (AbortError, network errors, etc.)
|
||||
let finalError = error;
|
||||
const { opts, url } = await beforeRequest(options);
|
||||
const requestInit: ReqInit = {
|
||||
redirect: 'follow',
|
||||
...opts,
|
||||
body: getValidRequestBody(opts),
|
||||
};
|
||||
|
||||
for (const fn of interceptors.error.fns) {
|
||||
request = new Request(url, requestInit);
|
||||
|
||||
for (const fn of interceptors.request.fns) {
|
||||
if (fn) {
|
||||
finalError = (await fn(error, undefined as any, request, opts)) as unknown;
|
||||
request = await fn(request, opts);
|
||||
}
|
||||
}
|
||||
|
||||
finalError = finalError || ({} as unknown);
|
||||
// fetch must be assigned here, otherwise it would throw the error:
|
||||
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
|
||||
const _fetch = opts.fetch!;
|
||||
|
||||
if (opts.throwOnError) {
|
||||
throw finalError;
|
||||
response = await _fetch(request);
|
||||
|
||||
for (const fn of interceptors.response.fns) {
|
||||
if (fn) {
|
||||
response = await fn(response, request, opts);
|
||||
}
|
||||
}
|
||||
|
||||
// Return error response
|
||||
return opts.responseStyle === 'data'
|
||||
? undefined
|
||||
: {
|
||||
error: finalError,
|
||||
request,
|
||||
response: undefined as any,
|
||||
};
|
||||
}
|
||||
const result = {
|
||||
request,
|
||||
response,
|
||||
};
|
||||
|
||||
for (const fn of interceptors.response.fns) {
|
||||
if (fn) {
|
||||
response = await fn(response, request, opts);
|
||||
}
|
||||
}
|
||||
if (response.ok) {
|
||||
const parseAs =
|
||||
(opts.parseAs === 'auto'
|
||||
? getParseAs(response.headers.get('Content-Type'))
|
||||
: opts.parseAs) ?? 'json';
|
||||
|
||||
const result = {
|
||||
request,
|
||||
response,
|
||||
};
|
||||
if (response.status === 204 || response.headers.get('Content-Length') === '0') {
|
||||
let emptyData: any;
|
||||
switch (parseAs) {
|
||||
case 'arrayBuffer':
|
||||
case 'blob':
|
||||
case 'text':
|
||||
emptyData = await response[parseAs]();
|
||||
break;
|
||||
case 'formData':
|
||||
emptyData = new FormData();
|
||||
break;
|
||||
case 'stream':
|
||||
emptyData = response.body;
|
||||
break;
|
||||
case 'json':
|
||||
default:
|
||||
emptyData = {};
|
||||
break;
|
||||
}
|
||||
return opts.responseStyle === 'data'
|
||||
? emptyData
|
||||
: {
|
||||
data: emptyData,
|
||||
...result,
|
||||
};
|
||||
}
|
||||
|
||||
if (response.ok) {
|
||||
const parseAs =
|
||||
(opts.parseAs === 'auto'
|
||||
? getParseAs(response.headers.get('Content-Type'))
|
||||
: opts.parseAs) ?? 'json';
|
||||
|
||||
if (response.status === 204 || response.headers.get('Content-Length') === '0') {
|
||||
let emptyData: any;
|
||||
let data: any;
|
||||
switch (parseAs) {
|
||||
case 'arrayBuffer':
|
||||
case 'blob':
|
||||
case 'text':
|
||||
emptyData = await response[parseAs]();
|
||||
break;
|
||||
case 'formData':
|
||||
emptyData = new FormData();
|
||||
case 'text':
|
||||
data = await response[parseAs]();
|
||||
break;
|
||||
case 'json': {
|
||||
// Some servers return 200 with no Content-Length and empty body.
|
||||
// response.json() would throw; read as text and parse if non-empty.
|
||||
const text = await response.text();
|
||||
data = text ? JSON.parse(text) : {};
|
||||
break;
|
||||
}
|
||||
case 'stream':
|
||||
emptyData = response.body;
|
||||
break;
|
||||
case 'json':
|
||||
default:
|
||||
emptyData = {};
|
||||
break;
|
||||
return opts.responseStyle === 'data'
|
||||
? response.body
|
||||
: {
|
||||
data: response.body,
|
||||
...result,
|
||||
};
|
||||
}
|
||||
|
||||
if (parseAs === 'json') {
|
||||
if (opts.responseValidator) {
|
||||
await opts.responseValidator(data);
|
||||
}
|
||||
|
||||
if (opts.responseTransformer) {
|
||||
data = await opts.responseTransformer(data);
|
||||
}
|
||||
}
|
||||
|
||||
return opts.responseStyle === 'data'
|
||||
? emptyData
|
||||
? data
|
||||
: {
|
||||
data: emptyData,
|
||||
data,
|
||||
...result,
|
||||
};
|
||||
}
|
||||
|
||||
let data: any;
|
||||
switch (parseAs) {
|
||||
case 'arrayBuffer':
|
||||
case 'blob':
|
||||
case 'formData':
|
||||
case 'text':
|
||||
data = await response[parseAs]();
|
||||
break;
|
||||
case 'json': {
|
||||
// Some servers return 200 with no Content-Length and empty body.
|
||||
// response.json() would throw; read as text and parse if non-empty.
|
||||
const text = await response.text();
|
||||
data = text ? JSON.parse(text) : {};
|
||||
break;
|
||||
}
|
||||
case 'stream':
|
||||
return opts.responseStyle === 'data'
|
||||
? response.body
|
||||
: {
|
||||
data: response.body,
|
||||
...result,
|
||||
};
|
||||
const textError = await response.text();
|
||||
let jsonError: unknown;
|
||||
|
||||
try {
|
||||
jsonError = JSON.parse(textError);
|
||||
} catch {
|
||||
// noop
|
||||
}
|
||||
|
||||
if (parseAs === 'json') {
|
||||
if (opts.responseValidator) {
|
||||
await opts.responseValidator(data);
|
||||
}
|
||||
throw jsonError ?? textError;
|
||||
} catch (error) {
|
||||
let finalError = error;
|
||||
|
||||
if (opts.responseTransformer) {
|
||||
data = await opts.responseTransformer(data);
|
||||
for (const fn of interceptors.error.fns) {
|
||||
if (fn) {
|
||||
finalError = await fn(finalError, response, request, options as ResolvedRequestOptions);
|
||||
}
|
||||
}
|
||||
|
||||
return opts.responseStyle === 'data'
|
||||
? data
|
||||
finalError = finalError || {};
|
||||
|
||||
if (throwOnError) {
|
||||
throw finalError;
|
||||
}
|
||||
|
||||
// TODO: we probably want to return error and improve types
|
||||
return responseStyle === 'data'
|
||||
? undefined
|
||||
: {
|
||||
data,
|
||||
...result,
|
||||
error: finalError,
|
||||
request,
|
||||
response,
|
||||
};
|
||||
}
|
||||
|
||||
const textError = await response.text();
|
||||
let jsonError: unknown;
|
||||
|
||||
try {
|
||||
jsonError = JSON.parse(textError);
|
||||
} catch {
|
||||
// noop
|
||||
}
|
||||
|
||||
const error = jsonError ?? textError;
|
||||
let finalError = error;
|
||||
|
||||
for (const fn of interceptors.error.fns) {
|
||||
if (fn) {
|
||||
finalError = (await fn(error, response, request, opts)) as string;
|
||||
}
|
||||
}
|
||||
|
||||
finalError = finalError || ({} as string);
|
||||
|
||||
if (opts.throwOnError) {
|
||||
throw finalError;
|
||||
}
|
||||
|
||||
// TODO: we probably want to return error and improve types
|
||||
return opts.responseStyle === 'data'
|
||||
? undefined
|
||||
: {
|
||||
error: finalError,
|
||||
...result,
|
||||
};
|
||||
};
|
||||
|
||||
const makeMethodFn = (method: Uppercase<HttpMethod>) => (options: RequestOptions) =>
|
||||
|
|
@ -243,7 +231,6 @@ export const createClient = (config: Config = {}): Client => {
|
|||
return createSseClient({
|
||||
...opts,
|
||||
body: opts.body as BodyInit | null | undefined,
|
||||
headers: opts.headers as unknown as Record<string, string>,
|
||||
method,
|
||||
onRequest: async (url, init) => {
|
||||
let request = new Request(url, init);
|
||||
|
|
@ -259,8 +246,10 @@ export const createClient = (config: Config = {}): Client => {
|
|||
});
|
||||
};
|
||||
|
||||
const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options });
|
||||
|
||||
return {
|
||||
buildUrl,
|
||||
buildUrl: _buildUrl,
|
||||
connect: makeMethodFn('CONNECT'),
|
||||
delete: makeMethodFn('DELETE'),
|
||||
get: makeMethodFn('GET'),
|
||||
|
|
|
|||
|
|
@ -94,6 +94,7 @@ export interface ResolvedRequestOptions<
|
|||
ThrowOnError extends boolean = boolean,
|
||||
Url extends string = string,
|
||||
> extends RequestOptions<unknown, TResponseStyle, ThrowOnError, Url> {
|
||||
headers: Headers;
|
||||
serializedBody?: string;
|
||||
}
|
||||
|
||||
|
|
@ -127,8 +128,10 @@ export type RequestResult<
|
|||
error: TError extends Record<string, unknown> ? TError[keyof TError] : TError;
|
||||
}
|
||||
) & {
|
||||
request: Request;
|
||||
response: Response;
|
||||
/** request may be undefined, because error may be from building the request object itself */
|
||||
request?: Request;
|
||||
/** response may be undefined, because error may be from building the request object itself or from a network error */
|
||||
response?: Response;
|
||||
}
|
||||
>;
|
||||
|
||||
|
|
@ -153,7 +156,7 @@ type SseFn = <
|
|||
ThrowOnError extends boolean = false,
|
||||
TResponseStyle extends ResponseStyle = 'fields',
|
||||
>(
|
||||
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'>,
|
||||
options: Omit<RequestOptions<never, TResponseStyle, ThrowOnError>, 'method'>,
|
||||
) => Promise<ServerSentEventsResult<TData, TError>>;
|
||||
|
||||
type RequestFn = <
|
||||
|
|
|
|||
|
|
@ -119,14 +119,12 @@ const checkForExistence = (
|
|||
return false;
|
||||
};
|
||||
|
||||
export const setAuthParams = async ({
|
||||
security,
|
||||
...options
|
||||
}: Pick<Required<RequestOptions>, 'security'> &
|
||||
Pick<RequestOptions, 'auth' | 'query'> & {
|
||||
export async function setAuthParams(
|
||||
options: Pick<RequestOptions, 'auth' | 'query' | 'security'> & {
|
||||
headers: Headers;
|
||||
}) => {
|
||||
for (const auth of security) {
|
||||
},
|
||||
): Promise<void> {
|
||||
for (const auth of options.security ?? []) {
|
||||
if (checkForExistence(options, auth.name)) {
|
||||
continue;
|
||||
}
|
||||
|
|
@ -155,7 +153,7 @@ export const setAuthParams = async ({
|
|||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const buildUrl: Client['buildUrl'] = (options) =>
|
||||
getUrl({
|
||||
|
|
@ -205,7 +203,7 @@ export const mergeHeaders = (
|
|||
mergedHeaders.append(key, v as string);
|
||||
}
|
||||
} else if (value !== undefined) {
|
||||
// assume object headers are meant to be JSON stringified, i.e. their
|
||||
// assume object headers are meant to be JSON stringified, i.e., their
|
||||
// content value in OpenAPI specification is 'application/json'
|
||||
mergedHeaders.set(
|
||||
key,
|
||||
|
|
@ -219,8 +217,10 @@ export const mergeHeaders = (
|
|||
|
||||
type ErrInterceptor<Err, Res, Req, Options> = (
|
||||
error: Err,
|
||||
response: Res,
|
||||
request: Req,
|
||||
/** response may be undefined due to a network error where no response object is produced */
|
||||
response: Res | undefined,
|
||||
/** request may be undefined, because error may be from building the request object itself */
|
||||
request: Req | undefined,
|
||||
options: Options,
|
||||
) => Err | Promise<Err>;
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerialize
|
|||
|
||||
export type QuerySerializer = (query: Record<string, unknown>) => string;
|
||||
|
||||
export type BodySerializer = (body: any) => any;
|
||||
export type BodySerializer = (body: unknown) => unknown;
|
||||
|
||||
type QuerySerializerOptionsObject = {
|
||||
allowReserved?: boolean;
|
||||
|
|
@ -40,12 +40,10 @@ const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value:
|
|||
};
|
||||
|
||||
export const formDataBodySerializer = {
|
||||
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
|
||||
body: T,
|
||||
): FormData => {
|
||||
bodySerializer: (body: unknown): FormData => {
|
||||
const data = new FormData();
|
||||
|
||||
Object.entries(body).forEach(([key, value]) => {
|
||||
Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {
|
||||
if (value === undefined || value === null) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -61,15 +59,15 @@ export const formDataBodySerializer = {
|
|||
};
|
||||
|
||||
export const jsonBodySerializer = {
|
||||
bodySerializer: <T>(body: T): string =>
|
||||
bodySerializer: (body: unknown): string =>
|
||||
JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)),
|
||||
};
|
||||
|
||||
export const urlSearchParamsBodySerializer = {
|
||||
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(body: T): string => {
|
||||
bodySerializer: (body: unknown): string => {
|
||||
const data = new URLSearchParams();
|
||||
|
||||
Object.entries(body).forEach(([key, value]) => {
|
||||
Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {
|
||||
if (value === undefined || value === null) {
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -97,7 +97,7 @@ interface Params {
|
|||
|
||||
const stripEmptySlots = (params: Params) => {
|
||||
for (const [slot, value] of Object.entries(params)) {
|
||||
if (value && typeof value === 'object' && !Object.keys(value).length) {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) {
|
||||
delete params[slot as Slot];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -80,7 +80,7 @@ export type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unkn
|
|||
>;
|
||||
};
|
||||
|
||||
export const createSseClient = <TData = unknown>({
|
||||
export function createSseClient<TData = unknown>({
|
||||
onRequest,
|
||||
onSseError,
|
||||
onSseEvent,
|
||||
|
|
@ -92,7 +92,7 @@ export const createSseClient = <TData = unknown>({
|
|||
sseSleepFn,
|
||||
url,
|
||||
...options
|
||||
}: ServerSentEventsOptions): ServerSentEventsResult<TData> => {
|
||||
}: ServerSentEventsOptions): ServerSentEventsResult<TData> {
|
||||
let lastEventId: string | undefined;
|
||||
|
||||
const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));
|
||||
|
|
@ -156,8 +156,7 @@ export const createSseClient = <TData = unknown>({
|
|||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += value;
|
||||
// Normalize line endings: CRLF -> LF, then CR -> LF
|
||||
buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
||||
buffer = buffer.replace(/\r\n?/g, '\n'); // normalize line endings
|
||||
|
||||
const chunks = buffer.split('\n\n');
|
||||
buffer = chunks.pop() ?? '';
|
||||
|
|
@ -241,4 +240,4 @@ export const createSseClient = <TData = unknown>({
|
|||
const stream = createStream();
|
||||
|
||||
return { stream };
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -81,7 +81,7 @@ export interface Config {
|
|||
requestValidator?: (data: unknown) => Promise<unknown>;
|
||||
/**
|
||||
* A function transforming response data before it's returned. This is useful
|
||||
* for post-processing data, e.g. converting ISO strings into Date objects.
|
||||
* for post-processing data, e.g., converting ISO strings into Date objects.
|
||||
*/
|
||||
responseTransformer?: (data: unknown) => Promise<unknown>;
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -127,7 +127,7 @@ export function getValidRequestBody(options: {
|
|||
return hasSerializedBody ? options.serializedBody : null;
|
||||
}
|
||||
|
||||
// not all clients implement a serializedBody property (i.e. client-axios)
|
||||
// not all clients implement a serializedBody property (i.e., client-axios)
|
||||
return options.body !== '' ? options.body : null;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ export {
|
|||
getBackupScheduleForVolume,
|
||||
getDevPanel,
|
||||
getMirrorCompatibility,
|
||||
getMirrorSyncStatus,
|
||||
getNotificationDestination,
|
||||
getOrgMembers,
|
||||
getPublicSsoProviders,
|
||||
|
|
@ -52,6 +53,7 @@ export {
|
|||
listVolumes,
|
||||
mountVolume,
|
||||
type Options,
|
||||
refreshRepositoryStats,
|
||||
refreshSnapshots,
|
||||
removeOrgMember,
|
||||
reorderBackupSchedules,
|
||||
|
|
@ -61,6 +63,7 @@ export {
|
|||
setRegistrationStatus,
|
||||
startDoctor,
|
||||
stopBackup,
|
||||
syncMirror,
|
||||
tagSnapshots,
|
||||
testConnection,
|
||||
testNotificationDestination,
|
||||
|
|
@ -152,6 +155,9 @@ export type {
|
|||
GetMirrorCompatibilityData,
|
||||
GetMirrorCompatibilityResponse,
|
||||
GetMirrorCompatibilityResponses,
|
||||
GetMirrorSyncStatusData,
|
||||
GetMirrorSyncStatusResponse,
|
||||
GetMirrorSyncStatusResponses,
|
||||
GetNotificationDestinationData,
|
||||
GetNotificationDestinationErrors,
|
||||
GetNotificationDestinationResponse,
|
||||
|
|
@ -230,6 +236,9 @@ export type {
|
|||
MountVolumeData,
|
||||
MountVolumeResponse,
|
||||
MountVolumeResponses,
|
||||
RefreshRepositoryStatsData,
|
||||
RefreshRepositoryStatsResponse,
|
||||
RefreshRepositoryStatsResponses,
|
||||
RefreshSnapshotsData,
|
||||
RefreshSnapshotsResponse,
|
||||
RefreshSnapshotsResponses,
|
||||
|
|
@ -259,6 +268,10 @@ export type {
|
|||
StopBackupErrors,
|
||||
StopBackupResponse,
|
||||
StopBackupResponses,
|
||||
SyncMirrorData,
|
||||
SyncMirrorErrors,
|
||||
SyncMirrorResponse,
|
||||
SyncMirrorResponses,
|
||||
TagSnapshotsData,
|
||||
TagSnapshotsResponse,
|
||||
TagSnapshotsResponses,
|
||||
|
|
|
|||
|
|
@ -3,9 +3,9 @@
|
|||
|
||||
import type { Client, Options as Options2, TDataShape } from './client';
|
||||
import { client } from './client.gen';
|
||||
import type { BrowseFilesystemData, BrowseFilesystemResponses, CancelDoctorData, CancelDoctorErrors, CancelDoctorResponses, CreateBackupScheduleData, CreateBackupScheduleResponses, CreateNotificationDestinationData, CreateNotificationDestinationResponses, CreateRepositoryData, CreateRepositoryResponses, CreateVolumeData, CreateVolumeResponses, DeleteBackupScheduleData, DeleteBackupScheduleResponses, DeleteNotificationDestinationData, DeleteNotificationDestinationErrors, DeleteNotificationDestinationResponses, DeleteRepositoryData, DeleteRepositoryResponses, DeleteSnapshotData, DeleteSnapshotResponses, DeleteSnapshotsData, DeleteSnapshotsResponses, DeleteSsoInvitationData, DeleteSsoInvitationErrors, DeleteSsoInvitationResponses, DeleteSsoProviderData, DeleteSsoProviderErrors, DeleteSsoProviderResponses, DeleteUserAccountData, DeleteUserAccountErrors, DeleteUserAccountResponses, DeleteVolumeData, DeleteVolumeResponses, DevPanelExecData, DevPanelExecErrors, DevPanelExecResponses, DownloadResticPasswordData, DownloadResticPasswordResponses, DumpSnapshotData, DumpSnapshotResponses, GetAdminUsersData, GetAdminUsersResponses, GetBackupProgressData, GetBackupProgressResponses, GetBackupScheduleData, GetBackupScheduleForVolumeData, GetBackupScheduleForVolumeResponses, GetBackupScheduleResponses, GetDevPanelData, GetDevPanelResponses, GetMirrorCompatibilityData, GetMirrorCompatibilityResponses, GetNotificationDestinationData, GetNotificationDestinationErrors, GetNotificationDestinationResponses, GetOrgMembersData, GetOrgMembersResponses, GetPublicSsoProvidersData, GetPublicSsoProvidersResponses, GetRegistrationStatusData, GetRegistrationStatusResponses, GetRepositoryData, GetRepositoryResponses, GetRepositoryStatsData, GetRepositoryStatsResponses, GetScheduleMirrorsData, GetScheduleMirrorsResponses, GetScheduleNotificationsData, GetScheduleNotificationsResponses, GetSnapshotDetailsData, GetSnapshotDetailsResponses, GetSsoSettingsData, GetSsoSettingsResponses, GetStatusData, GetStatusResponses, GetSystemInfoData, GetSystemInfoResponses, GetUpdatesData, GetUpdatesResponses, GetUserDeletionImpactData, GetUserDeletionImpactResponses, GetVolumeData, GetVolumeErrors, GetVolumeResponses, HealthCheckVolumeData, HealthCheckVolumeErrors, HealthCheckVolumeResponses, ListBackupSchedulesData, ListBackupSchedulesResponses, ListFilesData, ListFilesResponses, ListNotificationDestinationsData, ListNotificationDestinationsResponses, ListRcloneRemotesData, ListRcloneRemotesResponses, ListRepositoriesData, ListRepositoriesResponses, ListSnapshotFilesData, ListSnapshotFilesResponses, ListSnapshotsData, ListSnapshotsResponses, ListVolumesData, ListVolumesResponses, MountVolumeData, MountVolumeResponses, RefreshSnapshotsData, RefreshSnapshotsResponses, RemoveOrgMemberData, RemoveOrgMemberErrors, RemoveOrgMemberResponses, ReorderBackupSchedulesData, ReorderBackupSchedulesResponses, RestoreSnapshotData, RestoreSnapshotResponses, RunBackupNowData, RunBackupNowResponses, RunForgetData, RunForgetResponses, SetRegistrationStatusData, SetRegistrationStatusResponses, StartDoctorData, StartDoctorErrors, StartDoctorResponses, StopBackupData, StopBackupErrors, StopBackupResponses, TagSnapshotsData, TagSnapshotsResponses, TestConnectionData, TestConnectionResponses, TestNotificationDestinationData, TestNotificationDestinationErrors, TestNotificationDestinationResponses, UnlockRepositoryData, UnlockRepositoryResponses, UnmountVolumeData, UnmountVolumeResponses, UpdateBackupScheduleData, UpdateBackupScheduleResponses, UpdateMemberRoleData, UpdateMemberRoleErrors, UpdateMemberRoleResponses, UpdateNotificationDestinationData, UpdateNotificationDestinationErrors, UpdateNotificationDestinationResponses, UpdateRepositoryData, UpdateRepositoryErrors, UpdateRepositoryResponses, UpdateScheduleMirrorsData, UpdateScheduleMirrorsResponses, UpdateScheduleNotificationsData, UpdateScheduleNotificationsResponses, UpdateSsoProviderAutoLinkingData, UpdateSsoProviderAutoLinkingErrors, UpdateSsoProviderAutoLinkingResponses, UpdateVolumeData, UpdateVolumeErrors, UpdateVolumeResponses } from './types.gen';
|
||||
import type { BrowseFilesystemData, BrowseFilesystemResponses, CancelDoctorData, CancelDoctorErrors, CancelDoctorResponses, CreateBackupScheduleData, CreateBackupScheduleResponses, CreateNotificationDestinationData, CreateNotificationDestinationResponses, CreateRepositoryData, CreateRepositoryResponses, CreateVolumeData, CreateVolumeResponses, DeleteBackupScheduleData, DeleteBackupScheduleResponses, DeleteNotificationDestinationData, DeleteNotificationDestinationErrors, DeleteNotificationDestinationResponses, DeleteRepositoryData, DeleteRepositoryResponses, DeleteSnapshotData, DeleteSnapshotResponses, DeleteSnapshotsData, DeleteSnapshotsResponses, DeleteSsoInvitationData, DeleteSsoInvitationErrors, DeleteSsoInvitationResponses, DeleteSsoProviderData, DeleteSsoProviderErrors, DeleteSsoProviderResponses, DeleteUserAccountData, DeleteUserAccountErrors, DeleteUserAccountResponses, DeleteVolumeData, DeleteVolumeResponses, DevPanelExecData, DevPanelExecErrors, DevPanelExecResponse, DevPanelExecResponses, DownloadResticPasswordData, DownloadResticPasswordResponses, DumpSnapshotData, DumpSnapshotResponses, GetAdminUsersData, GetAdminUsersResponses, GetBackupProgressData, GetBackupProgressResponses, GetBackupScheduleData, GetBackupScheduleForVolumeData, GetBackupScheduleForVolumeResponses, GetBackupScheduleResponses, GetDevPanelData, GetDevPanelResponses, GetMirrorCompatibilityData, GetMirrorCompatibilityResponses, GetMirrorSyncStatusData, GetMirrorSyncStatusResponses, GetNotificationDestinationData, GetNotificationDestinationErrors, GetNotificationDestinationResponses, GetOrgMembersData, GetOrgMembersResponses, GetPublicSsoProvidersData, GetPublicSsoProvidersResponses, GetRegistrationStatusData, GetRegistrationStatusResponses, GetRepositoryData, GetRepositoryResponses, GetRepositoryStatsData, GetRepositoryStatsResponses, GetScheduleMirrorsData, GetScheduleMirrorsResponses, GetScheduleNotificationsData, GetScheduleNotificationsResponses, GetSnapshotDetailsData, GetSnapshotDetailsResponses, GetSsoSettingsData, GetSsoSettingsResponses, GetStatusData, GetStatusResponses, GetSystemInfoData, GetSystemInfoResponses, GetUpdatesData, GetUpdatesResponses, GetUserDeletionImpactData, GetUserDeletionImpactResponses, GetVolumeData, GetVolumeErrors, GetVolumeResponses, HealthCheckVolumeData, HealthCheckVolumeErrors, HealthCheckVolumeResponses, ListBackupSchedulesData, ListBackupSchedulesResponses, ListFilesData, ListFilesResponses, ListNotificationDestinationsData, ListNotificationDestinationsResponses, ListRcloneRemotesData, ListRcloneRemotesResponses, ListRepositoriesData, ListRepositoriesResponses, ListSnapshotFilesData, ListSnapshotFilesResponses, ListSnapshotsData, ListSnapshotsResponses, ListVolumesData, ListVolumesResponses, MountVolumeData, MountVolumeResponses, RefreshRepositoryStatsData, RefreshRepositoryStatsResponses, RefreshSnapshotsData, RefreshSnapshotsResponses, RemoveOrgMemberData, RemoveOrgMemberErrors, RemoveOrgMemberResponses, ReorderBackupSchedulesData, ReorderBackupSchedulesResponses, RestoreSnapshotData, RestoreSnapshotResponses, RunBackupNowData, RunBackupNowResponses, RunForgetData, RunForgetResponses, SetRegistrationStatusData, SetRegistrationStatusResponses, StartDoctorData, StartDoctorErrors, StartDoctorResponses, StopBackupData, StopBackupErrors, StopBackupResponses, SyncMirrorData, SyncMirrorErrors, SyncMirrorResponses, TagSnapshotsData, TagSnapshotsResponses, TestConnectionData, TestConnectionResponses, TestNotificationDestinationData, TestNotificationDestinationErrors, TestNotificationDestinationResponses, UnlockRepositoryData, UnlockRepositoryResponses, UnmountVolumeData, UnmountVolumeResponses, UpdateBackupScheduleData, UpdateBackupScheduleResponses, UpdateMemberRoleData, UpdateMemberRoleErrors, UpdateMemberRoleResponses, UpdateNotificationDestinationData, UpdateNotificationDestinationErrors, UpdateNotificationDestinationResponses, UpdateRepositoryData, UpdateRepositoryErrors, UpdateRepositoryResponses, UpdateScheduleMirrorsData, UpdateScheduleMirrorsResponses, UpdateScheduleNotificationsData, UpdateScheduleNotificationsResponses, UpdateSsoProviderAutoLinkingData, UpdateSsoProviderAutoLinkingErrors, UpdateSsoProviderAutoLinkingResponses, UpdateVolumeData, UpdateVolumeErrors, UpdateVolumeResponses } from './types.gen';
|
||||
|
||||
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean> = Options2<TData, ThrowOnError> & {
|
||||
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
|
||||
/**
|
||||
* You can provide a client instance returned by `createClient()` instead of
|
||||
* individual options. This might be also useful if you want to implement a
|
||||
|
|
@ -24,38 +24,6 @@ export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends
|
|||
*/
|
||||
export const getStatus = <ThrowOnError extends boolean = false>(options?: Options<GetStatusData, ThrowOnError>) => (options?.client ?? client).get<GetStatusResponses, unknown, ThrowOnError>({ url: '/api/v1/auth/status', ...options });
|
||||
|
||||
/**
|
||||
* Get public SSO providers for the instance
|
||||
*/
|
||||
export const getPublicSsoProviders = <ThrowOnError extends boolean = false>(options?: Options<GetPublicSsoProvidersData, ThrowOnError>) => (options?.client ?? client).get<GetPublicSsoProvidersResponses, unknown, ThrowOnError>({ url: '/api/v1/auth/sso-providers', ...options });
|
||||
|
||||
/**
|
||||
* Get SSO providers and invitations for the active organization
|
||||
*/
|
||||
export const getSsoSettings = <ThrowOnError extends boolean = false>(options?: Options<GetSsoSettingsData, ThrowOnError>) => (options?.client ?? client).get<GetSsoSettingsResponses, unknown, ThrowOnError>({ url: '/api/v1/auth/sso-settings', ...options });
|
||||
|
||||
/**
|
||||
* Delete an SSO provider
|
||||
*/
|
||||
export const deleteSsoProvider = <ThrowOnError extends boolean = false>(options: Options<DeleteSsoProviderData, ThrowOnError>) => (options.client ?? client).delete<DeleteSsoProviderResponses, DeleteSsoProviderErrors, ThrowOnError>({ url: '/api/v1/auth/sso-providers/{providerId}', ...options });
|
||||
|
||||
/**
|
||||
* Update whether SSO sign-in can auto-link existing accounts by email
|
||||
*/
|
||||
export const updateSsoProviderAutoLinking = <ThrowOnError extends boolean = false>(options: Options<UpdateSsoProviderAutoLinkingData, ThrowOnError>) => (options.client ?? client).patch<UpdateSsoProviderAutoLinkingResponses, UpdateSsoProviderAutoLinkingErrors, ThrowOnError>({
|
||||
url: '/api/v1/auth/sso-providers/{providerId}/auto-linking',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Delete an SSO invitation
|
||||
*/
|
||||
export const deleteSsoInvitation = <ThrowOnError extends boolean = false>(options: Options<DeleteSsoInvitationData, ThrowOnError>) => (options.client ?? client).delete<DeleteSsoInvitationResponses, DeleteSsoInvitationErrors, ThrowOnError>({ url: '/api/v1/auth/sso-invitations/{invitationId}', ...options });
|
||||
|
||||
/**
|
||||
* List admin users for settings management
|
||||
*/
|
||||
|
|
@ -93,6 +61,38 @@ export const updateMemberRole = <ThrowOnError extends boolean = false>(options:
|
|||
*/
|
||||
export const removeOrgMember = <ThrowOnError extends boolean = false>(options: Options<RemoveOrgMemberData, ThrowOnError>) => (options.client ?? client).delete<RemoveOrgMemberResponses, RemoveOrgMemberErrors, ThrowOnError>({ url: '/api/v1/auth/org-members/{memberId}', ...options });
|
||||
|
||||
/**
|
||||
* Get public SSO providers for the instance
|
||||
*/
|
||||
export const getPublicSsoProviders = <ThrowOnError extends boolean = false>(options?: Options<GetPublicSsoProvidersData, ThrowOnError>) => (options?.client ?? client).get<GetPublicSsoProvidersResponses, unknown, ThrowOnError>({ url: '/api/v1/auth/sso-providers', ...options });
|
||||
|
||||
/**
|
||||
* Get SSO providers and invitations for the active organization
|
||||
*/
|
||||
export const getSsoSettings = <ThrowOnError extends boolean = false>(options?: Options<GetSsoSettingsData, ThrowOnError>) => (options?.client ?? client).get<GetSsoSettingsResponses, unknown, ThrowOnError>({ url: '/api/v1/auth/sso-settings', ...options });
|
||||
|
||||
/**
|
||||
* Delete an SSO provider
|
||||
*/
|
||||
export const deleteSsoProvider = <ThrowOnError extends boolean = false>(options: Options<DeleteSsoProviderData, ThrowOnError>) => (options.client ?? client).delete<DeleteSsoProviderResponses, DeleteSsoProviderErrors, ThrowOnError>({ url: '/api/v1/auth/sso-providers/{providerId}', ...options });
|
||||
|
||||
/**
|
||||
* Update whether SSO sign-in can auto-link existing accounts by email
|
||||
*/
|
||||
export const updateSsoProviderAutoLinking = <ThrowOnError extends boolean = false>(options: Options<UpdateSsoProviderAutoLinkingData, ThrowOnError>) => (options.client ?? client).patch<UpdateSsoProviderAutoLinkingResponses, UpdateSsoProviderAutoLinkingErrors, ThrowOnError>({
|
||||
url: '/api/v1/auth/sso-providers/{providerId}/auto-linking',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Delete an SSO invitation
|
||||
*/
|
||||
export const deleteSsoInvitation = <ThrowOnError extends boolean = false>(options: Options<DeleteSsoInvitationData, ThrowOnError>) => (options.client ?? client).delete<DeleteSsoInvitationResponses, DeleteSsoInvitationErrors, ThrowOnError>({ url: '/api/v1/auth/sso-invitations/{invitationId}', ...options });
|
||||
|
||||
/**
|
||||
* List all volumes
|
||||
*/
|
||||
|
|
@ -101,24 +101,24 @@ export const listVolumes = <ThrowOnError extends boolean = false>(options?: Opti
|
|||
/**
|
||||
* Create a new volume
|
||||
*/
|
||||
export const createVolume = <ThrowOnError extends boolean = false>(options?: Options<CreateVolumeData, ThrowOnError>) => (options?.client ?? client).post<CreateVolumeResponses, unknown, ThrowOnError>({
|
||||
export const createVolume = <ThrowOnError extends boolean = false>(options: Options<CreateVolumeData, ThrowOnError>) => (options.client ?? client).post<CreateVolumeResponses, unknown, ThrowOnError>({
|
||||
url: '/api/v1/volumes',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options?.headers
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Test connection to backend
|
||||
*/
|
||||
export const testConnection = <ThrowOnError extends boolean = false>(options?: Options<TestConnectionData, ThrowOnError>) => (options?.client ?? client).post<TestConnectionResponses, unknown, ThrowOnError>({
|
||||
export const testConnection = <ThrowOnError extends boolean = false>(options: Options<TestConnectionData, ThrowOnError>) => (options.client ?? client).post<TestConnectionResponses, unknown, ThrowOnError>({
|
||||
url: '/api/v1/volumes/test-connection',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options?.headers
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -177,12 +177,12 @@ export const listRepositories = <ThrowOnError extends boolean = false>(options?:
|
|||
/**
|
||||
* Create a new restic repository
|
||||
*/
|
||||
export const createRepository = <ThrowOnError extends boolean = false>(options?: Options<CreateRepositoryData, ThrowOnError>) => (options?.client ?? client).post<CreateRepositoryResponses, unknown, ThrowOnError>({
|
||||
export const createRepository = <ThrowOnError extends boolean = false>(options: Options<CreateRepositoryData, ThrowOnError>) => (options.client ?? client).post<CreateRepositoryResponses, unknown, ThrowOnError>({
|
||||
url: '/api/v1/repositories',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options?.headers
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -218,6 +218,11 @@ export const updateRepository = <ThrowOnError extends boolean = false>(options:
|
|||
*/
|
||||
export const getRepositoryStats = <ThrowOnError extends boolean = false>(options: Options<GetRepositoryStatsData, ThrowOnError>) => (options.client ?? client).get<GetRepositoryStatsResponses, unknown, ThrowOnError>({ url: '/api/v1/repositories/{shortId}/stats', ...options });
|
||||
|
||||
/**
|
||||
* Refresh repository storage and compression statistics
|
||||
*/
|
||||
export const refreshRepositoryStats = <ThrowOnError extends boolean = false>(options: Options<RefreshRepositoryStatsData, ThrowOnError>) => (options.client ?? client).post<RefreshRepositoryStatsResponses, unknown, ThrowOnError>({ url: '/api/v1/repositories/{shortId}/stats/refresh', ...options });
|
||||
|
||||
/**
|
||||
* Delete multiple snapshots from a repository
|
||||
*/
|
||||
|
|
@ -302,7 +307,7 @@ export const tagSnapshots = <ThrowOnError extends boolean = false>(options: Opti
|
|||
/**
|
||||
* Execute a restic command against a repository (dev panel only)
|
||||
*/
|
||||
export const devPanelExec = <ThrowOnError extends boolean = false>(options: Options<DevPanelExecData, ThrowOnError>) => (options.client ?? client).sse.post<DevPanelExecResponses, DevPanelExecErrors, ThrowOnError>({
|
||||
export const devPanelExec = <ThrowOnError extends boolean = false>(options: Options<DevPanelExecData, ThrowOnError, DevPanelExecResponse>) => (options.client ?? client).sse.post<DevPanelExecResponses, DevPanelExecErrors, ThrowOnError>({
|
||||
url: '/api/v1/repositories/{shortId}/exec',
|
||||
...options,
|
||||
headers: {
|
||||
|
|
@ -319,12 +324,12 @@ export const listBackupSchedules = <ThrowOnError extends boolean = false>(option
|
|||
/**
|
||||
* Create a new backup schedule for a volume
|
||||
*/
|
||||
export const createBackupSchedule = <ThrowOnError extends boolean = false>(options?: Options<CreateBackupScheduleData, ThrowOnError>) => (options?.client ?? client).post<CreateBackupScheduleResponses, unknown, ThrowOnError>({
|
||||
export const createBackupSchedule = <ThrowOnError extends boolean = false>(options: Options<CreateBackupScheduleData, ThrowOnError>) => (options.client ?? client).post<CreateBackupScheduleResponses, unknown, ThrowOnError>({
|
||||
url: '/api/v1/backups',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options?.headers
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -404,6 +409,23 @@ export const updateScheduleMirrors = <ThrowOnError extends boolean = false>(opti
|
|||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Get sync status for a specific mirror, including missing snapshots
|
||||
*/
|
||||
export const getMirrorSyncStatus = <ThrowOnError extends boolean = false>(options: Options<GetMirrorSyncStatusData, ThrowOnError>) => (options.client ?? client).get<GetMirrorSyncStatusResponses, unknown, ThrowOnError>({ url: '/api/v1/backups/{shortId}/mirrors/{mirrorShortId}/status', ...options });
|
||||
|
||||
/**
|
||||
* Sync selected snapshots to a specific mirror repository
|
||||
*/
|
||||
export const syncMirror = <ThrowOnError extends boolean = false>(options: Options<SyncMirrorData, ThrowOnError>) => (options.client ?? client).post<SyncMirrorResponses, SyncMirrorErrors, ThrowOnError>({
|
||||
url: '/api/v1/backups/{shortId}/mirrors/{mirrorShortId}/sync',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Get mirror compatibility info for all repositories relative to a backup schedule's primary repository
|
||||
*/
|
||||
|
|
@ -412,12 +434,12 @@ export const getMirrorCompatibility = <ThrowOnError extends boolean = false>(opt
|
|||
/**
|
||||
* Reorder backup schedules by providing an array of schedule short IDs in the desired order
|
||||
*/
|
||||
export const reorderBackupSchedules = <ThrowOnError extends boolean = false>(options?: Options<ReorderBackupSchedulesData, ThrowOnError>) => (options?.client ?? client).post<ReorderBackupSchedulesResponses, unknown, ThrowOnError>({
|
||||
export const reorderBackupSchedules = <ThrowOnError extends boolean = false>(options: Options<ReorderBackupSchedulesData, ThrowOnError>) => (options.client ?? client).post<ReorderBackupSchedulesResponses, unknown, ThrowOnError>({
|
||||
url: '/api/v1/backups/reorder',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options?.headers
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -434,12 +456,12 @@ export const listNotificationDestinations = <ThrowOnError extends boolean = fals
|
|||
/**
|
||||
* Create a new notification destination
|
||||
*/
|
||||
export const createNotificationDestination = <ThrowOnError extends boolean = false>(options?: Options<CreateNotificationDestinationData, ThrowOnError>) => (options?.client ?? client).post<CreateNotificationDestinationResponses, unknown, ThrowOnError>({
|
||||
export const createNotificationDestination = <ThrowOnError extends boolean = false>(options: Options<CreateNotificationDestinationData, ThrowOnError>) => (options.client ?? client).post<CreateNotificationDestinationResponses, unknown, ThrowOnError>({
|
||||
url: '/api/v1/notifications/destinations',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options?.headers
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -488,24 +510,24 @@ export const getRegistrationStatus = <ThrowOnError extends boolean = false>(opti
|
|||
/**
|
||||
* Update the registration status for new users. Requires global admin role.
|
||||
*/
|
||||
export const setRegistrationStatus = <ThrowOnError extends boolean = false>(options?: Options<SetRegistrationStatusData, ThrowOnError>) => (options?.client ?? client).put<SetRegistrationStatusResponses, unknown, ThrowOnError>({
|
||||
export const setRegistrationStatus = <ThrowOnError extends boolean = false>(options: Options<SetRegistrationStatusData, ThrowOnError>) => (options.client ?? client).put<SetRegistrationStatusResponses, unknown, ThrowOnError>({
|
||||
url: '/api/v1/system/registration-status',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options?.headers
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Download the organization's Restic password for backup recovery. Requires organization owner or admin role and password re-authentication.
|
||||
*/
|
||||
export const downloadResticPassword = <ThrowOnError extends boolean = false>(options?: Options<DownloadResticPasswordData, ThrowOnError>) => (options?.client ?? client).post<DownloadResticPasswordResponses, unknown, ThrowOnError>({
|
||||
export const downloadResticPassword = <ThrowOnError extends boolean = false>(options: Options<DownloadResticPasswordData, ThrowOnError>) => (options.client ?? client).post<DownloadResticPasswordResponses, unknown, ThrowOnError>({
|
||||
url: '/api/v1/system/restic-password',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options?.headers
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,8 +1,48 @@
|
|||
/** biome-ignore-all lint/style/noNonNullAssertion: Testing file - non-null assertions are acceptable here */
|
||||
import { expect, test, describe } from "bun:test";
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
import { cleanup, render, screen, fireEvent, within } from "@testing-library/react";
|
||||
import { useState } from "react";
|
||||
import { FileTree, type FileEntry } from "../file-tree";
|
||||
|
||||
const getCheckboxFor = (name: string) => {
|
||||
const row = screen.getByRole("button", { name });
|
||||
return within(row).getByRole("checkbox");
|
||||
};
|
||||
|
||||
const FileTreeSelection = ({
|
||||
files,
|
||||
initialSelectedPaths = [],
|
||||
expandedFolders,
|
||||
}: {
|
||||
files: FileEntry[];
|
||||
initialSelectedPaths?: string[];
|
||||
expandedFolders?: Set<string>;
|
||||
}) => {
|
||||
const [selectedPaths, setSelectedPaths] = useState(() => new Set(initialSelectedPaths));
|
||||
|
||||
return (
|
||||
<>
|
||||
<FileTree
|
||||
files={files}
|
||||
withCheckboxes={true}
|
||||
selectedPaths={selectedPaths}
|
||||
onSelectionChange={setSelectedPaths}
|
||||
expandedFolders={expandedFolders}
|
||||
/>
|
||||
<output aria-label="Selected paths">{JSON.stringify(Array.from(selectedPaths).sort())}</output>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const getSelectedPaths = () => {
|
||||
const selectedPaths = screen.getByLabelText("Selected paths").textContent;
|
||||
return JSON.parse(selectedPaths ?? "[]") as string[];
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
describe("FileTree Pagination", () => {
|
||||
const testFiles: FileEntry[] = [
|
||||
{ name: "root", path: "/root", type: "folder" },
|
||||
|
|
@ -145,6 +185,19 @@ describe("FileTree Pagination", () => {
|
|||
|
||||
expect(screen.queryByText("Load more files")).toBeNull();
|
||||
});
|
||||
|
||||
test("renders missing ancestor folders for nested paths", () => {
|
||||
render(
|
||||
<FileTree
|
||||
files={[
|
||||
{ name: "subdir", path: "/project/subdir", type: "folder" },
|
||||
{ name: "file1", path: "/project/subdir/file1", type: "file" },
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByRole("button", { name: "project" })).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("FileTree Selection Logic", () => {
|
||||
|
|
@ -157,154 +210,67 @@ describe("FileTree Selection Logic", () => {
|
|||
{ name: "upload", path: "/root/photos/upload", type: "folder" },
|
||||
];
|
||||
|
||||
test("selecting a folder simplifies to parent if it's the only child", async () => {
|
||||
let currentSelection = new Set<string>();
|
||||
const onSelectionChange = (selection: Set<string>) => {
|
||||
currentSelection = selection;
|
||||
};
|
||||
test("selecting a folder simplifies to parent if it's the only child", () => {
|
||||
render(<FileTreeSelection files={testFiles} expandedFolders={new Set(testFiles.map((f) => f.path))} />);
|
||||
|
||||
render(
|
||||
<FileTree
|
||||
files={testFiles}
|
||||
withCheckboxes={true}
|
||||
selectedPaths={currentSelection}
|
||||
onSelectionChange={onSelectionChange}
|
||||
expandedFolders={new Set(testFiles.map((f) => f.path))}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(getCheckboxFor("photos"));
|
||||
|
||||
const photosCheckbox = screen.getByText("photos").parentElement?.querySelector('button[role="checkbox"]');
|
||||
expect(photosCheckbox).toBeTruthy();
|
||||
|
||||
fireEvent.click(photosCheckbox!);
|
||||
|
||||
expect(currentSelection.has("/root")).toBe(true);
|
||||
expect(currentSelection.size).toBe(1);
|
||||
expect(getSelectedPaths()).toEqual(["/root"]);
|
||||
});
|
||||
|
||||
test("unselecting a child removes the parent from selection", async () => {
|
||||
let currentSelection = new Set<string>(["/root"]);
|
||||
const onSelectionChange = (selection: Set<string>) => {
|
||||
currentSelection = selection;
|
||||
};
|
||||
|
||||
test("unselecting a child removes the parent from selection", () => {
|
||||
render(
|
||||
<FileTree
|
||||
<FileTreeSelection
|
||||
files={testFiles}
|
||||
withCheckboxes={true}
|
||||
selectedPaths={currentSelection}
|
||||
onSelectionChange={onSelectionChange}
|
||||
initialSelectedPaths={["/root"]}
|
||||
expandedFolders={new Set(testFiles.map((f) => f.path))}
|
||||
/>,
|
||||
);
|
||||
|
||||
const libraryCheckbox = screen.getByText("library").parentElement?.querySelector('button[role="checkbox"]');
|
||||
fireEvent.click(libraryCheckbox!);
|
||||
fireEvent.click(getCheckboxFor("library"));
|
||||
|
||||
expect(currentSelection.has("/root")).toBe(false);
|
||||
expect(currentSelection.has("/root/photos")).toBe(false);
|
||||
|
||||
expect(currentSelection.has("/root/photos/backups")).toBe(true);
|
||||
expect(currentSelection.has("/root/photos/profile")).toBe(true);
|
||||
expect(currentSelection.has("/root/photos/upload")).toBe(true);
|
||||
expect(currentSelection.size).toBe(3);
|
||||
expect(getSelectedPaths()).toEqual(["/root/photos/backups", "/root/photos/profile", "/root/photos/upload"]);
|
||||
});
|
||||
|
||||
test("recursive simplification when all children are selected", async () => {
|
||||
let currentSelection = new Set<string>();
|
||||
const onSelectionChange = (selection: Set<string>) => {
|
||||
currentSelection = selection;
|
||||
};
|
||||
|
||||
const { rerender } = render(
|
||||
<FileTree
|
||||
files={testFiles}
|
||||
withCheckboxes={true}
|
||||
selectedPaths={currentSelection}
|
||||
onSelectionChange={onSelectionChange}
|
||||
expandedFolders={new Set(testFiles.map((f) => f.path))}
|
||||
/>,
|
||||
);
|
||||
test("recursive simplification when all children are selected", () => {
|
||||
render(<FileTreeSelection files={testFiles} expandedFolders={new Set(testFiles.map((f) => f.path))} />);
|
||||
|
||||
const children = ["backups", "library", "profile", "upload"];
|
||||
|
||||
for (const name of children) {
|
||||
const checkbox = screen.getByText(name).parentElement?.querySelector('button[role="checkbox"]');
|
||||
fireEvent.click(checkbox!);
|
||||
|
||||
rerender(
|
||||
<FileTree
|
||||
files={testFiles}
|
||||
withCheckboxes={true}
|
||||
selectedPaths={currentSelection}
|
||||
onSelectionChange={onSelectionChange}
|
||||
expandedFolders={new Set(testFiles.map((f) => f.path))}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(getCheckboxFor(name));
|
||||
}
|
||||
|
||||
expect(currentSelection.has("/root")).toBe(true);
|
||||
expect(currentSelection.size).toBe(1);
|
||||
expect(getSelectedPaths()).toEqual(["/root"]);
|
||||
});
|
||||
|
||||
test("does not simplify to parent if not all children are selected", async () => {
|
||||
test("does not simplify to parent if not all children are selected", () => {
|
||||
const multipleFiles: FileEntry[] = [
|
||||
{ name: "root", path: "/root", type: "folder" },
|
||||
{ name: "child1", path: "/root/child1", type: "folder" },
|
||||
{ name: "child2", path: "/root/child2", type: "folder" },
|
||||
];
|
||||
|
||||
let currentSelection = new Set<string>();
|
||||
const onSelectionChange = (selection: Set<string>) => {
|
||||
currentSelection = selection;
|
||||
};
|
||||
render(<FileTreeSelection files={multipleFiles} expandedFolders={new Set(multipleFiles.map((f) => f.path))} />);
|
||||
|
||||
render(
|
||||
<FileTree
|
||||
files={multipleFiles}
|
||||
withCheckboxes={true}
|
||||
selectedPaths={currentSelection}
|
||||
onSelectionChange={onSelectionChange}
|
||||
expandedFolders={new Set(multipleFiles.map((f) => f.path))}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(getCheckboxFor("child1"));
|
||||
|
||||
const child1Checkbox = screen.getByText("child1").parentElement?.querySelector('button[role="checkbox"]');
|
||||
fireEvent.click(child1Checkbox!);
|
||||
|
||||
expect(currentSelection.has("/root/child1")).toBe(true);
|
||||
expect(currentSelection.has("/root")).toBe(false);
|
||||
expect(currentSelection.size).toBe(1);
|
||||
expect(getSelectedPaths()).toEqual(["/root/child1"]);
|
||||
});
|
||||
|
||||
test("simplifies existing deep paths when parent is selected", async () => {
|
||||
test("simplifies existing deep paths when parent is selected", () => {
|
||||
const files: FileEntry[] = [
|
||||
{ name: "hello", path: "/hello", type: "folder" },
|
||||
{ name: "hello_prev", path: "/hello_prev", type: "folder" },
|
||||
{ name: "service", path: "/service", type: "folder" },
|
||||
];
|
||||
|
||||
let currentSelection = new Set<string>(["/hello", "/hello_prev", "/service/app/data/upload"]);
|
||||
const onSelectionChange = (selection: Set<string>) => {
|
||||
currentSelection = selection;
|
||||
};
|
||||
|
||||
render(
|
||||
<FileTree
|
||||
files={files}
|
||||
withCheckboxes={true}
|
||||
selectedPaths={currentSelection}
|
||||
onSelectionChange={onSelectionChange}
|
||||
/>,
|
||||
<FileTreeSelection files={files} initialSelectedPaths={["/hello", "/hello_prev", "/service/app/data/upload"]} />,
|
||||
);
|
||||
|
||||
const serviceCheckbox = screen.getByText("service").parentElement?.querySelector('button[role="checkbox"]');
|
||||
expect(serviceCheckbox).toBeTruthy();
|
||||
fireEvent.click(getCheckboxFor("service"));
|
||||
|
||||
fireEvent.click(serviceCheckbox!);
|
||||
|
||||
expect(currentSelection.has("/service")).toBe(true);
|
||||
expect(currentSelection.has("/service/app/data/upload")).toBe(false);
|
||||
expect(currentSelection.size).toBe(3); // /hello, /hello_prev, /service
|
||||
expect(getSelectedPaths()).toEqual(["/hello", "/hello_prev", "/service"]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
155
app/client/components/__test__/restore-form.test.tsx
Normal file
155
app/client/components/__test__/restore-form.test.tsx
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { HttpResponse, http, server } from "~/test/msw/server";
|
||||
import { cleanup, render, screen, userEvent, waitFor, within } from "~/test/test-utils";
|
||||
import { fromAny } from "@total-typescript/shoehorn";
|
||||
|
||||
vi.mock("@tanstack/react-router", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@tanstack/react-router")>();
|
||||
|
||||
return {
|
||||
...actual,
|
||||
useNavigate: (() => vi.fn(async () => {})) as typeof actual.useNavigate,
|
||||
};
|
||||
});
|
||||
|
||||
import { RestoreForm } from "../restore-form";
|
||||
|
||||
class MockEventSource {
|
||||
addEventListener() {}
|
||||
close() {}
|
||||
onerror: ((event: Event) => void) | null = null;
|
||||
|
||||
constructor(public url: string) {}
|
||||
}
|
||||
|
||||
const originalEventSource = globalThis.EventSource;
|
||||
|
||||
beforeEach(() => {
|
||||
globalThis.EventSource = MockEventSource as unknown as typeof EventSource;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.EventSource = originalEventSource;
|
||||
cleanup();
|
||||
});
|
||||
|
||||
describe("RestoreForm", () => {
|
||||
test("restores the selected ancestor folder path from a broader display root", async () => {
|
||||
let restoreRequestBody: unknown;
|
||||
|
||||
server.use(
|
||||
http.get("/api/v1/repositories/:shortId/snapshots/:snapshotId/files", () => {
|
||||
return HttpResponse.json({
|
||||
files: [
|
||||
{ name: "subdir", path: "/mnt/project/subdir", type: "dir" },
|
||||
{ name: "deep.tx", path: "/mnt/project/subdir/deep.tx", type: "file" },
|
||||
],
|
||||
});
|
||||
}),
|
||||
http.post("/api/v1/repositories/:shortId/restore", async ({ request }) => {
|
||||
restoreRequestBody = await request.json();
|
||||
return HttpResponse.json({
|
||||
success: true,
|
||||
message: "Snapshot restored successfully",
|
||||
filesRestored: 1,
|
||||
filesSkipped: 0,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
render(
|
||||
<RestoreForm
|
||||
repository={fromAny({ shortId: "repo-1", name: "Repo 1" })}
|
||||
snapshotId="snap-1"
|
||||
returnPath="/repositories/repo-1/snap-1"
|
||||
queryBasePath="/mnt/project/subdir"
|
||||
displayBasePath="/mnt"
|
||||
/>,
|
||||
);
|
||||
|
||||
const row = await screen.findByRole("button", { name: "project" });
|
||||
await userEvent.click(within(row).getByRole("checkbox"));
|
||||
await userEvent.click(screen.getByRole("button", { name: "Restore 1 item" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(restoreRequestBody).toEqual({
|
||||
snapshotId: "snap-1",
|
||||
include: ["/mnt/project"],
|
||||
selectedItemKind: "dir",
|
||||
overwrite: "always",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("restores the selected full path when the display root is unrelated", async () => {
|
||||
let restoreRequestBody: unknown;
|
||||
|
||||
server.use(
|
||||
http.get("/api/v1/repositories/:shortId/snapshots/:snapshotId/files", () => {
|
||||
return HttpResponse.json({
|
||||
files: [
|
||||
{ name: "project", path: "/mnt/project", type: "dir" },
|
||||
{ name: "a.txt", path: "/mnt/project/a.txt", type: "file" },
|
||||
],
|
||||
});
|
||||
}),
|
||||
http.post("/api/v1/repositories/:shortId/restore", async ({ request }) => {
|
||||
restoreRequestBody = await request.json();
|
||||
return HttpResponse.json({
|
||||
success: true,
|
||||
message: "Snapshot restored successfully",
|
||||
filesRestored: 1,
|
||||
filesSkipped: 0,
|
||||
});
|
||||
}),
|
||||
http.get("/api/v1/volumes/filesystem/browse", () => {
|
||||
return HttpResponse.json({
|
||||
path: "/",
|
||||
directories: [{ name: "restore-target", path: "/restore-target", type: "dir" }],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
render(
|
||||
<RestoreForm
|
||||
repository={fromAny({ shortId: "repo-1", name: "Repo 1" })}
|
||||
snapshotId="snap-1"
|
||||
returnPath="/repositories/repo-1/snap-1"
|
||||
queryBasePath="/mnt/project"
|
||||
displayBasePath="/other/root"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.getByText(
|
||||
"This snapshot was created from source paths that do not match this Zerobyte server or the current linked volume. Restoring to the original location is unavailable. Restore it to a custom location, or download it instead.",
|
||||
),
|
||||
).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: "Original location" }).hasAttribute("disabled")).toBe(true);
|
||||
expect(screen.getByRole("button", { name: "Restore All" }).hasAttribute("disabled")).toBe(true);
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Change" }));
|
||||
await userEvent.click(await screen.findByRole("button", { name: "restore-target" }));
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole("button", { name: "Restore All" }).hasAttribute("disabled")).toBe(false);
|
||||
});
|
||||
|
||||
const row = await screen.findByRole("button", { name: "mnt" });
|
||||
await userEvent.click(within(row).getByRole("checkbox"));
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole("button", { name: "Restore 1 item" }).hasAttribute("disabled")).toBe(false);
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Restore 1 item" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(restoreRequestBody).toEqual({
|
||||
snapshotId: "snap-1",
|
||||
include: ["/mnt"],
|
||||
selectedItemKind: "dir",
|
||||
targetPath: "/restore-target",
|
||||
overwrite: "always",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import { Fragment } from "react";
|
||||
import { useMatches, Link } from "@tanstack/react-router";
|
||||
import {
|
||||
Breadcrumb,
|
||||
|
|
@ -41,7 +42,7 @@ export function AppBreadcrumb() {
|
|||
const isLast = index === breadcrumbs.length - 1;
|
||||
|
||||
return (
|
||||
<div key={`${breadcrumb.label}-${index}`} className="contents">
|
||||
<Fragment key={`${breadcrumb.label}-${index}`}>
|
||||
<BreadcrumbItem>
|
||||
{isLast || !breadcrumb.href ? (
|
||||
<BreadcrumbPage>{breadcrumb.label}</BreadcrumbPage>
|
||||
|
|
@ -52,7 +53,7 @@ export function AppBreadcrumb() {
|
|||
)}
|
||||
</BreadcrumbItem>
|
||||
{!isLast && <BreadcrumbSeparator />}
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</BreadcrumbList>
|
||||
|
|
|
|||
|
|
@ -69,7 +69,7 @@ export function AppSidebar({ isInstanceAdmin }: Props) {
|
|||
|
||||
return (
|
||||
<Sidebar variant="inset" collapsible="icon" className="p-0">
|
||||
<SidebarHeader className="bg-card-header border-b border-border/50 hidden md:flex h-16.25 flex-row items-center p-4">
|
||||
<SidebarHeader className="bg-card-header border-b border-border/80 dark:border-border/50 hidden md:flex h-16.25 flex-row items-center p-4">
|
||||
<Link to="/volumes" className="flex items-center gap-3 font-semibold pl-2">
|
||||
<img src="/images/zerobyte.png" alt="Zerobyte Logo" className={cn("h-8 w-8 shrink-0 object-contain -ml-2")} />
|
||||
<span
|
||||
|
|
@ -115,7 +115,7 @@ export function AppSidebar({ isInstanceAdmin }: Props) {
|
|||
/>
|
||||
<span
|
||||
className={cn({
|
||||
"text-white font-medium": isActive,
|
||||
"text-foreground font-medium": isActive,
|
||||
"text-muted-foreground": !isActive,
|
||||
})}
|
||||
>
|
||||
|
|
@ -171,7 +171,7 @@ export function AppSidebar({ isInstanceAdmin }: Props) {
|
|||
/>
|
||||
<span
|
||||
className={cn({
|
||||
"text-white font-medium": isActive,
|
||||
"text-foreground font-medium": isActive,
|
||||
"text-muted-foreground": !isActive,
|
||||
})}
|
||||
>
|
||||
|
|
@ -194,7 +194,7 @@ export function AppSidebar({ isInstanceAdmin }: Props) {
|
|||
</>
|
||||
)}
|
||||
</SidebarContent>
|
||||
<SidebarFooter className="p-4 border-r border-border/50">
|
||||
<SidebarFooter className="p-4 border-r border-border/80 dark:border-border/50">
|
||||
<OrganizationSwitcher />
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<HoverCard openDelay={200}>
|
||||
|
|
|
|||
|
|
@ -1,14 +1,13 @@
|
|||
import { Card, CardContent } from "~/client/components/ui/card";
|
||||
import { ByteSize } from "~/client/components/bytes-size";
|
||||
import type { ResticSnapshotSummaryDto } from "~/schemas/restic-dto";
|
||||
import { useRootLoaderData } from "~/client/hooks/use-root-loader-data";
|
||||
import type { ResticSnapshotSummaryDto } from "@zerobyte/core/restic";
|
||||
import { formatDuration } from "~/utils/utils";
|
||||
|
||||
type Props = {
|
||||
summary?: ResticSnapshotSummaryDto | null;
|
||||
};
|
||||
|
||||
const formatCount = (value: number) => value.toLocaleString();
|
||||
|
||||
const getDurationLabel = (start: string, end: string) => {
|
||||
const startMs = new Date(start).getTime();
|
||||
const endMs = new Date(end).getTime();
|
||||
|
|
@ -17,8 +16,11 @@ const getDurationLabel = (start: string, end: string) => {
|
|||
};
|
||||
|
||||
export const BackupSummaryCard = ({ summary }: Props) => {
|
||||
const { locale } = useRootLoaderData();
|
||||
|
||||
if (!summary) return null;
|
||||
|
||||
const formatCount = (value: number) => value.toLocaleString(locale);
|
||||
const durationLabel = getDurationLabel(summary.backup_start, summary.backup_end);
|
||||
|
||||
const topStats = [
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import type React from "react";
|
||||
import { formatBytes } from "~/utils/format-bytes";
|
||||
import { useFormatBytes } from "~/client/hooks/use-format-bytes";
|
||||
|
||||
type ByteSizeProps = {
|
||||
bytes: number;
|
||||
|
|
@ -14,6 +14,7 @@ type ByteSizeProps = {
|
|||
};
|
||||
|
||||
export function ByteSize(props: ByteSizeProps) {
|
||||
const formatBytes = useFormatBytes();
|
||||
const {
|
||||
bytes,
|
||||
base = 1000,
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { AlertCircle, CheckCircle2 } from "lucide-react";
|
|||
import { useMemo } from "react";
|
||||
import { FormControl, FormDescription, FormItem, FormLabel, FormMessage } from "~/client/components/ui/form";
|
||||
import { Input } from "~/client/components/ui/input";
|
||||
import { formatDateTime } from "~/client/lib/datetime";
|
||||
import { useTimeFormat } from "~/client/lib/datetime";
|
||||
import { cn } from "~/client/lib/utils";
|
||||
|
||||
interface CronInputProps {
|
||||
|
|
@ -13,6 +13,7 @@ interface CronInputProps {
|
|||
}
|
||||
|
||||
export function CronInput({ value, onChange, error }: CronInputProps) {
|
||||
const { formatDateTime } = useTimeFormat();
|
||||
const { isValid, nextRuns, parseError } = useMemo(() => {
|
||||
if (!value) {
|
||||
return { isValid: false, nextRuns: [], parseError: null };
|
||||
|
|
@ -59,7 +60,7 @@ export function CronInput({ value, onChange, error }: CronInputProps) {
|
|||
{value && (
|
||||
<div>
|
||||
{isValid ? (
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500" />
|
||||
<CheckCircle2 className="h-4 w-4 text-success" />
|
||||
) : (
|
||||
<AlertCircle className="h-4 w-4 text-destructive" />
|
||||
)}
|
||||
|
|
|
|||
54
app/client/components/data-table-sort-header.tsx
Normal file
54
app/client/components/data-table-sort-header.tsx
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import type { Column } from "@tanstack/react-table";
|
||||
import { ArrowDown, ArrowUp, ArrowUpDown } from "lucide-react";
|
||||
import { Button } from "~/client/components/ui/button";
|
||||
import { cn } from "~/client/lib/utils";
|
||||
|
||||
export function DataTableSortHeader<TData, TValue>({
|
||||
column,
|
||||
title,
|
||||
sortDirection,
|
||||
center = false,
|
||||
}: {
|
||||
column: Column<TData, TValue>;
|
||||
title: string;
|
||||
sortDirection: false | "asc" | "desc";
|
||||
center?: boolean;
|
||||
}) {
|
||||
const icon =
|
||||
sortDirection === "desc" ? (
|
||||
<ArrowDown className="ml-2 h-3.5 w-3.5" />
|
||||
) : sortDirection === "asc" ? (
|
||||
<ArrowUp className="ml-2 h-3.5 w-3.5" />
|
||||
) : (
|
||||
<ArrowUpDown className="ml-2 h-3.5 w-3.5" />
|
||||
);
|
||||
const iconVisibility = sortDirection ? "" : "lg:invisible lg:group-hover/sort:visible";
|
||||
|
||||
if (center) {
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
|
||||
className="h-auto! w-full! p-0! font-inherit hover:bg-transparent uppercase group/sort relative"
|
||||
>
|
||||
<span className="relative flex w-full items-center justify-center">
|
||||
{title}
|
||||
<span className={cn("lg:absolute lg:-right-6 lg:top-1/2 lg:-translate-y-1/2", iconVisibility)}>{icon}</span>
|
||||
</span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
|
||||
className="h-auto! p-0! font-inherit hover:bg-transparent uppercase group/sort"
|
||||
>
|
||||
{title}
|
||||
<span className={iconVisibility}>{icon}</span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useHotkey } from "@tanstack/react-hotkeys";
|
||||
import { useHotkeySequence } from "@tanstack/react-hotkeys";
|
||||
import { getDevPanelOptions } from "~/client/api-client/@tanstack/react-query.gen";
|
||||
import { DevPanel } from "./dev-panel";
|
||||
|
||||
|
|
@ -10,7 +10,12 @@ export function DevPanelListener() {
|
|||
...getDevPanelOptions(),
|
||||
});
|
||||
|
||||
useHotkey("Mod+Shift+D", () => setIsOpen(true), { enabled: !!devPanelStatus?.enabled, preventDefault: true });
|
||||
useHotkeySequence(["D", "E", "V"], () => setIsOpen(true), {
|
||||
enabled: !!devPanelStatus?.enabled,
|
||||
preventDefault: true,
|
||||
ignoreInputs: true,
|
||||
timeout: 1000,
|
||||
});
|
||||
|
||||
if (!devPanelStatus?.enabled) {
|
||||
return null;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,244 @@
|
|||
import type { ComponentProps } from "react";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
import { HttpResponse, http, server } from "~/test/msw/server";
|
||||
import { cleanup, fireEvent, render, screen, userEvent, waitFor, within } from "~/test/test-utils";
|
||||
|
||||
type SnapshotFilesRequest = {
|
||||
shortId: string;
|
||||
snapshotId: string;
|
||||
path: string | null;
|
||||
offset: string | null;
|
||||
limit: string | null;
|
||||
};
|
||||
|
||||
const snapshotFiles = {
|
||||
files: [
|
||||
{ name: "project", path: "/mnt/project", type: "dir" },
|
||||
{ name: "a.txt", path: "/mnt/project/a.txt", type: "file" },
|
||||
],
|
||||
};
|
||||
|
||||
import { SnapshotTreeBrowser } from "../snapshot-tree-browser";
|
||||
|
||||
const mockListSnapshotFiles = (response = snapshotFiles) => {
|
||||
const requests: SnapshotFilesRequest[] = [];
|
||||
|
||||
server.use(
|
||||
http.get("/api/v1/repositories/:shortId/snapshots/:snapshotId/files", ({ params, request }) => {
|
||||
const url = new URL(request.url);
|
||||
requests.push({
|
||||
shortId: String(params.shortId),
|
||||
snapshotId: String(params.snapshotId),
|
||||
path: url.searchParams.get("path"),
|
||||
offset: url.searchParams.get("offset"),
|
||||
limit: url.searchParams.get("limit"),
|
||||
});
|
||||
|
||||
return HttpResponse.json(response);
|
||||
}),
|
||||
);
|
||||
|
||||
return requests;
|
||||
};
|
||||
|
||||
const renderSnapshotTreeBrowser = (props: Partial<ComponentProps<typeof SnapshotTreeBrowser>> = {}) => {
|
||||
return render(
|
||||
<SnapshotTreeBrowser
|
||||
repositoryId="repo-1"
|
||||
snapshotId="snap-1"
|
||||
queryBasePath="/mnt/project"
|
||||
displayBasePath="/mnt"
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
describe("SnapshotTreeBrowser", () => {
|
||||
test("renders the query root folder when display base path is broader than query base path", async () => {
|
||||
mockListSnapshotFiles();
|
||||
|
||||
renderSnapshotTreeBrowser();
|
||||
|
||||
expect(await screen.findByRole("button", { name: "project" })).toBeTruthy();
|
||||
});
|
||||
|
||||
test("renders ancestor folders when the query root is nested multiple levels below the display root", async () => {
|
||||
mockListSnapshotFiles({
|
||||
files: [
|
||||
{ name: "subdir", path: "/mnt/project/subdir", type: "dir" },
|
||||
{ name: "a.txt", path: "/mnt/project/subdir/a.txt", type: "file" },
|
||||
],
|
||||
});
|
||||
|
||||
renderSnapshotTreeBrowser({
|
||||
queryBasePath: "/mnt/project/subdir",
|
||||
displayBasePath: "/mnt",
|
||||
});
|
||||
|
||||
expect(await screen.findByRole("button", { name: "project" })).toBeTruthy();
|
||||
});
|
||||
|
||||
test("renders synthesized ancestor folders for a single file when no display base path is available", async () => {
|
||||
const requests = mockListSnapshotFiles({
|
||||
files: [{ name: "report.txt", path: "/mnt/project/report.txt", type: "file" }],
|
||||
});
|
||||
|
||||
renderSnapshotTreeBrowser({
|
||||
queryBasePath: "/mnt/project/report.txt",
|
||||
displayBasePath: undefined,
|
||||
});
|
||||
|
||||
const mntRow = await screen.findByRole("button", { name: "mnt" });
|
||||
const mntExpandIcon = mntRow.querySelector("svg");
|
||||
if (!mntExpandIcon) {
|
||||
throw new Error("Expected expand icon for mnt row");
|
||||
}
|
||||
fireEvent.click(mntExpandIcon);
|
||||
|
||||
expect(await screen.findByRole("button", { name: "project" })).toBeTruthy();
|
||||
expect(requests[0]).toEqual({
|
||||
shortId: "repo-1",
|
||||
snapshotId: "snap-1",
|
||||
path: "/mnt/project/report.txt",
|
||||
offset: null,
|
||||
limit: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("returns the ancestor folder path when selecting above the query root", async () => {
|
||||
mockListSnapshotFiles({
|
||||
files: [
|
||||
{ name: "subdir", path: "/mnt/project/subdir", type: "dir" },
|
||||
{ name: "a.txt", path: "/mnt/project/subdir/a.txt", type: "file" },
|
||||
],
|
||||
});
|
||||
|
||||
let selectedPaths: Set<string> | undefined;
|
||||
let selectedKind: "file" | "dir" | null = null;
|
||||
|
||||
renderSnapshotTreeBrowser({
|
||||
queryBasePath: "/mnt/project/subdir",
|
||||
displayBasePath: "/mnt",
|
||||
withCheckboxes: true,
|
||||
onSelectionChange: (paths) => {
|
||||
selectedPaths = paths;
|
||||
},
|
||||
onSingleSelectionKindChange: (kind) => {
|
||||
selectedKind = kind;
|
||||
},
|
||||
});
|
||||
|
||||
const row = await screen.findByRole("button", { name: "project" });
|
||||
const checkbox = within(row).getByRole("checkbox");
|
||||
|
||||
await userEvent.click(checkbox);
|
||||
|
||||
expect(selectedPaths ? Array.from(selectedPaths) : []).toEqual(["/mnt/project"]);
|
||||
expect(selectedKind === "dir").toBe(true);
|
||||
});
|
||||
|
||||
test("keeps full paths when the display root does not contain the query root", async () => {
|
||||
mockListSnapshotFiles();
|
||||
|
||||
let selectedPaths: Set<string> | undefined;
|
||||
let selectedKind: "file" | "dir" | null = null;
|
||||
|
||||
renderSnapshotTreeBrowser({
|
||||
queryBasePath: "/mnt/project",
|
||||
displayBasePath: "/other/root",
|
||||
withCheckboxes: true,
|
||||
onSelectionChange: (paths) => {
|
||||
selectedPaths = paths;
|
||||
},
|
||||
onSingleSelectionKindChange: (kind) => {
|
||||
selectedKind = kind;
|
||||
},
|
||||
});
|
||||
|
||||
const row = await screen.findByRole("button", { name: "mnt" });
|
||||
const checkbox = within(row).getByRole("checkbox");
|
||||
|
||||
await userEvent.click(checkbox);
|
||||
|
||||
expect(selectedPaths ? Array.from(selectedPaths) : []).toEqual(["/mnt"]);
|
||||
expect(selectedKind === "dir").toBe(true);
|
||||
});
|
||||
|
||||
test("shows selected folder state when full paths are provided from the parent", async () => {
|
||||
mockListSnapshotFiles();
|
||||
|
||||
renderSnapshotTreeBrowser({
|
||||
withCheckboxes: true,
|
||||
selectedPaths: new Set(["/mnt/project"]),
|
||||
onSelectionChange: () => {},
|
||||
});
|
||||
|
||||
const row = await screen.findByRole("button", { name: "project" });
|
||||
const checkbox = within(row).getByRole("checkbox");
|
||||
|
||||
expect(checkbox.getAttribute("aria-checked")).toBe("true");
|
||||
});
|
||||
|
||||
test("returns the full snapshot path and kind when selecting a displayed folder", async () => {
|
||||
mockListSnapshotFiles();
|
||||
|
||||
let selectedPaths: Set<string> | undefined;
|
||||
let selectedKind: "file" | "dir" | null = null;
|
||||
|
||||
renderSnapshotTreeBrowser({
|
||||
withCheckboxes: true,
|
||||
onSelectionChange: (paths) => {
|
||||
selectedPaths = paths;
|
||||
},
|
||||
onSingleSelectionKindChange: (kind) => {
|
||||
selectedKind = kind;
|
||||
},
|
||||
});
|
||||
|
||||
const row = await screen.findByRole("button", { name: "project" });
|
||||
const checkbox = within(row).getByRole("checkbox");
|
||||
|
||||
await userEvent.click(checkbox);
|
||||
|
||||
expect(selectedPaths ? Array.from(selectedPaths) : []).toEqual(["/mnt/project"]);
|
||||
expect(selectedKind === "dir").toBe(true);
|
||||
});
|
||||
|
||||
test("uses the query base path for the initial request when display base path is broader", async () => {
|
||||
const requests = mockListSnapshotFiles();
|
||||
|
||||
renderSnapshotTreeBrowser();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(requests[0]).toEqual({
|
||||
shortId: "repo-1",
|
||||
snapshotId: "snap-1",
|
||||
path: "/mnt/project",
|
||||
offset: null,
|
||||
limit: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("shows the query root contents when display and query roots differ", async () => {
|
||||
mockListSnapshotFiles();
|
||||
|
||||
renderSnapshotTreeBrowser();
|
||||
|
||||
const row = await screen.findByRole("button", { name: "project" });
|
||||
const expandIcon = row.querySelector("svg");
|
||||
if (!expandIcon) {
|
||||
throw new Error("Expected expand icon for folder row");
|
||||
}
|
||||
|
||||
if (!screen.queryByRole("button", { name: "a.txt" })) {
|
||||
fireEvent.click(expandIcon);
|
||||
}
|
||||
|
||||
expect(await screen.findByRole("button", { name: "a.txt" })).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
|
@ -3,7 +3,8 @@ import { browseFilesystemOptions } from "~/client/api-client/@tanstack/react-que
|
|||
import { FileBrowser, type FileBrowserUiProps } from "~/client/components/file-browsers/file-browser";
|
||||
import { useFileBrowser } from "~/client/hooks/use-file-browser";
|
||||
import { parseError } from "~/client/lib/errors";
|
||||
import { normalizeAbsolutePath } from "~/utils/path";
|
||||
import { normalizeAbsolutePath } from "@zerobyte/core/utils";
|
||||
import { logger } from "~/client/lib/logger";
|
||||
|
||||
type LocalFileBrowserProps = FileBrowserUiProps & {
|
||||
initialPath?: string;
|
||||
|
|
@ -26,7 +27,7 @@ export const LocalFileBrowser = ({ initialPath = "/", enabled = true, ...uiProps
|
|||
return await queryClient.ensureQueryData(browseFilesystemOptions({ query: { path } }));
|
||||
},
|
||||
prefetchFolder: (path) => {
|
||||
void queryClient.prefetchQuery(browseFilesystemOptions({ query: { path } }));
|
||||
void queryClient.prefetchQuery(browseFilesystemOptions({ query: { path } })).catch((e) => logger.error(e));
|
||||
},
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -4,106 +4,107 @@ import { listSnapshotFilesOptions } from "~/client/api-client/@tanstack/react-qu
|
|||
import { FileBrowser, type FileBrowserUiProps } from "~/client/components/file-browsers/file-browser";
|
||||
import { useFileBrowser } from "~/client/hooks/use-file-browser";
|
||||
import { parseError } from "~/client/lib/errors";
|
||||
import { normalizeAbsolutePath } from "~/utils/path";
|
||||
import { isPathWithin, normalizeAbsolutePath } from "@zerobyte/core/utils";
|
||||
|
||||
function createPathPrefixFns(basePath: string) {
|
||||
return {
|
||||
strip(path: string) {
|
||||
if (basePath === "/") return path;
|
||||
if (path === basePath) return "/";
|
||||
if (path.startsWith(`${basePath}/`)) return path.slice(basePath.length);
|
||||
return path;
|
||||
},
|
||||
add(displayPath: string) {
|
||||
if (basePath === "/") return displayPath;
|
||||
if (displayPath === "/") return basePath;
|
||||
return `${basePath}${displayPath}`;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
type SnapshotTreeBrowserProps = FileBrowserUiProps & {
|
||||
repositoryId: string;
|
||||
snapshotId: string;
|
||||
basePath?: string;
|
||||
queryBasePath?: string;
|
||||
displayBasePath?: string;
|
||||
pageSize?: number;
|
||||
enabled?: boolean;
|
||||
onSingleSelectionKindChange?: (kind: "file" | "dir" | null) => void;
|
||||
};
|
||||
|
||||
export const SnapshotTreeBrowser = ({
|
||||
repositoryId,
|
||||
snapshotId,
|
||||
basePath = "/",
|
||||
pageSize = 500,
|
||||
enabled = true,
|
||||
...uiProps
|
||||
}: SnapshotTreeBrowserProps) => {
|
||||
export const SnapshotTreeBrowser = (props: SnapshotTreeBrowserProps) => {
|
||||
const {
|
||||
repositoryId,
|
||||
snapshotId,
|
||||
queryBasePath = "/",
|
||||
displayBasePath,
|
||||
pageSize = 500,
|
||||
enabled = true,
|
||||
...uiProps
|
||||
} = props;
|
||||
|
||||
const { selectedPaths, onSelectionChange, onSingleSelectionKindChange, ...fileBrowserUiProps } = uiProps;
|
||||
const queryClient = useQueryClient();
|
||||
const normalizedBasePath = normalizeAbsolutePath(basePath);
|
||||
const normalizedQueryBasePath = normalizeAbsolutePath(queryBasePath);
|
||||
const normalizedDisplayBasePath = normalizeAbsolutePath(displayBasePath ?? "/");
|
||||
const effectiveDisplayBasePath = isPathWithin(normalizedDisplayBasePath, normalizedQueryBasePath)
|
||||
? normalizedDisplayBasePath
|
||||
: "/";
|
||||
|
||||
const { data, isLoading, error } = useQuery({
|
||||
...listSnapshotFilesOptions({
|
||||
path: { shortId: repositoryId, snapshotId },
|
||||
query: { path: normalizedBasePath },
|
||||
query: { path: normalizedQueryBasePath },
|
||||
}),
|
||||
enabled,
|
||||
});
|
||||
|
||||
const stripBasePath = useCallback(
|
||||
(path: string): string => {
|
||||
if (normalizedBasePath === "/") return path;
|
||||
if (path === normalizedBasePath) return "/";
|
||||
if (path.startsWith(`${normalizedBasePath}/`)) {
|
||||
return path.slice(normalizedBasePath.length);
|
||||
}
|
||||
return path;
|
||||
},
|
||||
[normalizedBasePath],
|
||||
);
|
||||
|
||||
const addBasePath = useCallback(
|
||||
(displayPath: string): string => {
|
||||
if (normalizedBasePath === "/") return displayPath;
|
||||
if (displayPath === "/") return normalizedBasePath;
|
||||
return `${normalizedBasePath}${displayPath}`;
|
||||
},
|
||||
[normalizedBasePath],
|
||||
);
|
||||
const displayPathFns = useMemo(() => createPathPrefixFns(effectiveDisplayBasePath), [effectiveDisplayBasePath]);
|
||||
|
||||
const displaySelectedPaths = useMemo(() => {
|
||||
if (!selectedPaths) return undefined;
|
||||
|
||||
const displayPaths = new Set<string>();
|
||||
for (const fullPath of selectedPaths) {
|
||||
displayPaths.add(stripBasePath(fullPath));
|
||||
displayPaths.add(displayPathFns.strip(fullPath));
|
||||
}
|
||||
|
||||
return displayPaths;
|
||||
}, [selectedPaths, stripBasePath]);
|
||||
}, [displayPathFns, selectedPaths]);
|
||||
|
||||
const fileBrowser = useFileBrowser({
|
||||
initialData: data,
|
||||
isLoading,
|
||||
fetchFolder: async (path, offset = 0) => {
|
||||
fetchFolder: async (displayPath, offset = 0) => {
|
||||
return await queryClient.ensureQueryData(
|
||||
listSnapshotFilesOptions({
|
||||
path: { shortId: repositoryId, snapshotId },
|
||||
query: {
|
||||
path,
|
||||
offset: offset.toString(),
|
||||
limit: pageSize.toString(),
|
||||
},
|
||||
query: { path: displayPath, offset: offset, limit: pageSize },
|
||||
}),
|
||||
);
|
||||
},
|
||||
prefetchFolder: (path) => {
|
||||
void queryClient.prefetchQuery(
|
||||
listSnapshotFilesOptions({
|
||||
path: { shortId: repositoryId, snapshotId },
|
||||
query: {
|
||||
path,
|
||||
offset: "0",
|
||||
limit: pageSize.toString(),
|
||||
},
|
||||
}),
|
||||
);
|
||||
},
|
||||
pathTransform: {
|
||||
strip: stripBasePath,
|
||||
add: addBasePath,
|
||||
},
|
||||
pathTransform: displayPathFns,
|
||||
});
|
||||
|
||||
const displayPathKinds = useMemo(() => {
|
||||
const kinds = new Map<string, "file" | "dir">();
|
||||
for (const entry of fileBrowser.fileArray) {
|
||||
kinds.set(entry.path, entry.type === "file" ? "file" : "dir");
|
||||
|
||||
let parentPath = entry.path;
|
||||
while (true) {
|
||||
const lastSlashIndex = parentPath.lastIndexOf("/");
|
||||
if (lastSlashIndex <= 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
parentPath = parentPath.slice(0, lastSlashIndex);
|
||||
if (kinds.has(parentPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
kinds.set(parentPath, "dir");
|
||||
}
|
||||
}
|
||||
return kinds;
|
||||
}, [fileBrowser.fileArray]);
|
||||
|
|
@ -114,7 +115,7 @@ export const SnapshotTreeBrowser = ({
|
|||
|
||||
const nextFullPaths = new Set<string>();
|
||||
for (const displayPath of nextDisplayPaths) {
|
||||
nextFullPaths.add(addBasePath(displayPath));
|
||||
nextFullPaths.add(displayPathFns.add(displayPath));
|
||||
}
|
||||
|
||||
if (onSingleSelectionKindChange) {
|
||||
|
|
@ -132,7 +133,7 @@ export const SnapshotTreeBrowser = ({
|
|||
|
||||
onSelectionChange(nextFullPaths);
|
||||
},
|
||||
[onSelectionChange, addBasePath, onSingleSelectionKindChange, displayPathKinds],
|
||||
[displayPathFns, displayPathKinds, onSelectionChange, onSingleSelectionKindChange],
|
||||
);
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { listFilesOptions } from "~/client/api-client/@tanstack/react-query.gen"
|
|||
import { FileBrowser, type FileBrowserUiProps } from "~/client/components/file-browsers/file-browser";
|
||||
import { useFileBrowser, type FetchFolderResult } from "~/client/hooks/use-file-browser";
|
||||
import { parseError } from "~/client/lib/errors";
|
||||
import { logger } from "~/client/lib/logger";
|
||||
|
||||
type VolumeFileBrowserProps = FileBrowserUiProps & {
|
||||
volumeId: string;
|
||||
|
|
@ -24,17 +25,19 @@ export const VolumeFileBrowser = ({ volumeId, enabled = true, ...uiProps }: Volu
|
|||
return await queryClient.ensureQueryData(
|
||||
listFilesOptions({
|
||||
path: { shortId: volumeId },
|
||||
query: { path, offset: offset?.toString() },
|
||||
query: { path, offset: offset },
|
||||
}),
|
||||
);
|
||||
},
|
||||
prefetchFolder: (path) => {
|
||||
void queryClient.prefetchQuery(
|
||||
listFilesOptions({
|
||||
path: { shortId: volumeId },
|
||||
query: { path },
|
||||
}),
|
||||
);
|
||||
void queryClient
|
||||
.prefetchQuery(
|
||||
listFilesOptions({
|
||||
path: { shortId: volumeId },
|
||||
query: { path },
|
||||
}),
|
||||
)
|
||||
.catch((e) => logger.error(e));
|
||||
},
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -114,20 +114,25 @@ export const FileTree = memo((props: Props) => {
|
|||
|
||||
const toggleCollapseState = useCallback(
|
||||
(fullPath: string) => {
|
||||
const shouldExpand = collapsedFolders.has(fullPath);
|
||||
|
||||
setCollapsedFolders((prevSet) => {
|
||||
const newSet = new Set(prevSet);
|
||||
|
||||
if (newSet.has(fullPath)) {
|
||||
newSet.delete(fullPath);
|
||||
onFolderExpand?.(fullPath);
|
||||
} else {
|
||||
newSet.add(fullPath);
|
||||
}
|
||||
|
||||
return newSet;
|
||||
});
|
||||
|
||||
if (shouldExpand) {
|
||||
onFolderExpand?.(fullPath);
|
||||
}
|
||||
},
|
||||
[onFolderExpand],
|
||||
[collapsedFolders, onFolderExpand],
|
||||
);
|
||||
|
||||
// Add new folders to collapsed set when file list changes
|
||||
|
|
@ -581,8 +586,10 @@ const NodeButton = memo(({ depth, icon, onClick, onMouseEnter, className, childr
|
|||
);
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
<div
|
||||
// oxlint-disable-next-line jsx_a11y/prefer-tag-over-role
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
className={cn("flex items-center gap-2 w-full pr-2 text-sm py-1.5 text-left", className)}
|
||||
style={{ paddingLeft }}
|
||||
onClick={onClick}
|
||||
|
|
@ -591,7 +598,7 @@ const NodeButton = memo(({ depth, icon, onClick, onMouseEnter, className, childr
|
|||
>
|
||||
{icon}
|
||||
<div className="truncate w-full flex items-center gap-2">{children}</div>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -625,6 +632,10 @@ function buildFileList(files: FileEntry[], foldersOnly = false): Node[] {
|
|||
const depth = segments.length - 1;
|
||||
const name = segments[segments.length - 1];
|
||||
|
||||
if (!name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!fileMap.has(file.path)) {
|
||||
const isFile = file.type === "file";
|
||||
fileMap.set(file.path, {
|
||||
|
|
@ -636,6 +647,33 @@ function buildFileList(files: FileEntry[], foldersOnly = false): Node[] {
|
|||
size: file.size,
|
||||
});
|
||||
}
|
||||
|
||||
let parentPath = file.path;
|
||||
while (true) {
|
||||
const lastSlashIndex = parentPath.lastIndexOf("/");
|
||||
if (lastSlashIndex <= 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
parentPath = parentPath.slice(0, lastSlashIndex);
|
||||
if (fileMap.has(parentPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const parentSegments = parentPath.split("/").filter((segment) => segment);
|
||||
const parentName = parentSegments[parentSegments.length - 1];
|
||||
if (!parentName) {
|
||||
continue;
|
||||
}
|
||||
|
||||
fileMap.set(parentPath, {
|
||||
kind: "folder",
|
||||
id: fileMap.size,
|
||||
name: parentName,
|
||||
fullPath: parentPath,
|
||||
depth: parentSegments.length - 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Convert map to array and sort
|
||||
|
|
@ -702,5 +740,7 @@ function compareNodes(a: Node, b: Node): number {
|
|||
return a.kind === "folder" ? -1 : 1;
|
||||
}
|
||||
|
||||
return a.name.localeCompare(b.name);
|
||||
if (a.name < b.name) return -1;
|
||||
if (a.name > b.name) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ export function GridBackground({ children, className, containerClassName }: Grid
|
|||
className={cn(
|
||||
"pointer-events-none absolute inset-0 w-full h-full",
|
||||
"bg-[size:40px_40px]",
|
||||
"bg-[linear-gradient(to_right,#e4e4e7_1px,transparent_1px),linear-gradient(to_bottom,#e4e4e7_1px,transparent_1px)]",
|
||||
"bg-[linear-gradient(to_right,rgba(0,0,0,0.04)_1px,transparent_1px),linear-gradient(to_bottom,rgba(0,0,0,0.04)_1px,transparent_1px)]",
|
||||
"dark:bg-[linear-gradient(to_right,#262626_1px,transparent_1px),linear-gradient(to_bottom,#262626_1px,transparent_1px)]",
|
||||
"[mask-image:radial-gradient(ellipse_at_top,black_70%,transparent_100%)]",
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { LifeBuoy, LogOut } from "lucide-react";
|
|||
import { toast } from "sonner";
|
||||
import { type AppContext } from "~/context";
|
||||
import { GridBackground } from "./grid-background";
|
||||
import { Button } from "./ui/button";
|
||||
import { Button, buttonVariants } from "./ui/button";
|
||||
import { SidebarProvider, SidebarTrigger } from "./ui/sidebar";
|
||||
import { AppSidebar } from "./app-sidebar";
|
||||
import { authClient } from "../lib/auth-client";
|
||||
|
|
@ -10,6 +10,7 @@ import { DevPanelListener } from "./dev-panel-listener";
|
|||
import { Outlet, useNavigate } from "@tanstack/react-router";
|
||||
import { AppBreadcrumb } from "./app-breadcrumb";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";
|
||||
import { ThemeToggle } from "./theme-toggle";
|
||||
|
||||
type Props = {
|
||||
loaderData: AppContext;
|
||||
|
|
@ -35,23 +36,24 @@ export function Layout({ loaderData }: Props) {
|
|||
<SidebarProvider defaultOpen={loaderData.sidebarOpen}>
|
||||
<AppSidebar isInstanceAdmin={loaderData.user?.role === "admin"} />
|
||||
<div className="w-full relative flex flex-col min-h-screen md:h-screen md:overflow-hidden">
|
||||
<header className="z-50 bg-card-header border-b border-border/50 shrink-0 h-16.25">
|
||||
<header className="z-50 bg-card-header border-b border-border/80 dark:border-border/50 shrink-0 h-16.25">
|
||||
<div className="flex items-center h-full justify-between px-2 sm:px-8 mx-auto container gap-4">
|
||||
<div className="flex items-center gap-4 min-w-0">
|
||||
<SidebarTrigger />
|
||||
<AppBreadcrumb />
|
||||
</div>
|
||||
{loaderData.user && (
|
||||
<div className="flex items-center bg-muted/30 border border-border/50 px-2 py-1 rounded-full shadow-sm">
|
||||
<div className="flex items-center bg-card dark:bg-muted/30 border border-border/80 dark:border-border/50 px-2 py-1 rounded-full shadow-[0_2px_10px_-4px_rgba(0,0,0,0.05)] dark:shadow-sm">
|
||||
<span className="text-sm text-muted-foreground hidden md:inline-flex pl-2 mr-5">
|
||||
<span className="text-foreground">{loaderData.user.name}</span>
|
||||
</span>
|
||||
<ThemeToggle />
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="rounded-full h-7 text-xs text-muted-foreground hover:text-white"
|
||||
className="rounded-full h-7 text-xs text-muted-foreground hover:text-foreground"
|
||||
onClick={handleLogout}
|
||||
>
|
||||
<LogOut className="w-4 h-4" />
|
||||
|
|
@ -61,20 +63,19 @@ export function Layout({ loaderData }: Props) {
|
|||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="relative overflow-hidden hidden lg:inline-flex rounded-full h-7 w-7 text-muted-foreground hover:text-white"
|
||||
<a
|
||||
href="https://github.com/nicotsx/zerobyte/issues/new/choose"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className={buttonVariants({
|
||||
variant: "ghost",
|
||||
size: "icon",
|
||||
className:
|
||||
"relative overflow-hidden hidden lg:inline-flex rounded-full h-7 w-7 text-muted-foreground hover:text-foreground",
|
||||
})}
|
||||
>
|
||||
<a
|
||||
href="https://github.com/nicotsx/zerobyte/issues/new"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center justify-center w-full h-full"
|
||||
>
|
||||
<LifeBuoy className="w-4 h-4" />
|
||||
</a>
|
||||
</Button>
|
||||
<LifeBuoy className="w-4 h-4" />
|
||||
</a>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Report an issue</TooltipContent>
|
||||
</Tooltip>
|
||||
|
|
|
|||
23
app/client/components/managed-badge.tsx
Normal file
23
app/client/components/managed-badge.tsx
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import { Badge } from "~/client/components/ui/badge";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "~/client/components/ui/tooltip";
|
||||
|
||||
type ManagedBadgeProps = {
|
||||
label?: string;
|
||||
message?: string;
|
||||
};
|
||||
|
||||
const defaultMessage =
|
||||
"This resource is provisioned at startup. Changes are useful for testing, but the next provisioning sync can overwrite or recreate it.";
|
||||
|
||||
export const ManagedBadge = ({ label = "Managed", message = defaultMessage }: ManagedBadgeProps) => {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Badge variant="secondary">{label}</Badge>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p className="max-w-80 text-sm">{message}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
};
|
||||
|
|
@ -15,7 +15,7 @@ export const OnOff = ({ isOn, toggle, enabledLabel, disabledLabel, disabled }: P
|
|||
className={cn(
|
||||
"flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-semibold uppercase tracking-wide transition-colors",
|
||||
isOn
|
||||
? "border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-500/40 dark:bg-emerald-500/10 dark:text-emerald-200"
|
||||
? "border-success/30 bg-success/10 text-success"
|
||||
: "border-muted bg-muted/40 text-muted-foreground dark:border-muted/60 dark:bg-muted/10",
|
||||
)}
|
||||
>
|
||||
|
|
|
|||
|
|
@ -59,7 +59,7 @@ export function OrganizationSwitcher() {
|
|||
size="lg"
|
||||
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
|
||||
>
|
||||
<div className="bg-black text-sidebar-primary-foreground flex aspect-square size-8 shrink-0 items-center justify-center overflow-hidden rounded-lg">
|
||||
<div className="bg-foreground text-sidebar-primary-foreground flex aspect-square size-8 shrink-0 items-center justify-center overflow-hidden rounded-lg">
|
||||
{activeOrganization?.logo ? (
|
||||
<img
|
||||
src={activeOrganization.logo}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import ReactMarkdown from "react-markdown";
|
|||
import remarkGfm from "remark-gfm";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "~/client/components/ui/dialog";
|
||||
import { ScrollArea } from "~/client/components/ui/scroll-area";
|
||||
import { formatDate } from "~/client/lib/datetime";
|
||||
import { useTimeFormat } from "~/client/lib/datetime";
|
||||
import type { UpdateInfoDto } from "~/server/modules/system/system.dto";
|
||||
|
||||
interface ReleaseNotesDialogProps {
|
||||
|
|
@ -12,6 +12,8 @@ interface ReleaseNotesDialogProps {
|
|||
}
|
||||
|
||||
export function ReleaseNotesDialog({ open, onOpenChange, updates }: ReleaseNotesDialogProps) {
|
||||
const { formatDate } = useTimeFormat();
|
||||
|
||||
if (!updates) return null;
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { Database, HardDrive, Cloud, Server } from "lucide-react";
|
||||
import type { RepositoryBackend } from "~/schemas/restic";
|
||||
import type { RepositoryBackend } from "@zerobyte/core/restic";
|
||||
|
||||
type Props = {
|
||||
backend: RepositoryBackend;
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { ChevronDown, Download, FolderOpen, RotateCcw } from "lucide-react";
|
||||
import { AlertTriangle, ChevronDown, Download, FolderOpen, RotateCcw } from "lucide-react";
|
||||
import { Button } from "~/client/components/ui/button";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "~/client/components/ui/tooltip";
|
||||
import { Alert, AlertDescription, AlertTitle } from "~/client/components/ui/alert";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/client/components/ui/card";
|
||||
import { Input } from "~/client/components/ui/input";
|
||||
import { Label } from "~/client/components/ui/label";
|
||||
|
|
@ -21,7 +22,8 @@ import { SnapshotTreeBrowser } from "~/client/components/file-browsers/snapshot-
|
|||
import { RestoreProgress } from "~/client/components/restore-progress";
|
||||
import { restoreSnapshotMutation } from "~/client/api-client/@tanstack/react-query.gen";
|
||||
import { type RestoreCompletedEvent, useServerEvents } from "~/client/hooks/use-server-events";
|
||||
import { OVERWRITE_MODES, type OverwriteMode } from "~/schemas/restic";
|
||||
import { OVERWRITE_MODES, type OverwriteMode } from "@zerobyte/core/restic";
|
||||
import { isPathWithin } from "@zerobyte/core/utils";
|
||||
import type { Repository } from "~/client/lib/types";
|
||||
import { handleRepositoryError } from "~/client/lib/errors";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
|
|
@ -33,16 +35,29 @@ interface RestoreFormProps {
|
|||
repository: Repository;
|
||||
snapshotId: string;
|
||||
returnPath: string;
|
||||
basePath?: string;
|
||||
queryBasePath?: string;
|
||||
displayBasePath?: string;
|
||||
hasNonPosixSnapshotPaths?: boolean;
|
||||
}
|
||||
|
||||
export function RestoreForm({ repository, snapshotId, returnPath, basePath }: RestoreFormProps) {
|
||||
export function RestoreForm({
|
||||
repository,
|
||||
snapshotId,
|
||||
returnPath,
|
||||
queryBasePath,
|
||||
displayBasePath,
|
||||
hasNonPosixSnapshotPaths = false,
|
||||
}: RestoreFormProps) {
|
||||
const navigate = useNavigate();
|
||||
const { addEventListener } = useServerEvents();
|
||||
|
||||
const volumeBasePath = basePath ?? "/";
|
||||
const snapshotBasePath = queryBasePath ?? "/";
|
||||
const hasMismatchedDisplayBasePath = displayBasePath && !isPathWithin(displayBasePath, snapshotBasePath);
|
||||
const restoreRequiresCustomTarget = hasNonPosixSnapshotPaths || hasMismatchedDisplayBasePath;
|
||||
|
||||
const [restoreLocation, setRestoreLocation] = useState<RestoreLocation>("original");
|
||||
const [restoreLocation, setRestoreLocation] = useState<RestoreLocation>(
|
||||
restoreRequiresCustomTarget ? "custom" : "original",
|
||||
);
|
||||
const [customTargetPath, setCustomTargetPath] = useState("");
|
||||
const [overwriteMode, setOverwriteMode] = useState<OverwriteMode>("always");
|
||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||
|
|
@ -54,6 +69,15 @@ export function RestoreForm({ repository, snapshotId, returnPath, basePath }: Re
|
|||
|
||||
const [selectedPaths, setSelectedPaths] = useState<Set<string>>(new Set());
|
||||
const [selectedPathKind, setSelectedPathKind] = useState<"file" | "dir" | null>(null);
|
||||
const trimmedCustomTargetPath = customTargetPath.trim();
|
||||
const hasCustomTargetPath = trimmedCustomTargetPath !== "";
|
||||
const selectedPathCount = selectedPaths.size;
|
||||
|
||||
useEffect(() => {
|
||||
if (restoreRequiresCustomTarget) {
|
||||
setRestoreLocation("custom");
|
||||
}
|
||||
}, [restoreRequiresCustomTarget]);
|
||||
|
||||
useEffect(() => {
|
||||
const abortController = new AbortController();
|
||||
|
|
@ -113,13 +137,13 @@ export function RestoreForm({ repository, snapshotId, returnPath, basePath }: Re
|
|||
});
|
||||
|
||||
const handleRestore = useCallback(() => {
|
||||
const excludeXattrArray = excludeXattr
|
||||
?.split(",")
|
||||
.map((s) => s.trim())
|
||||
const excludeXattrValues = excludeXattr
|
||||
.split(",")
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const isCustomLocation = restoreLocation === "custom";
|
||||
const targetPath = isCustomLocation && customTargetPath.trim() ? customTargetPath.trim() : undefined;
|
||||
const targetPath = isCustomLocation && hasCustomTargetPath ? trimmedCustomTargetPath : undefined;
|
||||
|
||||
const includePaths = Array.from(selectedPaths);
|
||||
|
||||
|
|
@ -133,7 +157,8 @@ export function RestoreForm({ repository, snapshotId, returnPath, basePath }: Re
|
|||
body: {
|
||||
snapshotId,
|
||||
include: includePaths.length > 0 ? includePaths : undefined,
|
||||
excludeXattr: excludeXattrArray && excludeXattrArray.length > 0 ? excludeXattrArray : undefined,
|
||||
selectedItemKind: includePaths.length === 1 ? (selectedPathKind ?? undefined) : undefined,
|
||||
excludeXattr: excludeXattrValues.length > 0 ? excludeXattrValues : undefined,
|
||||
targetPath,
|
||||
overwrite: overwriteMode,
|
||||
},
|
||||
|
|
@ -142,9 +167,11 @@ export function RestoreForm({ repository, snapshotId, returnPath, basePath }: Re
|
|||
repository.shortId,
|
||||
snapshotId,
|
||||
excludeXattr,
|
||||
hasCustomTargetPath,
|
||||
restoreLocation,
|
||||
customTargetPath,
|
||||
trimmedCustomTargetPath,
|
||||
selectedPaths,
|
||||
selectedPathKind,
|
||||
overwriteMode,
|
||||
restoreSnapshot,
|
||||
]);
|
||||
|
|
@ -179,13 +206,15 @@ export function RestoreForm({ repository, snapshotId, returnPath, basePath }: Re
|
|||
}
|
||||
}, []);
|
||||
|
||||
const canRestore = restoreLocation === "original" || customTargetPath.trim();
|
||||
const canDownload = selectedPaths.size <= 1;
|
||||
const canRestore = restoreRequiresCustomTarget
|
||||
? hasCustomTargetPath
|
||||
: restoreLocation === "original" || hasCustomTargetPath;
|
||||
const canDownload = selectedPathCount <= 1;
|
||||
const isRestoreRunning = isRestoring || isRestoreActive;
|
||||
|
||||
function getDownloadButtonText(): string {
|
||||
if (selectedPaths.size > 0) {
|
||||
return `Download ${selectedPaths.size} ${selectedPaths.size === 1 ? "item" : "items"}`;
|
||||
if (selectedPathCount > 0) {
|
||||
return `Download ${selectedPathCount} ${selectedPathCount === 1 ? "item" : "items"}`;
|
||||
}
|
||||
return "Download All";
|
||||
}
|
||||
|
|
@ -194,8 +223,8 @@ export function RestoreForm({ repository, snapshotId, returnPath, basePath }: Re
|
|||
if (isRestoreRunning) {
|
||||
return "Restoring...";
|
||||
}
|
||||
if (selectedPaths.size > 0) {
|
||||
return `Restore ${selectedPaths.size} ${selectedPaths.size === 1 ? "item" : "items"}`;
|
||||
if (selectedPathCount > 0) {
|
||||
return `Restore ${selectedPathCount} ${selectedPathCount === 1 ? "item" : "items"}`;
|
||||
}
|
||||
return "Restore All";
|
||||
}
|
||||
|
|
@ -237,6 +266,18 @@ export function RestoreForm({ repository, snapshotId, returnPath, basePath }: Re
|
|||
<div className="space-y-6">
|
||||
{isRestoreRunning && <RestoreProgress repositoryId={repository.shortId} snapshotId={snapshotId} />}
|
||||
|
||||
{restoreRequiresCustomTarget && (
|
||||
<Alert variant="warning">
|
||||
<AlertTriangle className="size-4" />
|
||||
<AlertTitle>Source paths do not match</AlertTitle>
|
||||
<AlertDescription>
|
||||
This snapshot was created from source paths that do not match this Zerobyte server or the current linked
|
||||
volume. Restoring to the original location is unavailable. Restore it to a custom location, or download
|
||||
it instead.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Restore Location</CardTitle>
|
||||
|
|
@ -250,6 +291,7 @@ export function RestoreForm({ repository, snapshotId, returnPath, basePath }: Re
|
|||
size="sm"
|
||||
className="flex justify-start gap-2"
|
||||
onClick={() => setRestoreLocation("original")}
|
||||
disabled={!!restoreRequiresCustomTarget}
|
||||
>
|
||||
<RotateCcw size={16} className="mr-1" />
|
||||
Original location
|
||||
|
|
@ -344,7 +386,8 @@ export function RestoreForm({ repository, snapshotId, returnPath, basePath }: Re
|
|||
<SnapshotTreeBrowser
|
||||
repositoryId={repository.shortId}
|
||||
snapshotId={snapshotId}
|
||||
basePath={volumeBasePath}
|
||||
queryBasePath={snapshotBasePath}
|
||||
displayBasePath={displayBasePath}
|
||||
pageSize={500}
|
||||
className="flex flex-1 min-h-0 flex-col"
|
||||
treeContainerClassName="overflow-auto flex-1 min-h-0 border border-border rounded-md bg-card m-4"
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import { ByteSize } from "~/client/components/bytes-size";
|
||||
import { useFormatBytes } from "~/client/hooks/use-format-bytes";
|
||||
import { useRootLoaderData } from "~/client/hooks/use-root-loader-data";
|
||||
import { Card } from "~/client/components/ui/card";
|
||||
import { Progress } from "~/client/components/ui/progress";
|
||||
import { type RestoreProgressEvent, useServerEvents } from "~/client/hooks/use-server-events";
|
||||
import { formatBytes } from "~/utils/format-bytes";
|
||||
import { formatDuration } from "~/utils/utils";
|
||||
|
||||
type Props = {
|
||||
|
|
@ -12,6 +13,8 @@ type Props = {
|
|||
};
|
||||
|
||||
export const RestoreProgress = ({ repositoryId, snapshotId }: Props) => {
|
||||
const formatBytes = useFormatBytes();
|
||||
const { locale } = useRootLoaderData();
|
||||
const { addEventListener } = useServerEvents();
|
||||
const [progress, setProgress] = useState<RestoreProgressEvent | null>(null);
|
||||
|
||||
|
|
@ -71,9 +74,9 @@ export const RestoreProgress = ({ repositoryId, snapshotId }: Props) => {
|
|||
<div>
|
||||
<p className="text-xs uppercase text-muted-foreground">Files</p>
|
||||
<p className="font-medium">
|
||||
{progress.files_restored.toLocaleString()}
|
||||
{progress.files_restored.toLocaleString(locale)}
|
||||
/
|
||||
{progress.total_files.toLocaleString()}
|
||||
{progress.total_files.toLocaleString(locale)}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
|
|
|
|||
|
|
@ -25,8 +25,8 @@ import {
|
|||
DialogTitle,
|
||||
} from "~/client/components/ui/dialog";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "~/client/components/ui/select";
|
||||
import { useTimeFormat } from "~/client/lib/datetime";
|
||||
import { formatDuration } from "~/utils/utils";
|
||||
import { formatDateTime } from "~/client/lib/datetime";
|
||||
import {
|
||||
deleteSnapshotsMutation,
|
||||
listSnapshotsQueryKey,
|
||||
|
|
@ -49,6 +49,7 @@ type Props = {
|
|||
export const SnapshotsTable = ({ snapshots, repositoryId, backups, listSnapshotsQueryOptions }: Props) => {
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const { formatDateTime } = useTimeFormat();
|
||||
|
||||
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
|
||||
const [showBulkDeleteConfirm, setShowBulkDeleteConfirm] = useState(false);
|
||||
|
|
|
|||
|
|
@ -12,8 +12,8 @@ interface StatusDotProps {
|
|||
export const StatusDot = ({ variant, label, animated }: StatusDotProps) => {
|
||||
const statusMapping = {
|
||||
success: {
|
||||
color: "bg-emerald-500 shadow-[0_0_8px_rgba(16,185,129,0.5)]",
|
||||
colorLight: "bg-emerald-400",
|
||||
color: "bg-success shadow-[0_0_8px_rgba(16,185,129,0.5)]",
|
||||
colorLight: "bg-success/60",
|
||||
animated: animated ?? true,
|
||||
},
|
||||
neutral: {
|
||||
|
|
@ -40,7 +40,7 @@ export const StatusDot = ({ variant, label, animated }: StatusDotProps) => {
|
|||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<TooltipTrigger asChild aria-label={label}>
|
||||
<span className="relative flex size-3 mx-auto">
|
||||
{statusMapping?.animated && (
|
||||
<span
|
||||
|
|
@ -54,7 +54,7 @@ export const StatusDot = ({ variant, label, animated }: StatusDotProps) => {
|
|||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{label}</p>
|
||||
<p className="capitalize">{label}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
|
|
|
|||
35
app/client/components/theme-provider.tsx
Normal file
35
app/client/components/theme-provider.tsx
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import { createContext, useCallback, useContext, useState } from "react";
|
||||
|
||||
type Theme = "light" | "dark";
|
||||
|
||||
type ThemeContextValue = {
|
||||
theme: Theme;
|
||||
setTheme: (theme: Theme) => void;
|
||||
};
|
||||
|
||||
const ThemeContext = createContext<ThemeContextValue | null>(null);
|
||||
|
||||
export const THEME_COOKIE_NAME = "theme";
|
||||
const THEME_COOKIE_MAX_AGE = 60 * 60 * 24 * 365; // 1 year
|
||||
const DEFAULT_THEME: Theme = "dark";
|
||||
|
||||
export function ThemeProvider({ children, initialTheme }: { children: React.ReactNode; initialTheme?: Theme }) {
|
||||
const [theme, setThemeState] = useState<Theme>(initialTheme ?? DEFAULT_THEME);
|
||||
|
||||
const setTheme = useCallback((newTheme: Theme) => {
|
||||
setThemeState(newTheme);
|
||||
document.cookie = `${THEME_COOKIE_NAME}=${newTheme}; path=/; max-age=${THEME_COOKIE_MAX_AGE}`;
|
||||
document.documentElement.classList.toggle("dark", newTheme === "dark");
|
||||
document.documentElement.style.colorScheme = newTheme;
|
||||
}, []);
|
||||
|
||||
return <ThemeContext value={{ theme, setTheme }}>{children}</ThemeContext>;
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
const context = useContext(ThemeContext);
|
||||
if (!context) {
|
||||
throw new Error("useTheme must be used within a ThemeProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
26
app/client/components/theme-toggle.tsx
Normal file
26
app/client/components/theme-toggle.tsx
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import { Moon, Sun } from "lucide-react";
|
||||
import { useTheme } from "./theme-provider";
|
||||
import { Button } from "./ui/button";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";
|
||||
|
||||
export function ThemeToggle() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="relative rounded-full h-7 w-7 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
|
||||
aria-label="Toggle theme"
|
||||
>
|
||||
<Sun className="h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
|
||||
<Moon className="absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Toggle theme</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
12
app/client/components/time-ago.tsx
Normal file
12
app/client/components/time-ago.tsx
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { useTimeFormat, type DateInput } from "~/client/lib/datetime";
|
||||
|
||||
type Props = {
|
||||
date: DateInput;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export function TimeAgo({ date, className }: Props) {
|
||||
const { formatTimeAgo } = useTimeFormat();
|
||||
|
||||
return <span className={className}>{formatTimeAgo(date)}</span>;
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
// fallow-ignore-file unused-export
|
||||
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
|
||||
import type * as React from "react";
|
||||
import { buttonVariants } from "~/client/components/ui/button";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// fallow-ignore-file unused-export
|
||||
import type * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// fallow-ignore-file unused-export
|
||||
import type * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { ChevronRight, MoreHorizontal } from "lucide-react";
|
||||
|
|
@ -12,17 +13,16 @@ function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
|
|||
return (
|
||||
<ol
|
||||
data-slot="breadcrumb-list"
|
||||
className={cn(
|
||||
"text-muted-foreground flex items-center gap-1.5 text-sm sm:gap-2.5 min-w-0",
|
||||
className,
|
||||
)}
|
||||
className={cn("text-muted-foreground flex items-center gap-1.5 text-sm sm:gap-2.5 min-w-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return <li data-slot="breadcrumb-item" className={cn("inline-flex items-center gap-1.5 min-w-0", className)} {...props} />;
|
||||
return (
|
||||
<li data-slot="breadcrumb-item" className={cn("inline-flex items-center gap-1.5 min-w-0", className)} {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
function BreadcrumbLink({
|
||||
|
|
|
|||
|
|
@ -11,13 +11,12 @@ const buttonVariants = cva(
|
|||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-transparent text-white hover:bg-[#3A3A3A]/80 border hover:border-white/40 dark:text-white dark:hover:bg-[#3A3A3A]/80",
|
||||
default: "bg-transparent text-foreground hover:bg-muted border hover:border-border",
|
||||
primary: "bg-strong-accent text-white hover:bg-strong-accent/90 focus-visible:ring-strong-accent/50",
|
||||
destructive:
|
||||
"border border-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/50 text-destructive hover:text-white",
|
||||
"border border-destructive text-destructive hover:bg-destructive hover:text-destructive-foreground focus-visible:ring-destructive/50",
|
||||
outline: "border border-border bg-background hover:bg-accent hover:text-accent-foreground",
|
||||
secondary: "bg-transparent text-white hover:bg-[#3A3A3A]/80 border dark:text-white dark:hover:bg-[#3A3A3A]/80",
|
||||
secondary: "bg-transparent text-foreground hover:bg-muted border",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// fallow-ignore-file unused-export
|
||||
import type * as React from "react";
|
||||
|
||||
import { cn } from "~/client/lib/utils";
|
||||
|
|
@ -7,7 +8,7 @@ function Card({ className, children, interactive, ...props }: React.ComponentPro
|
|||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"bg-card text-card-foreground group relative flex flex-col gap-6 border border-border py-6 shadow-[inset_0_0_0_1px_rgba(255,255,255,0.02)] transition-colors duration-300 ",
|
||||
"bg-card text-card-foreground group relative flex flex-col gap-6 border border-border py-6 shadow-[0_8px_30px_-15px_rgba(0,0,0,0.04)] dark:shadow-[inset_0_0_0_1px_rgba(255,255,255,0.02)] transition-colors duration-300 ",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
|
@ -21,14 +22,14 @@ function Card({ className, children, interactive, ...props }: React.ComponentPro
|
|||
},
|
||||
)}
|
||||
>
|
||||
<span className="absolute -left-0.5 -top-0.5 h-0.5 w-4 bg-white/80" />
|
||||
<span className="absolute -left-0.5 -top-0.5 h-4 w-0.5 bg-white/80" />
|
||||
<span className="absolute -right-0.5 -top-0.5 h-0.5 w-4 bg-white/80" />
|
||||
<span className="absolute -right-0.5 -top-0.5 h-4 w-0.5 bg-white/80" />
|
||||
<span className="absolute -left-0.5 -bottom-0.5 h-0.5 w-4 bg-white/80" />
|
||||
<span className="absolute -left-0.5 -bottom-0.5 h-4 w-0.5 bg-white/80" />
|
||||
<span className="absolute -right-0.5 -bottom-0.5 h-0.5 w-4 bg-white/80" />
|
||||
<span className="absolute -right-0.5 -bottom-0.5 h-4 w-0.5 bg-white/80" />
|
||||
<span className="absolute -left-0.5 -top-0.5 h-0.5 w-4 bg-foreground" />
|
||||
<span className="absolute -left-0.5 -top-0.5 h-4 w-0.5 bg-foreground" />
|
||||
<span className="absolute -right-0.5 -top-0.5 h-0.5 w-4 bg-foreground" />
|
||||
<span className="absolute -right-0.5 -top-0.5 h-4 w-0.5 bg-foreground" />
|
||||
<span className="absolute -left-0.5 -bottom-0.5 h-0.5 w-4 bg-foreground" />
|
||||
<span className="absolute -left-0.5 -bottom-0.5 h-4 w-0.5 bg-foreground" />
|
||||
<span className="absolute -right-0.5 -bottom-0.5 h-0.5 w-4 bg-foreground" />
|
||||
<span className="absolute -right-0.5 -bottom-0.5 h-4 w-0.5 bg-foreground" />
|
||||
</span>
|
||||
{children}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,13 +1,16 @@
|
|||
// fallow-ignore-file unused-export
|
||||
// @ts-nocheck
|
||||
// biome-ignore-all lint: reason
|
||||
import * as React from "react";
|
||||
import * as RechartsPrimitive from "recharts";
|
||||
|
||||
import { useRootLoaderData } from "~/client/hooks/use-root-loader-data";
|
||||
import { cn } from "~/client/lib/utils";
|
||||
|
||||
// Format: { THEME_NAME: CSS_SELECTOR }
|
||||
const THEMES = { light: "", dark: ".dark" } as const;
|
||||
|
||||
// fallow-ignore-next-line unused-type
|
||||
export type ChartConfig = {
|
||||
[k in string]: {
|
||||
label?: React.ReactNode;
|
||||
|
|
@ -116,6 +119,7 @@ function ChartTooltipContent({
|
|||
labelKey?: string;
|
||||
}) {
|
||||
const { config } = useChart();
|
||||
const { locale } = useRootLoaderData();
|
||||
|
||||
const tooltipLabel = React.useMemo(() => {
|
||||
if (hideLabel || !payload?.length) {
|
||||
|
|
@ -205,7 +209,7 @@ function ChartTooltipContent({
|
|||
</div>
|
||||
{item.value && (
|
||||
<span className="text-foreground font-mono font-medium tabular-nums">
|
||||
{item.value.toLocaleString()}
|
||||
{item.value.toLocaleString(locale)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@ interface CodeBlockProps {
|
|||
|
||||
export const CodeBlock: React.FC<CodeBlockProps> = ({ code, filename }) => {
|
||||
return (
|
||||
<div className="overflow-hidden rounded-sm bg-card-header ring-1 ring-white/10">
|
||||
<div className="flex items-center justify-between border-b border-white/10 px-4 py-2 text-xs">
|
||||
<div className="overflow-hidden rounded-sm bg-card-header ring-1 ring-border">
|
||||
<div className="flex items-center justify-between border-b border-border px-4 py-2 text-xs">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="h-2.5 w-2.5 rounded-full bg-rose-500" />
|
||||
<span className="h-2.5 w-2.5 rounded-full bg-amber-500" />
|
||||
|
|
@ -18,7 +18,7 @@ export const CodeBlock: React.FC<CodeBlockProps> = ({ code, filename }) => {
|
|||
</div>
|
||||
</div>
|
||||
<pre className="text-xs m-0 px-4 py-2 bg-card-header">
|
||||
<code className="text-white/80 select-all">{code}</code>
|
||||
<code className="text-foreground/80 select-all">{code}</code>
|
||||
</pre>
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// fallow-ignore-file unused-export
|
||||
import type * as React from "react";
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
||||
import { XIcon } from "lucide-react";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// fallow-ignore-file unused-export
|
||||
import * as React from "react";
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// fallow-ignore-file unused-export
|
||||
import * as React from "react";
|
||||
import type * as LabelPrimitive from "@radix-ui/react-label";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import * as React from "react";
|
||||
import { OTPInput, OTPInputContext } from "input-otp";
|
||||
import { MinusIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "~/client/lib/utils";
|
||||
|
||||
|
|
@ -55,12 +54,8 @@ function InputOTPSlot({
|
|||
);
|
||||
}
|
||||
|
||||
function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div data-slot="input-otp-separator" role="separator" {...props}>
|
||||
<MinusIcon />
|
||||
</div>
|
||||
);
|
||||
function InputOTPSeparator({ ...props }: React.ComponentProps<"hr">) {
|
||||
return <hr data-slot="input-otp-separator" {...props} />;
|
||||
}
|
||||
|
||||
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator };
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// fallow-ignore-file unused-export
|
||||
import type * as React from "react";
|
||||
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// fallow-ignore-file unused-export
|
||||
import { Eye, EyeOff } from "lucide-react";
|
||||
import type * as React from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
|
|
@ -14,7 +15,7 @@ export const isStoredSecretValue = (value?: string): boolean => {
|
|||
return value.startsWith("env://") || value.startsWith("file://") || value.startsWith("encv1:");
|
||||
};
|
||||
|
||||
type SecretInputProps = Omit<React.ComponentProps<typeof Input>, "type">
|
||||
type SecretInputProps = Omit<React.ComponentProps<typeof Input>, "type">;
|
||||
|
||||
export const SecretInput = ({ className, value, ...props }: SecretInputProps) => {
|
||||
const [revealed, setRevealed] = useState(false);
|
||||
|
|
@ -36,12 +37,7 @@ export const SecretInput = ({ className, value, ...props }: SecretInputProps) =>
|
|||
|
||||
return (
|
||||
<div className="relative" data-secret-input>
|
||||
<Input
|
||||
{...props}
|
||||
value={value}
|
||||
type={type}
|
||||
className={cn(!showAsPlaintext && "pr-10", className)}
|
||||
/>
|
||||
<Input {...props} value={value} type={type} className={cn(!showAsPlaintext && "pr-10", className)} />
|
||||
{!showAsPlaintext && (
|
||||
<Button
|
||||
type="button"
|
||||
|
|
|
|||
|
|
@ -1,19 +1,73 @@
|
|||
import type * as React from "react";
|
||||
// fallow-ignore-file unused-export
|
||||
import * as React from "react";
|
||||
import * as SelectPrimitive from "@radix-ui/react-select";
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "~/client/lib/utils";
|
||||
|
||||
function Select({ ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />;
|
||||
const SelectSsrValueContext = React.createContext<{
|
||||
hydrated: boolean;
|
||||
items: Map<string, React.ReactNode>;
|
||||
value: string | undefined;
|
||||
} | null>(null);
|
||||
|
||||
function collectSelectItems(children: React.ReactNode, items = new Map<string, React.ReactNode>()) {
|
||||
for (const child of React.Children.toArray(children)) {
|
||||
if (!React.isValidElement<{ children?: React.ReactNode; value?: string }>(child)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((child.type === SelectItem || child.type === SelectPrimitive.Item) && typeof child.props.value === "string") {
|
||||
items.set(child.props.value, child.props.children);
|
||||
}
|
||||
|
||||
if (child.props.children) {
|
||||
collectSelectItems(child.props.children, items);
|
||||
}
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
function Select({ children, value, ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
const [hydrated, setHydrated] = React.useState(false);
|
||||
const items = collectSelectItems(children);
|
||||
|
||||
React.useEffect(() => {
|
||||
setHydrated(true);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<SelectSsrValueContext.Provider value={{ hydrated, items, value }}>
|
||||
<SelectPrimitive.Root data-slot="select" value={value} {...props}>
|
||||
{children}
|
||||
</SelectPrimitive.Root>
|
||||
</SelectSsrValueContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectGroup({ ...props }: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
|
||||
}
|
||||
|
||||
function SelectValue({ ...props }: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
|
||||
function SelectValue({ children, placeholder, style, ...props }: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
const context = React.useContext(SelectSsrValueContext);
|
||||
const selectedItem =
|
||||
context?.value !== undefined && context.value !== "" ? context.items.get(context.value) : undefined;
|
||||
|
||||
if (!context?.hydrated) {
|
||||
return (
|
||||
<span data-slot="select-value" {...props} style={{ pointerEvents: "none", ...style }}>
|
||||
{children ?? selectedItem ?? placeholder}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SelectPrimitive.Value data-slot="select-value" placeholder={placeholder} style={style} {...props}>
|
||||
{children}
|
||||
</SelectPrimitive.Value>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
|
|
@ -21,19 +75,35 @@ function SelectTrigger({
|
|||
size = "default",
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
}: React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default";
|
||||
}) {
|
||||
const context = React.useContext(SelectSsrValueContext);
|
||||
const hasValue = context?.value !== undefined && context.value !== "";
|
||||
const triggerClassName = cn(
|
||||
"border-input data-placeholder:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&+select[aria-hidden=true]]:hidden [&:has(+select[aria-hidden=true]:last-child)]:mb-0",
|
||||
className,
|
||||
);
|
||||
|
||||
if (!context?.hydrated) {
|
||||
return (
|
||||
<div
|
||||
id={props.id}
|
||||
aria-disabled="true"
|
||||
aria-invalid={props["aria-invalid"]}
|
||||
data-placeholder={hasValue ? undefined : ""}
|
||||
data-size={size}
|
||||
data-slot="select-trigger"
|
||||
className={triggerClassName}
|
||||
>
|
||||
{children}
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"border-input data-placeholder:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SelectPrimitive.Trigger data-slot="select-trigger" data-size={size} className={triggerClassName} {...props}>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// fallow-ignore-file unused-export
|
||||
"use client";
|
||||
|
||||
import type * as React from "react";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// fallow-ignore-file unused-export
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
|
@ -565,10 +566,16 @@ function SidebarMenuSkeleton({
|
|||
}: React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean;
|
||||
}) {
|
||||
// Random width between 50 to 90%.
|
||||
const skeletonId = React.useId();
|
||||
const width = React.useMemo(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`;
|
||||
}, []);
|
||||
let hash = 0;
|
||||
|
||||
for (const char of skeletonId) {
|
||||
hash = (hash * 31 + char.charCodeAt(0)) % 40;
|
||||
}
|
||||
|
||||
return `${hash + 50}%`;
|
||||
}, [skeletonId]);
|
||||
|
||||
return (
|
||||
<div
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import { useTheme } from "next-themes";
|
||||
import { useTheme } from "~/client/components/theme-provider";
|
||||
import { Toaster as Sonner, type ToasterProps } from "sonner";
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "dark" } = useTheme();
|
||||
const { theme } = useTheme();
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// fallow-ignore-file unused-export
|
||||
import type * as React from "react";
|
||||
|
||||
import { cn } from "~/client/lib/utils";
|
||||
|
|
|
|||
|
|
@ -37,11 +37,11 @@ function TabsTrigger({ className, onClick, ...props }: React.ComponentProps<type
|
|||
// Padding: 20px horizontal (8px for bracket tick + 12px gap to text)
|
||||
"px-5",
|
||||
// Transparent orange background for active state
|
||||
"data-[state=active]:bg-[#FF453A]/10",
|
||||
"data-[state=active]:bg-strong-accent/10",
|
||||
// Left bracket - vertical line
|
||||
"before:absolute before:left-0 before:top-0 before:h-7 before:w-0.5 before:bg-[#5D6570] before:transition-colors data-[state=active]:before:bg-[#FF453A]",
|
||||
"before:absolute before:left-0 before:top-0 before:h-7 before:w-0.5 before:bg-muted-foreground/60 before:transition-colors data-[state=active]:before:bg-strong-accent",
|
||||
// Left bracket - top tick
|
||||
"after:absolute after:left-0 after:-top-px after:w-2 after:h-0.5 after:bg-[#5D6570] after:transition-colors data-[state=active]:after:bg-[#FF453A]",
|
||||
"after:absolute after:left-0 after:-top-px after:w-2 after:h-0.5 after:bg-muted-foreground/60 after:transition-colors data-[state=active]:after:bg-strong-accent",
|
||||
className,
|
||||
)}
|
||||
onClick={handleClick}
|
||||
|
|
@ -49,13 +49,13 @@ function TabsTrigger({ className, onClick, ...props }: React.ComponentProps<type
|
|||
>
|
||||
<span className="relative z-10">{props.children}</span>
|
||||
{/* Left bracket - bottom tick */}
|
||||
<span className="absolute left-0 bottom-[-1px] h-0.5 w-2 bg-[#5D6570] transition-colors group-data-[state=active]:bg-[#FF453A]" />
|
||||
<span className="absolute left-0 bottom-[-1px] h-0.5 w-2 bg-muted-foreground/60 transition-colors group-data-[state=active]:bg-strong-accent" />
|
||||
{/* Right bracket - top tick */}
|
||||
<span className="absolute right-0 top-[-1px] h-0.5 w-2 bg-[#5D6570] transition-colors group-data-[state=active]:bg-[#FF453A]" />
|
||||
<span className="absolute right-0 top-[-1px] h-0.5 w-2 bg-muted-foreground/60 transition-colors group-data-[state=active]:bg-strong-accent" />
|
||||
{/* Right bracket - vertical line */}
|
||||
<span className="absolute right-0 top-0 h-7 w-0.5 bg-[#5D6570] transition-colors group-data-[state=active]:bg-[#FF453A]" />
|
||||
<span className="absolute right-0 top-0 h-7 w-0.5 bg-muted-foreground/60 transition-colors group-data-[state=active]:bg-strong-accent" />
|
||||
{/* Right bracket - bottom tick */}
|
||||
<span className="absolute right-0 bottom-[-1px] h-0.5 w-2 bg-[#5D6570] transition-colors group-data-[state=active]:bg-[#FF453A]" />
|
||||
<span className="absolute right-0 bottom-[-1px] h-0.5 w-2 bg-muted-foreground/60 transition-colors group-data-[state=active]:bg-strong-accent" />
|
||||
</TabsPrimitive.Trigger>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { Cloud, Folder, Server } from "lucide-react";
|
||||
import type { BackendType } from "~/schemas/volumes";
|
||||
import type { BackendType } from "@zerobyte/contracts/volumes";
|
||||
|
||||
type VolumeIconProps = {
|
||||
backend: BackendType;
|
||||
|
|
|
|||
25
app/client/components/webhook-request-preview.tsx
Normal file
25
app/client/components/webhook-request-preview.tsx
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { CodeBlock } from "~/client/components/ui/code-block";
|
||||
import { Label } from "~/client/components/ui/label";
|
||||
|
||||
type WebhookRequestPreviewProps = {
|
||||
method: string;
|
||||
url?: string;
|
||||
contentType?: string;
|
||||
headers?: string[];
|
||||
body: string;
|
||||
};
|
||||
|
||||
export const WebhookRequestPreview = ({ method, url, contentType, headers, body }: WebhookRequestPreviewProps) => {
|
||||
const headerLines = [contentType ? `Content-Type: ${contentType}` : undefined, ...(headers ?? [])].filter(Boolean);
|
||||
const previewCode = `${method} ${url || "https://api.example.com/webhook"}${headerLines.length > 0 ? `\n${headerLines.join("\n")}` : ""}
|
||||
|
||||
${body}`;
|
||||
|
||||
return (
|
||||
<div className="space-y-2 pt-4 border-t">
|
||||
<Label>Request Preview</Label>
|
||||
<CodeBlock code={previewCode} filename="HTTP Request" />
|
||||
<p className="text-[0.8rem] text-muted-foreground">This is a preview of the HTTP request that will be sent.</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
36
app/client/functions/__tests__/is-secure-context.test.ts
Normal file
36
app/client/functions/__tests__/is-secure-context.test.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import { describe, expect, test } from "vitest";
|
||||
import { getIsSecureContextForRequest, isSecureContextOrigin } from "../is-secure-context";
|
||||
|
||||
describe("isSecureContextOrigin", () => {
|
||||
test("treats HTTPS and loopback HTTP origins as secure contexts", () => {
|
||||
expect(isSecureContextOrigin("https://example.com")).toBe(true);
|
||||
expect(isSecureContextOrigin("http://localhost:3000")).toBe(true);
|
||||
expect(isSecureContextOrigin("http://app.localhost")).toBe(true);
|
||||
expect(isSecureContextOrigin("http://127.0.0.1:3000")).toBe(true);
|
||||
expect(isSecureContextOrigin("http://[::1]:3000")).toBe(true);
|
||||
});
|
||||
|
||||
test("treats non-local HTTP origins as insecure contexts", () => {
|
||||
expect(isSecureContextOrigin("http://example.com")).toBe(false);
|
||||
expect(isSecureContextOrigin("http://127.example.com")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getIsSecureContextForRequest", () => {
|
||||
test("uses forwarded protocol and host when present", () => {
|
||||
const request = new Request("http://internal.local/settings", {
|
||||
headers: {
|
||||
host: "internal.local",
|
||||
"x-forwarded-host": "zerobyte.example.com",
|
||||
"x-forwarded-proto": "https",
|
||||
},
|
||||
});
|
||||
|
||||
expect(getIsSecureContextForRequest(request)).toBe(true);
|
||||
});
|
||||
|
||||
test("uses the request URL when forwarded headers are absent", () => {
|
||||
expect(getIsSecureContextForRequest(new Request("http://zerobyte.example.com/settings"))).toBe(false);
|
||||
expect(getIsSecureContextForRequest(new Request("https://zerobyte.example.com/settings"))).toBe(true);
|
||||
});
|
||||
});
|
||||
51
app/client/functions/is-secure-context.ts
Normal file
51
app/client/functions/is-secure-context.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { createIsomorphicFn } from "@tanstack/react-start";
|
||||
import { getRequest } from "@tanstack/react-start/server";
|
||||
import ipaddr from "ipaddr.js";
|
||||
|
||||
const getFirstHeaderValue = (value: string | null) => value?.split(",")[0]?.trim();
|
||||
|
||||
const isLoopbackIp = (hostname: string) => {
|
||||
try {
|
||||
return ipaddr.parse(hostname).range() === "loopback";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const getRequestOrigin = (request: Request) => {
|
||||
const requestUrl = new URL(request.url);
|
||||
const forwardedProto = getFirstHeaderValue(request.headers.get("x-forwarded-proto"));
|
||||
const forwardedHost = getFirstHeaderValue(request.headers.get("x-forwarded-host"));
|
||||
const host = forwardedHost || getFirstHeaderValue(request.headers.get("host"));
|
||||
|
||||
if (!host) {
|
||||
return requestUrl.origin;
|
||||
}
|
||||
|
||||
const protocol = (forwardedProto || requestUrl.protocol).replace(/:$/, "");
|
||||
return `${protocol}://${host}`;
|
||||
};
|
||||
|
||||
export const isSecureContextOrigin = (origin: string) => {
|
||||
const url = new URL(origin);
|
||||
|
||||
if (url.protocol === "https:") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const hostname = url.hostname.replace(/^\[(.*)\]$/, "$1").toLowerCase();
|
||||
|
||||
return hostname === "localhost" || hostname.endsWith(".localhost") || isLoopbackIp(hostname);
|
||||
};
|
||||
|
||||
export const getIsSecureContextForRequest = (request: Request) => isSecureContextOrigin(getRequestOrigin(request));
|
||||
|
||||
export const getIsSecureContext = createIsomorphicFn()
|
||||
.server(() => {
|
||||
try {
|
||||
return getIsSecureContextForRequest(getRequest());
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
})
|
||||
.client(() => window.isSecureContext ?? true);
|
||||
141
app/client/hooks/__tests__/use-server-events.test.tsx
Normal file
141
app/client/hooks/__tests__/use-server-events.test.tsx
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { cleanup, createTestQueryClient, render, screen } from "~/test/test-utils";
|
||||
import { useServerEvents } from "../use-server-events";
|
||||
|
||||
class MockEventSource {
|
||||
static instances: MockEventSource[] = [];
|
||||
|
||||
public onerror: ((event: Event) => void) | null = null;
|
||||
public close = vi.fn(() => {});
|
||||
private listeners = new Map<string, Set<(event: Event) => void>>();
|
||||
|
||||
constructor(public url: string) {
|
||||
MockEventSource.instances.push(this);
|
||||
}
|
||||
|
||||
addEventListener(type: string, listener: EventListenerOrEventListenerObject) {
|
||||
const listeners = this.listeners.get(type) ?? new Set<(event: Event) => void>();
|
||||
const callback = typeof listener === "function" ? listener : (event: Event) => listener.handleEvent(event);
|
||||
listeners.add(callback);
|
||||
this.listeners.set(type, listeners);
|
||||
}
|
||||
|
||||
emit(type: string, data: unknown) {
|
||||
const event = new MessageEvent(type, {
|
||||
data: JSON.stringify(data),
|
||||
});
|
||||
for (const listener of this.listeners.get(type) ?? []) {
|
||||
listener(event);
|
||||
}
|
||||
}
|
||||
|
||||
static reset() {
|
||||
MockEventSource.instances = [];
|
||||
}
|
||||
}
|
||||
|
||||
const originalEventSource = globalThis.EventSource;
|
||||
const originalConsoleInfo = console.info;
|
||||
const originalConsoleError = console.error;
|
||||
|
||||
const ConnectionConsumer = ({ enabled = true }: { enabled?: boolean }) => {
|
||||
useServerEvents({ enabled });
|
||||
return null;
|
||||
};
|
||||
|
||||
const BackupCompletedListener = ({ scheduleId }: { scheduleId: string }) => {
|
||||
const { addEventListener } = useServerEvents();
|
||||
const [status, setStatus] = useState("pending");
|
||||
|
||||
useEffect(() => {
|
||||
const abortController = new AbortController();
|
||||
|
||||
addEventListener(
|
||||
"backup:completed",
|
||||
(event) => {
|
||||
if (event.scheduleId === scheduleId) {
|
||||
setStatus(event.status);
|
||||
}
|
||||
},
|
||||
{ signal: abortController.signal },
|
||||
);
|
||||
|
||||
return () => abortController.abort();
|
||||
}, [addEventListener, scheduleId]);
|
||||
|
||||
return <div>{status}</div>;
|
||||
};
|
||||
|
||||
const QueryStatusConsumer = ({ getValue }: { getValue: () => string }) => {
|
||||
const { data } = useQuery({
|
||||
queryKey: ["backup-status"],
|
||||
queryFn: async () => getValue(),
|
||||
});
|
||||
|
||||
return <div>{data}</div>;
|
||||
};
|
||||
|
||||
describe("useServerEvents", () => {
|
||||
beforeEach(() => {
|
||||
MockEventSource.reset();
|
||||
globalThis.EventSource = MockEventSource as unknown as typeof EventSource;
|
||||
console.info = vi.fn(() => {});
|
||||
console.error = vi.fn(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
globalThis.EventSource = originalEventSource;
|
||||
console.info = originalConsoleInfo;
|
||||
console.error = originalConsoleError;
|
||||
MockEventSource.reset();
|
||||
});
|
||||
|
||||
test("shares one EventSource across consumers and refreshes active queries on backup completion", async () => {
|
||||
const queryClient = createTestQueryClient();
|
||||
let queryValue = "before";
|
||||
|
||||
const view = render(
|
||||
<>
|
||||
<ConnectionConsumer />
|
||||
<BackupCompletedListener scheduleId="0b9c940b" />
|
||||
<QueryStatusConsumer getValue={() => queryValue} />
|
||||
</>,
|
||||
{ queryClient },
|
||||
);
|
||||
|
||||
expect(MockEventSource.instances).toHaveLength(1);
|
||||
expect(await screen.findByText("before")).toBeTruthy();
|
||||
|
||||
queryValue = "after";
|
||||
|
||||
MockEventSource.instances[0]?.emit("backup:completed", {
|
||||
organizationId: "default-org",
|
||||
scheduleId: "0b9c940b",
|
||||
volumeName: "synology",
|
||||
repositoryName: "swiss-backup",
|
||||
status: "success",
|
||||
});
|
||||
|
||||
expect(await screen.findByText("success")).toBeTruthy();
|
||||
expect(await screen.findByText("after")).toBeTruthy();
|
||||
|
||||
view.unmount();
|
||||
|
||||
expect(MockEventSource.instances[0]?.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("waits to subscribe until enabled", () => {
|
||||
const queryClient = createTestQueryClient();
|
||||
const view = render(<ConnectionConsumer enabled={false} />, { queryClient });
|
||||
|
||||
expect(MockEventSource.instances).toHaveLength(0);
|
||||
|
||||
view.rerender(<ConnectionConsumer />);
|
||||
|
||||
expect(MockEventSource.instances).toHaveLength(1);
|
||||
expect(MockEventSource.instances[0]?.url).toBe("/api/v1/events");
|
||||
});
|
||||
});
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { logger } from "~/client/lib/logger";
|
||||
import type { FileEntry } from "../components/file-tree";
|
||||
|
||||
export type FetchFolderResult = {
|
||||
|
|
@ -44,7 +45,7 @@ export const useFileBrowser = (props: UseFileBrowserOptions) => {
|
|||
const stripPath = pathTransform?.strip;
|
||||
const addPath = pathTransform?.add;
|
||||
|
||||
useMemo(() => {
|
||||
useEffect(() => {
|
||||
if (initialData?.files) {
|
||||
const files = initialData.files;
|
||||
setAllFiles((prev) => {
|
||||
|
|
@ -135,7 +136,7 @@ export const useFileBrowser = (props: UseFileBrowserOptions) => {
|
|||
|
||||
setFetchedFolders((prev) => new Set(prev).add(folderPath));
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch folder contents:", error);
|
||||
logger.error("Failed to fetch folder contents:", error);
|
||||
} finally {
|
||||
setLoadingFolders((prev) => {
|
||||
const next = new Set(prev);
|
||||
|
|
@ -190,7 +191,7 @@ export const useFileBrowser = (props: UseFileBrowserOptions) => {
|
|||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to load more files:", error);
|
||||
logger.error("Failed to load more files:", error);
|
||||
setFolderPagination((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.set(folderPath, { ...pagination, isLoadingMore: false });
|
||||
|
|
|
|||
12
app/client/hooks/use-format-bytes.ts
Normal file
12
app/client/hooks/use-format-bytes.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { useRootLoaderData } from "~/client/hooks/use-root-loader-data";
|
||||
import { formatBytes, type FormatBytesOptions } from "~/utils/format-bytes";
|
||||
|
||||
export const useFormatBytes = () => {
|
||||
const { locale } = useRootLoaderData();
|
||||
|
||||
return (bytes: number, options?: FormatBytesOptions) =>
|
||||
formatBytes(bytes, {
|
||||
...options,
|
||||
locale: options?.locale ?? locale,
|
||||
});
|
||||
};
|
||||
3
app/client/hooks/use-root-loader-data.ts
Normal file
3
app/client/hooks/use-root-loader-data.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import { Route as RootRoute } from "~/routes/__root";
|
||||
|
||||
export const useRootLoaderData = () => RootRoute.useLoaderData();
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { type QueryClient, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { logger } from "~/client/lib/logger";
|
||||
import { serverEventNames, type ServerEventPayloadMap } from "~/schemas/server-events";
|
||||
|
||||
type LifecycleEventPayloadMap = {
|
||||
|
|
@ -16,118 +17,176 @@ type EventHandlerMap = {
|
|||
[K in ServerEventType]?: EventHandlerSet<K>;
|
||||
};
|
||||
|
||||
type SharedServerEventsState = {
|
||||
eventSource: EventSource | null;
|
||||
handlers: EventHandlerMap;
|
||||
queryClient: QueryClient | null;
|
||||
subscribers: number;
|
||||
};
|
||||
|
||||
const invalidatingEvents = new Set<ServerEventType>([
|
||||
"backup:completed",
|
||||
"volume:updated",
|
||||
"volume:status_changed",
|
||||
"notification:updated",
|
||||
"mirror:completed",
|
||||
"doctor:started",
|
||||
"doctor:completed",
|
||||
"doctor:cancelled",
|
||||
]);
|
||||
|
||||
export type RestoreEvent = ServerEventsPayloadMap["restore:started"] | ServerEventsPayloadMap["restore:completed"];
|
||||
export type RestoreProgressEvent = ServerEventsPayloadMap["restore:progress"];
|
||||
export type RestoreCompletedEvent = ServerEventsPayloadMap["restore:completed"];
|
||||
export type BackupProgressEvent = ServerEventsPayloadMap["backup:progress"];
|
||||
|
||||
const sharedState: SharedServerEventsState = {
|
||||
eventSource: null,
|
||||
handlers: {},
|
||||
queryClient: null,
|
||||
subscribers: 0,
|
||||
};
|
||||
|
||||
const parseEventData = <T extends ServerEventType>(event: Event): ServerEventsPayloadMap[T] =>
|
||||
JSON.parse((event as MessageEvent<string>).data) as ServerEventsPayloadMap[T];
|
||||
|
||||
const isAbortError = (error: unknown): error is Error => error instanceof Error && error.name === "AbortError";
|
||||
|
||||
const emit = <T extends ServerEventType>(eventName: T, data: ServerEventsPayloadMap[T]) => {
|
||||
const handlers = sharedState.handlers[eventName] as EventHandlerSet<T> | undefined;
|
||||
handlers?.forEach((handler) => {
|
||||
handler(data);
|
||||
});
|
||||
};
|
||||
|
||||
const refreshQueriesForEvent = (eventName: ServerEventType) => {
|
||||
if (!invalidatingEvents.has(eventName) || !sharedState.queryClient) {
|
||||
return;
|
||||
}
|
||||
|
||||
void sharedState.queryClient.invalidateQueries().catch((error) => {
|
||||
if (!isAbortError(error)) {
|
||||
logger.error(`[SSE] Failed to refresh queries after ${eventName}:`, error);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const connectEventSource = (queryClient: QueryClient) => {
|
||||
sharedState.queryClient = queryClient;
|
||||
if (sharedState.eventSource) {
|
||||
return;
|
||||
}
|
||||
|
||||
const eventSource = new EventSource("/api/v1/events");
|
||||
sharedState.eventSource = eventSource;
|
||||
|
||||
eventSource.addEventListener("connected", (event) => {
|
||||
const data = parseEventData<"connected">(event);
|
||||
logger.info("[SSE] Connected to server events");
|
||||
emit("connected", data);
|
||||
});
|
||||
|
||||
eventSource.addEventListener("heartbeat", (event) => {
|
||||
emit("heartbeat", parseEventData<"heartbeat">(event));
|
||||
});
|
||||
|
||||
for (const eventName of serverEventNames) {
|
||||
eventSource.addEventListener(eventName, (event) => {
|
||||
const data = parseEventData<typeof eventName>(event);
|
||||
logger.info(`[SSE] ${eventName}:`, data);
|
||||
|
||||
refreshQueriesForEvent(eventName);
|
||||
|
||||
if (eventName === "volume:status_changed") {
|
||||
const statusData = data as ServerEventsPayloadMap["volume:status_changed"];
|
||||
emit("volume:status_changed", statusData);
|
||||
emit("volume:updated", statusData);
|
||||
return;
|
||||
}
|
||||
|
||||
emit(eventName, data);
|
||||
});
|
||||
}
|
||||
|
||||
eventSource.onerror = (error) => {
|
||||
logger.error("[SSE] Connection error:", error);
|
||||
};
|
||||
};
|
||||
|
||||
const disconnectEventSource = () => {
|
||||
if (!sharedState.eventSource) {
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info("[SSE] Disconnecting from server events");
|
||||
sharedState.eventSource.close();
|
||||
sharedState.eventSource = null;
|
||||
sharedState.queryClient = null;
|
||||
sharedState.handlers = {};
|
||||
};
|
||||
|
||||
const addSharedEventListener = <T extends ServerEventType>(
|
||||
eventName: T,
|
||||
handler: EventHandler<T>,
|
||||
options?: { signal?: AbortSignal },
|
||||
) => {
|
||||
if (options?.signal?.aborted) {
|
||||
return () => {};
|
||||
}
|
||||
|
||||
const existingHandlers = sharedState.handlers[eventName] as EventHandlerSet<T> | undefined;
|
||||
const eventHandlers = existingHandlers ?? new Set<EventHandler<T>>();
|
||||
eventHandlers.add(handler);
|
||||
sharedState.handlers[eventName] = eventHandlers as EventHandlerMap[T];
|
||||
|
||||
const unsubscribe = () => {
|
||||
const handlers = sharedState.handlers[eventName] as EventHandlerSet<T> | undefined;
|
||||
handlers?.delete(handler);
|
||||
if (handlers && handlers.size === 0) {
|
||||
delete sharedState.handlers[eventName];
|
||||
}
|
||||
if (options?.signal) {
|
||||
options.signal.removeEventListener("abort", unsubscribe);
|
||||
}
|
||||
};
|
||||
|
||||
if (options?.signal) {
|
||||
options.signal.addEventListener("abort", unsubscribe, { once: true });
|
||||
}
|
||||
|
||||
return unsubscribe;
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook to listen to Server-Sent Events (SSE) from the backend
|
||||
* Automatically handles cache invalidation for backup and volume events
|
||||
*/
|
||||
export function useServerEvents() {
|
||||
export function useServerEvents({ enabled = true }: { enabled?: boolean } = {}) {
|
||||
const queryClient = useQueryClient();
|
||||
const eventSourceRef = useRef<EventSource | null>(null);
|
||||
const handlersRef = useRef<EventHandlerMap>({});
|
||||
const emit = useCallback(<T extends ServerEventType>(eventName: T, data: ServerEventsPayloadMap[T]) => {
|
||||
const handlers = handlersRef.current[eventName] as EventHandlerSet<T> | undefined;
|
||||
handlers?.forEach((handler) => {
|
||||
handler(data);
|
||||
});
|
||||
}, []);
|
||||
const addEventListener = useCallback(addSharedEventListener, []);
|
||||
const hasMountedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
const eventSource = new EventSource("/api/v1/events");
|
||||
eventSourceRef.current = eventSource;
|
||||
|
||||
eventSource.addEventListener("connected", (event) => {
|
||||
const data = parseEventData<"connected">(event);
|
||||
console.info("[SSE] Connected to server events");
|
||||
emit("connected", data);
|
||||
});
|
||||
|
||||
eventSource.addEventListener("heartbeat", (event) => {
|
||||
emit("heartbeat", parseEventData<"heartbeat">(event));
|
||||
});
|
||||
|
||||
for (const eventName of serverEventNames) {
|
||||
eventSource.addEventListener(eventName, (event) => {
|
||||
const data = parseEventData<typeof eventName>(event);
|
||||
console.info(`[SSE] ${eventName}:`, data);
|
||||
|
||||
if (invalidatingEvents.has(eventName)) {
|
||||
void queryClient.invalidateQueries();
|
||||
}
|
||||
|
||||
if (eventName === "backup:completed") {
|
||||
void queryClient.refetchQueries();
|
||||
}
|
||||
|
||||
if (eventName === "volume:status_changed") {
|
||||
const statusData = data as ServerEventsPayloadMap["volume:status_changed"];
|
||||
emit("volume:status_changed", statusData);
|
||||
emit("volume:updated", statusData);
|
||||
return;
|
||||
}
|
||||
|
||||
emit(eventName, data);
|
||||
});
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
eventSource.onerror = (error) => {
|
||||
console.error("[SSE] Connection error:", error);
|
||||
};
|
||||
connectEventSource(queryClient);
|
||||
if (!hasMountedRef.current) {
|
||||
sharedState.subscribers += 1;
|
||||
hasMountedRef.current = true;
|
||||
}
|
||||
|
||||
return () => {
|
||||
console.info("[SSE] Disconnecting from server events");
|
||||
eventSource.close();
|
||||
eventSourceRef.current = null;
|
||||
if (!hasMountedRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
hasMountedRef.current = false;
|
||||
sharedState.subscribers = Math.max(0, sharedState.subscribers - 1);
|
||||
if (sharedState.subscribers === 0) {
|
||||
disconnectEventSource();
|
||||
}
|
||||
};
|
||||
}, [emit, queryClient]);
|
||||
|
||||
const addEventListener = useCallback(
|
||||
<T extends ServerEventType>(eventName: T, handler: EventHandler<T>, options?: { signal?: AbortSignal }) => {
|
||||
if (options?.signal?.aborted) {
|
||||
return () => {};
|
||||
}
|
||||
|
||||
const existingHandlers = handlersRef.current[eventName] as EventHandlerSet<T> | undefined;
|
||||
const eventHandlers = existingHandlers ?? new Set<EventHandler<T>>();
|
||||
eventHandlers.add(handler);
|
||||
handlersRef.current[eventName] = eventHandlers as EventHandlerMap[T];
|
||||
|
||||
const unsubscribe = () => {
|
||||
const handlers = handlersRef.current[eventName] as EventHandlerSet<T> | undefined;
|
||||
handlers?.delete(handler);
|
||||
if (handlers && handlers.size === 0) {
|
||||
delete handlersRef.current[eventName];
|
||||
}
|
||||
if (options?.signal) {
|
||||
options.signal.removeEventListener("abort", unsubscribe);
|
||||
}
|
||||
};
|
||||
|
||||
if (options?.signal) {
|
||||
options.signal.addEventListener("abort", unsubscribe, { once: true });
|
||||
}
|
||||
|
||||
return unsubscribe;
|
||||
},
|
||||
[],
|
||||
);
|
||||
}, [enabled, queryClient]);
|
||||
|
||||
return { addEventListener };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,8 @@ export function useUpdates() {
|
|||
...getUpdatesOptions(),
|
||||
staleTime: 60 * 60 * 1000,
|
||||
gcTime: 24 * 60 * 60 * 1000,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnMount: "always",
|
||||
refetchOnWindowFocus: "always",
|
||||
});
|
||||
|
||||
return {
|
||||
|
|
|
|||
111
app/client/lib/__tests__/datetime.test.ts
Normal file
111
app/client/lib/__tests__/datetime.test.ts
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { DEFAULT_TIME_FORMAT, inferDateTimePreferences, rawFormatters } from "../datetime";
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
const {
|
||||
formatDate,
|
||||
formatDateTime,
|
||||
formatDateWithMonth,
|
||||
formatShortDate,
|
||||
formatShortDateTime,
|
||||
formatTime,
|
||||
formatTimeAgo,
|
||||
} = rawFormatters;
|
||||
|
||||
const sampleDate = new Date("2026-01-10T14:30:00.000Z");
|
||||
|
||||
describe("datetime formatters", () => {
|
||||
test.each([
|
||||
formatDateTime,
|
||||
formatDateWithMonth,
|
||||
formatDate,
|
||||
formatShortDate,
|
||||
formatShortDateTime,
|
||||
formatTime,
|
||||
formatTimeAgo,
|
||||
])("returns Never when no date is provided", (formatValue) => {
|
||||
expect(formatValue(null)).toBe("Never");
|
||||
});
|
||||
|
||||
test.each([
|
||||
formatDateTime,
|
||||
formatDateWithMonth,
|
||||
formatDate,
|
||||
formatShortDate,
|
||||
formatShortDateTime,
|
||||
formatTime,
|
||||
formatTimeAgo,
|
||||
])("returns Invalid Date when the input cannot be parsed", (formatValue) => {
|
||||
expect(formatValue("not-a-date")).toBe("Invalid Date");
|
||||
});
|
||||
|
||||
test("accepts Date, string, and timestamp inputs for calendar formatters", () => {
|
||||
const isoDate = sampleDate.toISOString();
|
||||
const timestamp = sampleDate.getTime();
|
||||
|
||||
expect(formatDateTime(isoDate)).toBe(formatDateTime(sampleDate));
|
||||
expect(formatDateTime(timestamp)).toBe(formatDateTime(sampleDate));
|
||||
expect(formatDateWithMonth(isoDate)).toBe(formatDateWithMonth(sampleDate));
|
||||
expect(formatDate(timestamp)).toBe(formatDate(sampleDate));
|
||||
expect(formatShortDate(isoDate)).toBe(formatShortDate(sampleDate));
|
||||
expect(formatShortDateTime(timestamp)).toBe(formatShortDateTime(sampleDate));
|
||||
expect(formatTime(isoDate)).toBe(formatTime(sampleDate));
|
||||
});
|
||||
|
||||
test("formats relative times without approximation prefixes", () => {
|
||||
const nowSpy = vi.spyOn(Date, "now").mockReturnValue(new Date("2026-01-10T14:35:00.000Z").getTime());
|
||||
|
||||
expect(formatTimeAgo(sampleDate)).toBe("5 minutes ago");
|
||||
|
||||
nowSpy.mockRestore();
|
||||
});
|
||||
|
||||
test("formats calendar values with an explicit locale and timezone", () => {
|
||||
expect(formatShortDateTime(sampleDate, { locale: "en-US", timeZone: "UTC" })).toBe("01/10, 2:30 PM");
|
||||
});
|
||||
|
||||
test.each([
|
||||
["MM/DD/YYYY", "01/10/2026"],
|
||||
["DD/MM/YYYY", "10/01/2026"],
|
||||
["YYYY/MM/DD", "2026/01/10"],
|
||||
] as const)("formats numeric dates with %s order", (dateFormat, expected) => {
|
||||
expect(formatDate(sampleDate, { locale: "en-US", timeZone: "UTC", dateFormat })).toBe(expected);
|
||||
});
|
||||
|
||||
test.each([
|
||||
["MM/DD/YYYY", "Jan 10, 2026"],
|
||||
["DD/MM/YYYY", "10 Jan 2026"],
|
||||
["YYYY/MM/DD", "2026 Jan 10"],
|
||||
] as const)("formats month dates with %s order", (dateFormat, expected) => {
|
||||
expect(formatDateWithMonth(sampleDate, { locale: "en-US", timeZone: "UTC", dateFormat })).toBe(expected);
|
||||
});
|
||||
|
||||
test.each([
|
||||
[DEFAULT_TIME_FORMAT, "2:30 PM"],
|
||||
["24h", "14:30"],
|
||||
] as const)("formats times with %s clock", (timeFormat, expected) => {
|
||||
expect(formatTime(sampleDate, { locale: "en-US", timeZone: "UTC", timeFormat })).toBe(expected);
|
||||
});
|
||||
|
||||
test.each([
|
||||
["en-US", { dateFormat: "MM/DD/YYYY", timeFormat: "12h" }],
|
||||
["en-GB", { dateFormat: "DD/MM/YYYY", timeFormat: "24h" }],
|
||||
["ja-JP", { dateFormat: "YYYY/MM/DD", timeFormat: "24h" }],
|
||||
] as const)("infers date and time preferences for %s", (locale, expected) => {
|
||||
expect(inferDateTimePreferences(locale)).toEqual(expected);
|
||||
});
|
||||
|
||||
test("formats combined values with custom date and time preferences", () => {
|
||||
expect(
|
||||
formatDateTime(sampleDate, {
|
||||
locale: "en-US",
|
||||
timeZone: "UTC",
|
||||
dateFormat: "DD/MM/YYYY",
|
||||
timeFormat: "24h",
|
||||
}),
|
||||
).toBe("10/01/2026, 14:30");
|
||||
});
|
||||
});
|
||||
|
|
@ -7,6 +7,7 @@ import {
|
|||
inferAdditionalFields,
|
||||
} from "better-auth/client/plugins";
|
||||
import { ssoClient } from "@better-auth/sso/client";
|
||||
import { passkeyClient } from "@better-auth/passkey/client";
|
||||
import type { auth } from "~/server/lib/auth";
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
|
|
@ -17,5 +18,6 @@ export const authClient = createAuthClient({
|
|||
organizationClient(),
|
||||
ssoClient(),
|
||||
twoFactorClient(),
|
||||
passkeyClient(),
|
||||
],
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,93 +1,234 @@
|
|||
import { formatDistanceToNow, isValid } from "date-fns";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useRootLoaderData } from "~/client/hooks/use-root-loader-data";
|
||||
|
||||
// 1/10/2026, 2:30 PM
|
||||
export function formatDateTime(date: Date | string | number | null | undefined): string {
|
||||
export type DateInput = Date | string | number | null | undefined;
|
||||
|
||||
export const DATE_FORMATS = ["MM/DD/YYYY", "DD/MM/YYYY", "YYYY/MM/DD"] as const;
|
||||
export type DateFormatPreference = (typeof DATE_FORMATS)[number];
|
||||
const DEFAULT_DATE_FORMAT: DateFormatPreference = "MM/DD/YYYY";
|
||||
|
||||
export const TIME_FORMATS = ["12h", "24h"] as const;
|
||||
export type TimeFormatPreference = (typeof TIME_FORMATS)[number];
|
||||
export const DEFAULT_TIME_FORMAT: TimeFormatPreference = "12h";
|
||||
|
||||
const BROWSER_PREFERENCE_SAMPLE_DATE = new Date(Date.UTC(2006, 0, 2, 15, 4, 5));
|
||||
|
||||
const DATE_PART_ORDERS = {
|
||||
"MM/DD/YYYY": ["month", "day", "year"],
|
||||
"DD/MM/YYYY": ["day", "month", "year"],
|
||||
"YYYY/MM/DD": ["year", "month", "day"],
|
||||
} as const;
|
||||
|
||||
const SHORT_DATE_PART_ORDERS = {
|
||||
"MM/DD/YYYY": ["month", "day"],
|
||||
"DD/MM/YYYY": ["day", "month"],
|
||||
"YYYY/MM/DD": ["month", "day"],
|
||||
} as const;
|
||||
|
||||
type DateFormatOptions = {
|
||||
locale?: string | string[];
|
||||
timeZone?: string;
|
||||
dateFormat?: DateFormatPreference;
|
||||
timeFormat?: TimeFormatPreference;
|
||||
};
|
||||
|
||||
function formatValidDate(date: DateInput, formatter: (date: Date) => string): string {
|
||||
if (!date) return "Never";
|
||||
const d = new Date(date);
|
||||
if (!isValid(d)) return "Invalid Date";
|
||||
|
||||
return Intl.DateTimeFormat(navigator.languages, {
|
||||
month: "numeric",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
hour: "numeric",
|
||||
minute: "numeric",
|
||||
}).format(d);
|
||||
const parsedDate = new Date(date);
|
||||
if (!isValid(parsedDate)) return "Invalid Date";
|
||||
|
||||
return formatter(parsedDate);
|
||||
}
|
||||
|
||||
// Jan 10, 2026
|
||||
export function formatDateWithMonth(date: Date | string | number | null | undefined): string {
|
||||
if (!date) return "Never";
|
||||
const d = new Date(date);
|
||||
if (!isValid(d)) return "Invalid Date";
|
||||
return Intl.DateTimeFormat(navigator.languages, {
|
||||
function getDateTimeFormat(
|
||||
locale: DateFormatOptions["locale"],
|
||||
timeZone: DateFormatOptions["timeZone"],
|
||||
options: Intl.DateTimeFormatOptions,
|
||||
) {
|
||||
return Intl.DateTimeFormat(locale, {
|
||||
...options,
|
||||
timeZone,
|
||||
});
|
||||
}
|
||||
|
||||
function getRequiredPart(parts: Intl.DateTimeFormatPart[], type: Intl.DateTimeFormatPartTypes) {
|
||||
const value = parts.find((part) => part.type === type)?.value;
|
||||
|
||||
if (!value) {
|
||||
throw new Error(`Missing ${type} in formatted date`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function formatConfiguredDate(date: Date, options: DateFormatOptions, includeYear: boolean) {
|
||||
const dateFormat = options.dateFormat ?? DEFAULT_DATE_FORMAT;
|
||||
const safeDateFormat = DATE_FORMATS.includes(dateFormat) ? dateFormat : DEFAULT_DATE_FORMAT;
|
||||
const parts = getDateTimeFormat(options.locale, options.timeZone, {
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
}).formatToParts(date);
|
||||
const values = {
|
||||
month: getRequiredPart(parts, "month"),
|
||||
day: getRequiredPart(parts, "day"),
|
||||
year: getRequiredPart(parts, "year"),
|
||||
};
|
||||
const order = includeYear ? DATE_PART_ORDERS[safeDateFormat] : SHORT_DATE_PART_ORDERS[safeDateFormat];
|
||||
|
||||
return order.map((part) => values[part]).join("/");
|
||||
}
|
||||
|
||||
function formatConfiguredDateWithMonth(date: Date, options: DateFormatOptions) {
|
||||
const dateFormat = options.dateFormat ?? DEFAULT_DATE_FORMAT;
|
||||
const parts = getDateTimeFormat(options.locale, options.timeZone, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
}).format(d);
|
||||
}).formatToParts(date);
|
||||
const month = getRequiredPart(parts, "month");
|
||||
const day = getRequiredPart(parts, "day");
|
||||
const year = getRequiredPart(parts, "year");
|
||||
|
||||
if (dateFormat === "DD/MM/YYYY") {
|
||||
return `${day} ${month} ${year}`;
|
||||
}
|
||||
|
||||
if (dateFormat === "YYYY/MM/DD") {
|
||||
return `${year} ${month} ${day}`;
|
||||
}
|
||||
|
||||
return `${month} ${day}, ${year}`;
|
||||
}
|
||||
|
||||
// 1/10/2026
|
||||
export function formatDate(date: Date | string | number | null | undefined): string {
|
||||
if (!date) return "Never";
|
||||
const d = new Date(date);
|
||||
if (!isValid(d)) return "Invalid Date";
|
||||
function formatConfiguredTime(date: Date, options: DateFormatOptions) {
|
||||
return getDateTimeFormat(options.locale, options.timeZone, {
|
||||
hour: "numeric",
|
||||
minute: "numeric",
|
||||
hour12: (options.timeFormat ?? DEFAULT_TIME_FORMAT) === "12h",
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
return Intl.DateTimeFormat(navigator.languages, {
|
||||
export function inferDateTimePreferences(locale?: string) {
|
||||
const dateOrder = getDateTimeFormat(locale, undefined, {
|
||||
month: "numeric",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
}).format(d);
|
||||
})
|
||||
.formatToParts(BROWSER_PREFERENCE_SAMPLE_DATE)
|
||||
.flatMap((part) => {
|
||||
if (part.type === "year" || part.type === "month" || part.type === "day") {
|
||||
return [part.type];
|
||||
}
|
||||
|
||||
return [];
|
||||
})
|
||||
.join("/");
|
||||
|
||||
let dateFormat = DEFAULT_DATE_FORMAT;
|
||||
|
||||
if (dateOrder === "day/month/year") {
|
||||
dateFormat = "DD/MM/YYYY";
|
||||
} else if (dateOrder === "year/month/day") {
|
||||
dateFormat = "YYYY/MM/DD";
|
||||
}
|
||||
|
||||
let timeFormat: TimeFormatPreference = "12h";
|
||||
const hour12 = getDateTimeFormat(locale, undefined, { hour: "numeric" }).resolvedOptions().hour12;
|
||||
|
||||
if (hour12 === false) {
|
||||
timeFormat = "24h";
|
||||
}
|
||||
|
||||
return {
|
||||
dateFormat,
|
||||
timeFormat,
|
||||
};
|
||||
}
|
||||
|
||||
// 01/10/2026, 2:30 PM
|
||||
function formatDateTime(date: DateInput, options: DateFormatOptions = {}): string {
|
||||
return formatValidDate(
|
||||
date,
|
||||
(validDate) => `${formatConfiguredDate(validDate, options, true)}, ${formatConfiguredTime(validDate, options)}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Jan 10, 2026
|
||||
function formatDateWithMonth(date: DateInput, options: DateFormatOptions = {}): string {
|
||||
return formatValidDate(date, (validDate) => formatConfiguredDateWithMonth(validDate, options));
|
||||
}
|
||||
|
||||
// 01/10/2026
|
||||
function formatDate(date: DateInput, options: DateFormatOptions = {}): string {
|
||||
return formatValidDate(date, (validDate) => formatConfiguredDate(validDate, options, true));
|
||||
}
|
||||
|
||||
// 1/10
|
||||
export function formatShortDate(date: Date | string | number | null | undefined): string {
|
||||
if (!date) return "Never";
|
||||
const d = new Date(date);
|
||||
if (!isValid(d)) return "Invalid Date";
|
||||
|
||||
return Intl.DateTimeFormat(navigator.languages, {
|
||||
month: "numeric",
|
||||
day: "numeric",
|
||||
}).format(d);
|
||||
function formatShortDate(date: DateInput, options: DateFormatOptions = {}): string {
|
||||
return formatValidDate(date, (validDate) => formatConfiguredDate(validDate, options, false));
|
||||
}
|
||||
|
||||
// 1/10, 2:30 PM
|
||||
export function formatShortDateTime(date: Date | string | number | null | undefined): string {
|
||||
if (!date) return "Never";
|
||||
const d = new Date(date);
|
||||
if (!isValid(d)) return "Invalid Date";
|
||||
|
||||
return Intl.DateTimeFormat(navigator.languages, {
|
||||
month: "numeric",
|
||||
day: "numeric",
|
||||
hour: "numeric",
|
||||
minute: "numeric",
|
||||
}).format(d);
|
||||
// 01/10, 2:30 PM
|
||||
function formatShortDateTime(date: DateInput, options: DateFormatOptions = {}): string {
|
||||
return formatValidDate(
|
||||
date,
|
||||
(validDate) => `${formatConfiguredDate(validDate, options, false)}, ${formatConfiguredTime(validDate, options)}`,
|
||||
);
|
||||
}
|
||||
|
||||
// 2:30 PM
|
||||
export function formatTime(date: Date | string | number | null | undefined): string {
|
||||
if (!date) return "Never";
|
||||
const d = new Date(date);
|
||||
if (!isValid(d)) return "Invalid Date";
|
||||
|
||||
return Intl.DateTimeFormat(navigator.languages, {
|
||||
hour: "numeric",
|
||||
minute: "numeric",
|
||||
}).format(d);
|
||||
function formatTime(date: DateInput, options: DateFormatOptions = {}): string {
|
||||
return formatValidDate(date, (validDate) => formatConfiguredTime(validDate, options));
|
||||
}
|
||||
|
||||
// 5 minutes ago
|
||||
export function formatTimeAgo(date: Date | string | number | null | undefined): string {
|
||||
if (!date) return "Never";
|
||||
const d = new Date(date);
|
||||
if (!isValid(d)) return "Invalid Date";
|
||||
function formatTimeAgo(date: DateInput, now = Date.now()): string {
|
||||
return formatValidDate(date, (validDate) => {
|
||||
if (Math.abs(now - validDate.getTime()) < 120_000) {
|
||||
return "just now";
|
||||
}
|
||||
|
||||
const timeAgo = formatDistanceToNow(d, {
|
||||
addSuffix: true,
|
||||
includeSeconds: true,
|
||||
const timeAgo = formatDistanceToNow(validDate, {
|
||||
addSuffix: true,
|
||||
includeSeconds: true,
|
||||
});
|
||||
|
||||
return timeAgo.replace("about ", "").replace("over ", "").replace("almost ", "").replace("less than ", "");
|
||||
});
|
||||
|
||||
return timeAgo.replace("about ", "").replace("over ", "").replace("almost ", "").replace("less than ", "");
|
||||
}
|
||||
|
||||
export function useTimeFormat() {
|
||||
const { locale, timeZone, dateFormat, timeFormat, now } = useRootLoaderData();
|
||||
const [currentNow, setCurrentNow] = useState(now);
|
||||
|
||||
useEffect(() => {
|
||||
const nextNow = Date.now();
|
||||
setCurrentNow(nextNow === now ? now : nextNow);
|
||||
}, [now]);
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
formatDateTime: (date: DateInput) => formatDateTime(date, { locale, timeZone, dateFormat, timeFormat }),
|
||||
formatDateWithMonth: (date: DateInput) => formatDateWithMonth(date, { locale, timeZone, dateFormat, timeFormat }),
|
||||
formatDate: (date: DateInput) => formatDate(date, { locale, timeZone, dateFormat, timeFormat }),
|
||||
formatShortDate: (date: DateInput) => formatShortDate(date, { locale, timeZone, dateFormat, timeFormat }),
|
||||
formatShortDateTime: (date: DateInput) => formatShortDateTime(date, { locale, timeZone, dateFormat, timeFormat }),
|
||||
formatTime: (date: DateInput) => formatTime(date, { locale, timeZone, dateFormat, timeFormat }),
|
||||
formatTimeAgo: (date: DateInput) => formatTimeAgo(date, currentNow),
|
||||
}),
|
||||
[locale, timeZone, currentNow, dateFormat, timeFormat],
|
||||
);
|
||||
}
|
||||
|
||||
export const rawFormatters = {
|
||||
formatDateTime,
|
||||
formatDateWithMonth,
|
||||
formatDate,
|
||||
formatShortDate,
|
||||
formatShortDateTime,
|
||||
formatTime,
|
||||
formatTimeAgo,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { unlockRepository } from "~/client/api-client/sdk.gen";
|
|||
import { Button } from "~/client/components/ui/button";
|
||||
import { Unlock } from "lucide-react";
|
||||
|
||||
export const isLockError = (error: unknown): boolean => {
|
||||
const isLockError = (error: unknown): boolean => {
|
||||
const errorMessage = parseError(error)?.message || "";
|
||||
|
||||
return (
|
||||
|
|
@ -25,7 +25,7 @@ export const parseError = (error?: unknown) => {
|
|||
return undefined;
|
||||
};
|
||||
|
||||
export const showLockErrorToast = (repositoryId: string, title: string) => {
|
||||
const showLockErrorToast = (repositoryId: string, title: string) => {
|
||||
toast.error(title, {
|
||||
description:
|
||||
"The repository is currently locked by another operation. This can happen when a previous operation didn't complete properly.",
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue