From 70f97c4b16e36190666915a137541bdbe150b21b Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Fri, 8 May 2026 21:35:07 +0100 Subject: [PATCH 01/17] split: CI workflows, scripts, root tooling, and docs Forgejo workflows (new), GitHub workflow tweaks, .gitignore/.vscode, root package-lock, rustfmt.toml, scripts/* updates, docs/ updates including data-flow / authentication / server-setup, CLAUDE.md and README updates. --- .forgejo/workflows/check.yml | 35 + .forgejo/workflows/deploy-docs.yml | 38 + .forgejo/workflows/e2e.yml | 71 + .forgejo/workflows/publish-cli-docker.yml | 51 + .forgejo/workflows/publish-plugin.yml | 71 + .forgejo/workflows/publish-server-docker.yml | 51 + .github/workflows/check.yml | 4 +- .github/workflows/deploy-docs.yml | 13 +- .github/workflows/e2e.yml | 6 +- .github/workflows/publish-plugin.yml | 4 +- .gitignore | 9 +- .vscode/settings.json | 4 +- CLAUDE.md | 195 +- README.md | 8 +- docs/.cspell.json | 7 +- docs/architecture/data-flow.md | 58 +- docs/architecture/index.md | 2 +- docs/config/authentication.md | 6 +- docs/guide/server-setup.md | 2 +- docs/package-lock.json | 5960 +++++++++--------- package-lock.json | 6 + rustfmt.toml | 11 + scripts/bump-version.sh | 3 +- scripts/check.sh | 14 +- scripts/clean-up.sh | 2 +- scripts/e2e.sh | 72 +- scripts/update-api-types.sh | 10 +- scripts/utils/check-node.sh | 6 +- scripts/utils/wait-for-server.sh | 4 +- 29 files changed, 3571 insertions(+), 3152 deletions(-) create mode 100644 .forgejo/workflows/check.yml create mode 100644 .forgejo/workflows/deploy-docs.yml create mode 100644 .forgejo/workflows/e2e.yml create mode 100644 .forgejo/workflows/publish-cli-docker.yml create mode 100644 .forgejo/workflows/publish-plugin.yml create mode 100644 .forgejo/workflows/publish-server-docker.yml create mode 100644 package-lock.json create mode 100644 rustfmt.toml diff --git a/.forgejo/workflows/check.yml b/.forgejo/workflows/check.yml new file mode 100644 index 00000000..40e01dea --- /dev/null +++ b/.forgejo/workflows/check.yml @@ -0,0 +1,35 @@ +name: Check + +on: + push: + branches: ["main"] + pull_request: + branches: ["main"] + workflow_dispatch: + +env: + CARGO_TERM_COLOR: always + RUSTFLAGS: "-Dwarnings" + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Node.js environment + uses: actions/setup-node@v4 + with: + node-version: "25.x" + + - name: Setup Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: "1.92.0" + components: clippy, rustfmt + + - name: Lint & test + run: scripts/check.sh diff --git a/.forgejo/workflows/deploy-docs.yml b/.forgejo/workflows/deploy-docs.yml new file mode 100644 index 00000000..c49d0379 --- /dev/null +++ b/.forgejo/workflows/deploy-docs.yml @@ -0,0 +1,38 @@ +name: Deploy Documentation + +on: + push: + branches: + - main + paths: + - "docs/**" + - ".forgejo/workflows/deploy-docs.yml" + workflow_dispatch: + +concurrency: + group: pages + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Node.js environment + uses: actions/setup-node@v4 + with: + node-version: "25.x" + + - name: Build docs + run: scripts/build-docs.sh + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: docs + path: docs/.vitepress/dist diff --git a/.forgejo/workflows/e2e.yml b/.forgejo/workflows/e2e.yml new file mode 100644 index 00000000..eb8d1e54 --- /dev/null +++ b/.forgejo/workflows/e2e.yml @@ -0,0 +1,71 @@ +name: E2E tests + +on: + push: + branches: ["main"] + pull_request: + branches: ["main"] + schedule: + - cron: "0 * * * *" + workflow_dispatch: + +concurrency: + group: e2e-tests + cancel-in-progress: false + +env: + RUSTFLAGS: "-Dwarnings" + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Node.js environment + uses: actions/setup-node@v4 + with: + node-version: "25.x" + + - name: Setup Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: "1.92.0" + components: clippy, rustfmt + + - name: Setup rust + run: | + which sqlx || cargo install sqlx-cli + cd sync-server + sqlx database create --database-url sqlite://db.sqlite3 + sqlx migrate run --source src/app_state/database/migrations --database-url sqlite://db.sqlite3 + + - name: E2E tests + run: | + cd sync-server + cargo run config-e2e.yml --color never & + SERVER_PID=$! + cd .. + + scripts/e2e.sh 8 + EXIT_CODE=$? + + kill $SERVER_PID 2>/dev/null || true + wait $SERVER_PID 2>/dev/null || true + + exit $EXIT_CODE + + - name: Upload e2e logs + if: always() + uses: actions/upload-artifact@v4 + with: + name: e2e-logs + path: logs/ + retention-days: 30 + + - name: Cleanup + if: always() + run: scripts/clean-up.sh diff --git a/.forgejo/workflows/publish-cli-docker.yml b/.forgejo/workflows/publish-cli-docker.yml new file mode 100644 index 00000000..265283ab --- /dev/null +++ b/.forgejo/workflows/publish-cli-docker.yml @@ -0,0 +1,51 @@ +name: Publish CLI + +on: + push: + branches: ["main"] + tags: ["*"] + pull_request: + branches: ["main"] + +jobs: + publish-docker: + runs-on: ubuntu-docker + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Extract registry hostname + id: registry + run: echo "host=$(echo '${{ github.server_url }}' | sed 's|https\?://||')" >> "$GITHUB_OUTPUT" + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log into container registry + uses: docker/login-action@v3 + with: + registry: ${{ steps.registry.outputs.host }} + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract Docker metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ steps.registry.outputs.host }}/${{ github.repository }}-cli + + - name: Build and push Docker image + id: build-and-push + uses: docker/build-push-action@v5 + with: + context: frontend + file: frontend/local-client-cli/Dockerfile + platforms: linux/amd64 + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=registry,ref=${{ steps.registry.outputs.host }}/${{ github.repository }}-cli:buildcache + cache-to: type=registry,ref=${{ steps.registry.outputs.host }}/${{ github.repository }}-cli:buildcache,mode=max diff --git a/.forgejo/workflows/publish-plugin.yml b/.forgejo/workflows/publish-plugin.yml new file mode 100644 index 00000000..25a652aa --- /dev/null +++ b/.forgejo/workflows/publish-plugin.yml @@ -0,0 +1,71 @@ +name: Publish Obsidian plugin + +on: + push: + tags: ["*"] + +env: + CARGO_TERM_COLOR: always + +jobs: + publish-plugin: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Node.js environment + uses: actions/setup-node@v4 + with: + node-version: "25.x" + + - name: Build plugin + run: | + cd frontend + npm ci + npm run build + + - name: Setup Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: "1.92.0" + components: clippy, rustfmt + + - name: Install cross-compilation tools + run: | + apt update + apt install -y gcc-aarch64-linux-gnu musl-tools gcc-mingw-w64-x86-64 jq + + - name: Build Linux and Windows binaries + run: ./scripts/build-sync-server-binaries.sh + + - name: Create release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SERVER_URL: ${{ github.server_url }} + REPO: ${{ github.repository }} + run: | + tag="${GITHUB_REF#refs/tags/}" + + mkdir -p release + cp frontend/obsidian-plugin/dist/* release/ + cp sync-server/artifacts/sync-server-* release/ + + # Create draft release via Forgejo API + RELEASE_ID=$(curl -s -X POST \ + "${SERVER_URL}/api/v1/repos/${REPO}/releases" \ + -H "Authorization: token ${GITHUB_TOKEN}" \ + -H "Content-Type: application/json" \ + -d "{\"tag_name\": \"${tag}\", \"name\": \"${tag}\", \"draft\": true}" \ + | jq -r '.id') + + # Upload release assets + for file in release/*; do + filename=$(basename "$file") + curl -s -X POST \ + "${SERVER_URL}/api/v1/repos/${REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \ + -H "Authorization: token ${GITHUB_TOKEN}" \ + -F "attachment=@${file}" + done diff --git a/.forgejo/workflows/publish-server-docker.yml b/.forgejo/workflows/publish-server-docker.yml new file mode 100644 index 00000000..23852e56 --- /dev/null +++ b/.forgejo/workflows/publish-server-docker.yml @@ -0,0 +1,51 @@ +name: Publish server Docker image + +on: + push: + branches: ["main"] + tags: ["*"] + pull_request: + branches: ["main"] + +jobs: + publish-docker: + runs-on: ubuntu-docker + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Extract registry hostname + id: registry + run: echo "host=$(echo '${{ github.server_url }}' | sed 's|https\?://||')" >> "$GITHUB_OUTPUT" + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log into container registry + if: github.ref_type == 'tag' + uses: docker/login-action@v3 + with: + registry: ${{ steps.registry.outputs.host }} + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract Docker metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ steps.registry.outputs.host }}/${{ github.repository }} + + - name: Build and push Docker image + id: build-and-push + uses: docker/build-push-action@v5 + with: + context: sync-server + platforms: linux/amd64,linux/arm64 + push: ${{ github.ref_type == 'tag' }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=registry,ref=${{ steps.registry.outputs.host }}/${{ github.repository }}:buildcache + cache-to: type=registry,ref=${{ steps.registry.outputs.host }}/${{ github.repository }}:buildcache,mode=max diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 9aa71fb4..fc1b1c99 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -23,13 +23,13 @@ jobs: - name: Setup Node.js environment uses: actions/setup-node@v4.2.0 with: - node-version: "22.x" + node-version: "25.x" check-latest: true - name: Setup Rust toolchain uses: dtolnay/rust-toolchain@stable with: - toolchain: "1.89.0" + toolchain: "1.92.0" components: clippy, rustfmt - name: Lint & test diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index b6d369cc..bb25e463 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -5,8 +5,8 @@ on: branches: - main paths: - - 'docs/**' - - '.github/workflows/deploy-docs.yml' + - "docs/**" + - ".github/workflows/deploy-docs.yml" workflow_dispatch: permissions: @@ -28,12 +28,11 @@ jobs: with: fetch-depth: 0 - - name: Setup Node - uses: actions/setup-node@v4 + - name: Setup Node.js environment + uses: actions/setup-node@v4.2.0 with: - node-version: 22 - cache: npm - cache-dependency-path: docs/package-lock.json + node-version: "25.x" + check-latest: true - name: Setup Pages uses: actions/configure-pages@v4 diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 7d0a2a0f..98dbfc1f 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -6,7 +6,7 @@ on: pull_request: branches: ["main"] schedule: - - cron: '0 * * * *' + - cron: "0 * * * *" workflow_dispatch: concurrency: @@ -28,13 +28,13 @@ jobs: - name: Setup Node.js environment uses: actions/setup-node@v4.2.0 with: - node-version: "22.x" + node-version: "25.x" check-latest: true - name: Setup Rust toolchain uses: dtolnay/rust-toolchain@stable with: - toolchain: "1.89.0" + toolchain: "1.92.0" components: clippy, rustfmt - name: Setup rust diff --git a/.github/workflows/publish-plugin.yml b/.github/workflows/publish-plugin.yml index 92dd199b..452bc601 100644 --- a/.github/workflows/publish-plugin.yml +++ b/.github/workflows/publish-plugin.yml @@ -19,7 +19,7 @@ jobs: - name: Setup Node.js environment uses: actions/setup-node@v4.2.0 with: - node-version: "22.x" + node-version: "25.x" check-latest: true - name: Build plugin @@ -31,7 +31,7 @@ jobs: - name: Setup Rust toolchain uses: dtolnay/rust-toolchain@stable with: - toolchain: "1.89.0" + toolchain: "1.92.0" components: clippy, rustfmt - name: Install cross-compilation tools diff --git a/.gitignore b/.gitignore index a1c1ac4f..967b2b65 100644 --- a/.gitignore +++ b/.gitignore @@ -7,15 +7,18 @@ node_modules # Frontend build folders frontend/*/dist -sync-server/db.sqlite3* -sync-server/databases - # Rust build folders sync-server/target sync-server/artifacts sync-server/bindings/*.ts +# build folders +sync-server/db.sqlite3* +**/databases + *.log *.sqlx target + +.task diff --git a/.vscode/settings.json b/.vscode/settings.json index 88d395f5..98187650 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -5,6 +5,6 @@ "**/dist": true, "**/node_modules": true, "**/.sqlx": true, - "**/target": true, - }, + "**/target": true + } } diff --git a/CLAUDE.md b/CLAUDE.md index c77b091b..39161e39 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,109 +2,154 @@ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. -## Project Overview +## Project shape -VaultLink is a self-hosted Obsidian plugin for real-time collaborative file syncing. The project consists of a Rust-based sync server and a TypeScript frontend with three main components: an Obsidian plugin, a sync client library, and a test client. +VaultLink is a self-hosted Obsidian file-sync system. Two halves of one repo: -## Architecture +- `sync-server/` — Rust (axum + sqlx/SQLite). Source of truth for vault state, broadcasts changes via WebSocket. +- `frontend/` — npm workspaces. The sync engine (`sync-client`) is consumed by an Obsidian plugin, a standalone CLI, a fuzz E2E harness, a scripted determinism harness, and a history UI. -### Core Components +The HTTP/WS API types are generated from Rust (`ts-rs`) and mirrored into the TS workspaces. **Never hand-edit files in `frontend/sync-client/src/services/types/` or `frontend/history-ui/src/lib/types/`** — run `scripts/update-api-types.sh` after changing anything Serde-derived in the server. -- **sync-server/**: Rust-based WebSocket server with SQLite database for document versioning and real-time synchronization -- **frontend/sync-client/**: TypeScript library providing core sync functionality, WebSocket management, and file operations -- **frontend/obsidian-plugin/**: Obsidian plugin that integrates the sync client with Obsidian's API -- **frontend/test-client/**: CLI testing tool for the sync functionality +### Frontend workspaces -### Key Technologies +- `sync-client` — the sync engine; published to consumers via `dist/`. All other TS workspaces depend on it via `file:../sync-client`. +- `obsidian-plugin` — Obsidian plugin built from `sync-client`. +- `local-client-cli` — same engine wrapped as a standalone CLI. +- `history-ui` — vault-history web UI. +- `test-client` — fuzz E2E harness (random ops across N processes). +- `deterministic-tests` — scripted multi-client tests with an in-memory FS, run against a real server. -- **Backend**: Rust with Axum framework, SQLite with SQLx, WebSockets for real-time sync -- **Frontend**: TypeScript, Webpack for bundling, Jest for testing -- **Sync Algorithm**: Uses reconcile-text library for operational transformation +## Common commands -## Development Commands +Pre-push hygiene (formats, lints, runs tests, requires clean git state): -### Server Development -```bash -cd sync-server -cargo run config-e2e.yml # Start development server -cargo test --verbose # Run Rust tests -cargo clippy --all-targets --all-features # Lint Rust code -cargo clippy --all-targets --all-features --fix --allow-dirty --allow-staged # Auto-fix clippy warnings -cargo fmt --all -- --check # Check Rust formatting -cargo fmt --all # Auto-format Rust code -cargo machete --with-metadata # Detect unused dependencies +```sh +scripts/check.sh --fix ``` -### Frontend Development -```bash +Run the fuzz E2E (N parallel processes): + +```sh +scripts/e2e.sh 12 +# Logs land in logs/log_.log. Clean with scripts/clean-up.sh +``` + +Run deterministic tests (require a release-built server in `sync-server/target/release/sync_server` — they spawn it themselves): + +```sh +cd sync-server && cargo build --release && cd .. cd frontend -npm run dev # Start development mode (watches sync-client and obsidian-plugin) -npm run build # Build all workspaces -npm run test # Run all tests -npm run lint # Lint and format TypeScript code +npm run build -w sync-client -w deterministic-tests +node deterministic-tests/dist/cli.js # all +node deterministic-tests/dist/cli.js --filter=rename # subset +node deterministic-tests/dist/cli.js --filter=… -j 4 # cap parallelism ``` -### Database Setup (Development) -```bash +Run a single sync-client unit test by file: + +```sh +cd frontend/sync-client && npx tsx --test 'src/**/sync-event-queue.test.ts' +``` + +Server: dev runs from `sync-server/` against `config-e2e.yml`: + +```sh +cd sync-server +cargo run config-e2e.yml # dev +cargo build --release # used by both e2e harnesses +cargo test # unit + ts-rs binding export tests +``` + +Frontend dev (sync-client + obsidian-plugin watch in parallel): + +```sh +cd frontend && npm install && npm run dev +``` + +Regenerate TS bindings from Rust types (touches `frontend/{sync-client,history-ui}/src/.../types/`): + +```sh +scripts/update-api-types.sh +``` + +## SQLite / sqlx + +The server uses `sqlx::query!` macros that need a prepared `.sqlx` cache to compile offline. Touching any SQL means regenerating it: + +```sh cd sync-server sqlx database create --database-url sqlite://db.sqlite3 sqlx migrate run --source src/app_state/database/migrations --database-url sqlite://db.sqlite3 cargo sqlx prepare --workspace ``` -### Initial Setup -```bash -# Install required cargo tools -cargo install sqlx-cli cargo-machete cargo-edit +New migrations: `sqlx migrate add --source src/app_state/database/migrations `. + +## Sync engine architecture + +Read `frontend/sync-client/src/sync-operations/` to follow the sync engine; the rest of `sync-client` is plumbing (filesystem ops, persistence, services, telemetry). + +The engine is **two independent loops with separate invariants**: + +- **Wire loop** (`syncer.ts`) — drains the single-consumer FIFO queue. HTTP and WS handlers update record fields (`remoteRelativePath`, `parentVersionId`, `remoteHash`) and write content to the file at `record.localPath`. They never move files for path placement. +- **Path reconciler** (`reconciler.ts`) — runs after every drained event. Best-effort pass that moves files to make `localPath === remoteRelativePath`. The move graph is topologically sorted; cycles are resolved by reading every file in the cycle into memory and writing each back to its new slot (no tmp files). Records with pending local events are skipped on each pass — the reconciler operates only on settled records. Failures (slot occupied by an untracked file, etc.) are silent skips; the next pass retries. + +**`SyncEventQueue`** (`sync-event-queue.ts`) holds: + +- `byDocId: Map` — primary record store. +- `byLocalPath: Map` — derived index for path lookups, maintained at every mutation point. +- `events: SyncEvent[]` — pending wire ops in FIFO drain order. + +```ts +DocumentRecord = { + documentId, + parentVersionId, + remoteHash?, + remoteRelativePath, + localPath: RelativePath | undefined +} ``` -### Scripts -- `scripts/check.sh`: Full CI check (builds, lints, tests both server and frontend) -- `scripts/check.sh --fix`: Same as above but auto-fixes linting and formatting issues -- `scripts/e2e.sh`: End-to-end testing -- `scripts/clean-up.sh`: Clean logs and database files -- `scripts/bump-version.sh patch`: Publish new version -- `scripts/update-api-types.sh`: Update TypeScript bindings from Rust types +`localPath === undefined` means the doc has no local file yet — typically a remote create whose target slot was occupied at receive time; the reconciler will fetch and place when the slot frees (the bytes wait in `pendingPlacementContent`). -## Code Structure +Local FS events from the watcher update `localPath` synchronously at enqueue time via `setLocalPath` / `upsertRecord`. The wire loop never updates it for path placement; only the reconciler does. A user rename onto a tracked slot enqueues a `LocalDelete` for the displaced doc (the OS rename clobbered its content) and clears that doc's `localPath`. -### Workspace Configuration -The frontend uses npm workspaces with four packages: -- `sync-client`: Core synchronization logic -- `obsidian-plugin`: Obsidian-specific integration -- `test-client`: Testing utilities -- `local-client-cli`: Standalone CLI for VaultLink sync client +**Pending creates** use a `Promise` chain to serialize dependent ops (`LocalUpdate`, `LocalDelete`) behind the still-in-flight `LocalCreate`. `resolveCreate` resolves the promise once the server returns a docId, and `replacePendingDocumentId` swaps the resolved id across already-queued events. `findLatestCreateForPath` is the lookup the watcher uses to attach dependents; `updatePendingCreatePath` rewrites a pending create's `event.path` in place when the user renames the file before its create has acked. -### Type Generation -Rust structs generate TypeScript types via ts-rs crate, stored in `sync-server/bindings/` and used by frontend packages. +**Watermark.** `lastSeenUpdateId` uses a `MinCovered` (a contiguous-prefix tracker over a stream of integers): we only advance the published min when the next consecutive id has been processed, so out-of-order RemoteChange ids don't fool the WebSocket handshake into requesting a too-recent catch-up. -### Key Files -- `sync-server/src/`: Rust server implementation with WebSocket handlers -- `frontend/sync-client/src/sync-client.ts`: Main sync client entry point -- `frontend/obsidian-plugin/src/vault-link-plugin.ts`: Main Obsidian plugin class -- `frontend/sync-client/src/services/sync-service.ts`: Core synchronization logic +**Server catch-up.** The server's WS handshake replays events newer than the client's `last_seen_vault_update_id` from the `latest_document_versions` view (one row per doc, the latest). On those replayed rows `is_new_file` means _new to this client_ (`creation_vault_update_id > last_seen_vault_update_id`), not "this row is the doc's first version" — necessary because the catch-up only carries the latest version; if a doc was created and updated past the watermark, the client never sees its create otherwise. -## Testing +## Edge-case patterns the sync engine has to survive -### Running Tests -- Server: `cargo test --verbose` -- Frontend: `npm run test` (runs Jest across all workspaces) -- E2E: `scripts/e2e.sh` +The two-loop split defuses most of the old race catalogue (slot-collision stashes, conflict-uuid divergence, `MoveOnConflict.NEW`/`EXISTING` policy choices) by separating wire transport from path placement. What's left: -### Test Structure -- Rust: Unit tests alongside source files -- TypeScript: `.test.ts` files using Jest -- E2E: Uses test-client to simulate multiple concurrent users +**Pending-create docId is a `Promise`, not a string, until the create acks.** Any `LocalUpdate` / `LocalDelete` queued behind a still-in-flight `LocalCreate` carries the create's `resolvers.promise` as its `documentId`. `replacePendingDocumentId` swaps the resolved id across queued events when the create resolves; `===` comparisons against the resolved string elsewhere will silently fail until that swap runs. Anything that walks `events[]` looking for a docId match must either run after the swap or be tolerant of `Promise`-typed ids. -## Code Style +**`processCreate` reads `event.path` live, not `event.originalPath`.** The watcher rewrites `event.path` in place via `updatePendingCreatePath` when the user renames a pending-create file. `originalPath` was removed from `LocalCreate` events specifically because reading it would send the stale pre-rename path to the server. -### Rust -- Uses extensive Clippy lints (see Cargo.toml) -- Follows pedantic linting rules -- Forbids unsafe code -- Uses cargo fmt with default settings +**`record.localPath` mutates in place across awaits.** When the watcher renames a doc while a drain handler is awaiting an HTTP roundtrip, the queue mutates the in-flight event's record so subsequent reads see the new path. Snapshotting `record.localPath` into a local at function entry and using it after an `await` reads/writes a now-vacated slot. Read `record.localPath` live; only snapshot for the deliberate "did it change while I was awaiting" comparison. -### TypeScript -- Prettier configuration: 4-space tabs, trailing commas removed, LF line endings -- ESLint with unused imports plugin -- Consistent across all three frontend packages +**Reconciler-defer is the wire-loop's contract with the reconciler.** The reconciler skips records where `hasPendingLocalEventsForDocumentId` returns true. Wire-loop handlers can therefore freely write `remoteRelativePath` to whatever the server returned — even if it disagrees with `localPath` — knowing the reconciler won't move the file out from under a queued user rename. + +**Watermark advancement is load-bearing both ways.** Branches that _skip_ a remote event without advancing `lastSeenUpdateId` create permanent gaps that re-deliver forever. Branches that _advance_ without applying the content lose data: the server has no further event to re-deliver, the catch-up only carries the latest version, and any state in between is gone. Don't advance unless the event was actually applied (or deliberately discarded after weighing both halves). + +**`isNewFile` semantics differ between catch-up and real-time.** On WS handshake replay it means _new to this client_ (`creation_vault_update_id > last_seen_vault_update_id`); on real-time broadcasts it means _this version is the create_ (`creation_vault_update_id == vault_update_id`). A handler that decides based on one interpretation will be wrong on the other channel; reasoning about fetch-and-treat-as-new vs. ignore needs to know which channel delivered the event. + +**Pause / disable-sync mid-flight** is the one race the new model doesn't structurally fix. An HTTP that committed server-side but whose response was discarded leaves the server holding a doc the client has no record of. Resume → offline scan → server-side dedupe handles it (the server merges the duplicate create into the existing doc), but if the merge produces a deconflict, the client picks up an extra file. Out of scope for the two-loop split. + +**Cycle reconciliation uses in-memory content swap.** When the move graph contains a cycle, the reconciler reads every file in the cycle into memory and writes each back to its new slot, with no tmp files. A write-ahead marker at `.vaultlink/swap-.json` lists each leg; on startup the reconciler reads the marker, hashes each `from` to determine which legs ran, and replays the rest. The `.vaultlink/**` glob is hard-coded as an internal ignore pattern so swap markers don't get sync'd. + +## Two complementary E2E harnesses + +- **`test-client` (fuzz):** random ops across N parallel processes for many minutes. Used by `scripts/e2e.sh`. Catches bugs nobody thought to write a test for, but reproductions are noisy. +- **`deterministic-tests`:** scripted scenarios with an in-memory FS pinned to a real server. Used to _capture_ a fuzz-discovered bug as a minimal repro before fixing it. See `frontend/deterministic-tests/README.md` for the step grammar (`pause-server`, `pause-websocket`, `barrier`, `assert-consistent`, etc.). + +When a fuzz failure surfaces, the workflow is: root-cause from logs → write a deterministic test that fails on the bug → fix → confirm both the deterministic test and `e2e.sh` pass. + +## Style + +- TS: 4-space indent, no tabs, LF, prettier (`trailingComma: "none"`). YAML/MD use 2-space indent. +- Rust: `rustfmt.toml` enforces 4-space spaces, LF. +- Lint: ESLint for TS, Clippy for Rust, `cargo machete` for unused deps. All wired into `scripts/check.sh`. diff --git a/README.md b/README.md index f5da9b61..74c6ee97 100644 --- a/README.md +++ b/README.md @@ -8,12 +8,12 @@ ## Develop -### Install [nvm](https://github.com/nvm-sh/nvm) +### Set up Node.JS 25 with [nvm](https://github.com/nvm-sh/nvm) - `curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash` -- `nvm install 22` -- `nvm use 22` -- Optionally set the system-wide default: `nvm alias default 22` +- `nvm install 25` +- `nvm use 25` +- Optionally, set the system-wide default: `nvm alias default 25` ### Set up Rust diff --git a/docs/.cspell.json b/docs/.cspell.json index 4967ec16..1177e1e1 100644 --- a/docs/.cspell.json +++ b/docs/.cspell.json @@ -2,12 +2,7 @@ "version": "0.2", "language": "en-GB", "dictionaries": ["en-gb"], - "ignorePaths": [ - "node_modules", - ".vitepress/dist", - ".vitepress/cache", - "package-lock.json" - ], + "ignorePaths": ["node_modules", ".vitepress/dist", ".vitepress/cache", "package-lock.json"], "words": [ "VaultLink", "Obsidian", diff --git a/docs/architecture/data-flow.md b/docs/architecture/data-flow.md index 832c5624..167be524 100644 --- a/docs/architecture/data-flow.md +++ b/docs/architecture/data-flow.md @@ -361,11 +361,11 @@ VALUES (?, ?, ?); ```json { - "type": "upload_file", - "path": "notes/example.md", - "content": "File content here...", - "base_version": 10, - "timestamp": "2024-01-01T12:00:00Z" + "type": "upload_file", + "path": "notes/example.md", + "content": "File content here...", + "base_version": 10, + "timestamp": "2024-01-01T12:00:00Z" } ``` @@ -373,8 +373,8 @@ VALUES (?, ?, ?); ```json { - "type": "download_file", - "path": "notes/example.md" + "type": "download_file", + "path": "notes/example.md" } ``` @@ -382,8 +382,8 @@ VALUES (?, ?, ?); ```json { - "type": "delete_file", - "path": "notes/old.md" + "type": "delete_file", + "path": "notes/old.md" } ``` @@ -391,8 +391,8 @@ VALUES (?, ?, ?); ```json { - "type": "list_files", - "since_version": 0 + "type": "list_files", + "since_version": 0 } ``` @@ -402,11 +402,11 @@ VALUES (?, ?, ?); ```json { - "type": "file_updated", - "path": "notes/example.md", - "version": 11, - "size": 1024, - "hash": "abc123..." + "type": "file_updated", + "path": "notes/example.md", + "version": 11, + "size": 1024, + "hash": "abc123..." } ``` @@ -414,10 +414,10 @@ VALUES (?, ?, ?); ```json { - "type": "file_content", - "path": "notes/example.md", - "content": "Updated content...", - "version": 11 + "type": "file_content", + "path": "notes/example.md", + "content": "Updated content...", + "version": 11 } ``` @@ -425,9 +425,9 @@ VALUES (?, ?, ?); ```json { - "type": "file_deleted", - "path": "notes/old.md", - "version": 12 + "type": "file_deleted", + "path": "notes/old.md", + "version": 12 } ``` @@ -435,9 +435,9 @@ VALUES (?, ?, ?); ```json { - "type": "sync_complete", - "total_files": 150, - "current_version": 200 + "type": "sync_complete", + "total_files": 150, + "current_version": 200 } ``` @@ -445,9 +445,9 @@ VALUES (?, ?, ?); ```json { - "type": "error", - "message": "File too large", - "code": "FILE_TOO_LARGE" + "type": "error", + "message": "File too large", + "code": "FILE_TOO_LARGE" } ``` diff --git a/docs/architecture/index.md b/docs/architecture/index.md index f5eca5e3..bebb6c49 100644 --- a/docs/architecture/index.md +++ b/docs/architecture/index.md @@ -53,7 +53,7 @@ Central authority for synchronisation. Rust + Axum framework. **Technology**: -- **Language**: Rust 1.89+ +- **Language**: Rust 1.92+ - **Framework**: Axum (async web framework) - **Database**: SQLite with SQLx - **Protocol**: WebSockets for real-time communication diff --git a/docs/config/authentication.md b/docs/config/authentication.md index 11425b5b..74977be7 100644 --- a/docs/config/authentication.md +++ b/docs/config/authentication.md @@ -243,9 +243,9 @@ users: 2. Client sends authentication message: ```json { - "type": "auth", - "token": "user-token", - "vault": "vault-name" + "type": "auth", + "token": "user-token", + "vault": "vault-name" } ``` 3. Server validates: diff --git a/docs/guide/server-setup.md b/docs/guide/server-setup.md index 7754da54..1848db26 100644 --- a/docs/guide/server-setup.md +++ b/docs/guide/server-setup.md @@ -75,7 +75,7 @@ chmod +x sync_server-linux-x86_64 ### Build from Source -Requirements: Rust 1.89.0+, SQLite development headers, SQLx CLI +Requirements: Rust 1.92.0+, SQLite development headers, SQLx CLI ```bash # Clone the repository diff --git a/docs/package-lock.json b/docs/package-lock.json index dcd4f3b0..d078bbe6 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -1,2989 +1,2989 @@ { - "name": "docs", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { "name": "docs", "version": "1.0.0", - "license": "ISC", - "devDependencies": { - "@cspell/dict-en-gb": "^5.0.19", - "cspell": "^9.3.2", - "prettier": "^3.6.2", - "vitepress": "^1.6.4", - "vue": "^3.5.24" - } - }, - "node_modules/@algolia/abtesting": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@algolia/abtesting/-/abtesting-1.10.0.tgz", - "integrity": "sha512-mQT3jwuTgX8QMoqbIR7mPlWkqQqBPQaPabQzm37xg2txMlaMogK/4hCiiESGdg39MlHZOVHeV+0VJuE7f5UK8A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/autocomplete-core": { - "version": "1.17.7", - "resolved": "https://registry.npmjs.org/@algolia/autocomplete-core/-/autocomplete-core-1.17.7.tgz", - "integrity": "sha512-BjiPOW6ks90UKl7TwMv7oNQMnzU+t/wk9mgIDi6b1tXpUek7MW0lbNOUHpvam9pe3lVCf4xPFT+lK7s+e+fs7Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/autocomplete-plugin-algolia-insights": "1.17.7", - "@algolia/autocomplete-shared": "1.17.7" - } - }, - "node_modules/@algolia/autocomplete-plugin-algolia-insights": { - "version": "1.17.7", - "resolved": "https://registry.npmjs.org/@algolia/autocomplete-plugin-algolia-insights/-/autocomplete-plugin-algolia-insights-1.17.7.tgz", - "integrity": "sha512-Jca5Ude6yUOuyzjnz57og7Et3aXjbwCSDf/8onLHSQgw1qW3ALl9mrMWaXb5FmPVkV3EtkD2F/+NkT6VHyPu9A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/autocomplete-shared": "1.17.7" - }, - "peerDependencies": { - "search-insights": ">= 1 < 3" - } - }, - "node_modules/@algolia/autocomplete-preset-algolia": { - "version": "1.17.7", - "resolved": "https://registry.npmjs.org/@algolia/autocomplete-preset-algolia/-/autocomplete-preset-algolia-1.17.7.tgz", - "integrity": "sha512-ggOQ950+nwbWROq2MOCIL71RE0DdQZsceqrg32UqnhDz8FlO9rL8ONHNsI2R1MH0tkgVIDKI/D0sMiUchsFdWA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/autocomplete-shared": "1.17.7" - }, - "peerDependencies": { - "@algolia/client-search": ">= 4.9.1 < 6", - "algoliasearch": ">= 4.9.1 < 6" - } - }, - "node_modules/@algolia/autocomplete-shared": { - "version": "1.17.7", - "resolved": "https://registry.npmjs.org/@algolia/autocomplete-shared/-/autocomplete-shared-1.17.7.tgz", - "integrity": "sha512-o/1Vurr42U/qskRSuhBH+VKxMvkkUVTLU6WZQr+L5lGZZLYWyhdzWjW0iGXY7EkwRTjBqvN2EsR81yCTGV/kmg==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "@algolia/client-search": ">= 4.9.1 < 6", - "algoliasearch": ">= 4.9.1 < 6" - } - }, - "node_modules/@algolia/client-abtesting": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/client-abtesting/-/client-abtesting-5.44.0.tgz", - "integrity": "sha512-KY5CcrWhRTUo/lV7KcyjrZkPOOF9bjgWpMj9z98VA+sXzVpZtkuskBLCKsWYFp2sbwchZFTd3wJM48H0IGgF7g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/client-analytics": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-5.44.0.tgz", - "integrity": "sha512-LKOCE8S4ewI9bN3ot9RZoYASPi8b78E918/DVPW3HHjCMUe6i+NjbNG6KotU4RpP6AhRWZjjswbOkWelUO+OoA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/client-common": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/client-common/-/client-common-5.44.0.tgz", - "integrity": "sha512-1yyJm4OYC2cztbS28XYVWwLXdwpLsMG4LoZLOltVglQ2+hc/i9q9fUDZyjRa2Bqt4DmkIfezagfMrokhyH4uxQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/client-insights": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/client-insights/-/client-insights-5.44.0.tgz", - "integrity": "sha512-wVQWK6jYYsbEOjIMI+e5voLGPUIbXrvDj392IckXaCPvQ6vCMTXakQqOYCd+znQdL76S+3wHDo77HZWiAYKrtA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/client-personalization": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-5.44.0.tgz", - "integrity": "sha512-lkgRjOjOkqmIkebHjHpU9rLJcJNUDMm+eVSW/KJQYLjGqykEZxal+nYJJTBbLceEU2roByP/+27ZmgIwCdf0iA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/client-query-suggestions": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/client-query-suggestions/-/client-query-suggestions-5.44.0.tgz", - "integrity": "sha512-sYfhgwKu6NDVmZHL1WEKVLsOx/jUXCY4BHKLUOcYa8k4COCs6USGgz6IjFkUf+niwq8NCECMmTC4o/fVQOalsA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/client-search": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/client-search/-/client-search-5.44.0.tgz", - "integrity": "sha512-/FRKUM1G4xn3vV8+9xH1WJ9XknU8rkBGlefruq9jDhYUAvYozKimhrmC2pRqw/RyHhPivmgZCRuC8jHP8piz4Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/ingestion": { - "version": "1.44.0", - "resolved": "https://registry.npmjs.org/@algolia/ingestion/-/ingestion-1.44.0.tgz", - "integrity": "sha512-5+S5ynwMmpTpCLXGjTDpeIa81J+R4BLH0lAojOhmeGSeGEHQTqacl/4sbPyDTcidvnWhaqtyf8m42ue6lvISAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/monitoring": { - "version": "1.44.0", - "resolved": "https://registry.npmjs.org/@algolia/monitoring/-/monitoring-1.44.0.tgz", - "integrity": "sha512-xhaTN8pXJjR6zkrecg4Cc9YZaQK2LKm2R+LkbAq+AYGBCWJxtSGlNwftozZzkUyq4AXWoyoc0x2SyBtq5LRtqQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/recommend": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/recommend/-/recommend-5.44.0.tgz", - "integrity": "sha512-GNcite/uOIS7wgRU1MT7SdNIupGSW+vbK9igIzMePvD2Dl8dy0O3urKPKIbTuZQqiVH1Cb84y5cgLvwNrdCj/Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/requester-browser-xhr": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-5.44.0.tgz", - "integrity": "sha512-YZHBk72Cd7pcuNHzbhNzF/FbbYszlc7JhZlDyQAchnX5S7tcemSS96F39Sy8t4O4WQLpFvUf1MTNedlitWdOsQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/requester-fetch": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/requester-fetch/-/requester-fetch-5.44.0.tgz", - "integrity": "sha512-B9WHl+wQ7uf46t9cq+vVM/ypVbOeuldVDq9OtKsX2ApL2g/htx6ImB9ugDOOJmB5+fE31/XPTuCcYz/j03+idA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/requester-node-http": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-5.44.0.tgz", - "integrity": "sha512-MULm0qeAIk4cdzZ/ehJnl1o7uB5NMokg83/3MKhPq0Pk7+I0uELGNbzIfAkvkKKEYcHALemKdArtySF9eKzh/A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@babel/helper-string-parser": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", - "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-identifier": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", - "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/parser": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.28.5.tgz", - "integrity": "sha512-KKBU1VGYR7ORr3At5HAtUQ+TV3SzRCXmA/8OdDZiLDBIZxVyzXuztPjfLd3BV1PRAQGCMWWSHYhL0F8d5uHBDQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.28.5" - }, - "bin": { - "parser": "bin/babel-parser.js" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/types": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.5.tgz", - "integrity": "sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-string-parser": "^7.27.1", - "@babel/helper-validator-identifier": "^7.28.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@cspell/cspell-bundled-dicts": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/cspell-bundled-dicts/-/cspell-bundled-dicts-9.3.2.tgz", - "integrity": "sha512-OmKzq/0FATHU671GKMzBrTyLdm25Wnziva7h4ylumVn1wnwWsXGef5bgXD7iuApqfqH9SzxsU0NtTB8m8vwEHQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/dict-ada": "^4.1.1", - "@cspell/dict-al": "^1.1.1", - "@cspell/dict-aws": "^4.0.16", - "@cspell/dict-bash": "^4.2.2", - "@cspell/dict-companies": "^3.2.7", - "@cspell/dict-cpp": "^6.0.14", - "@cspell/dict-cryptocurrencies": "^5.0.5", - "@cspell/dict-csharp": "^4.0.7", - "@cspell/dict-css": "^4.0.18", - "@cspell/dict-dart": "^2.3.1", - "@cspell/dict-data-science": "^2.0.11", - "@cspell/dict-django": "^4.1.5", - "@cspell/dict-docker": "^1.1.16", - "@cspell/dict-dotnet": "^5.0.10", - "@cspell/dict-elixir": "^4.0.8", - "@cspell/dict-en_us": "^4.4.24", - "@cspell/dict-en-common-misspellings": "^2.1.8", - "@cspell/dict-en-gb-mit": "^3.1.14", - "@cspell/dict-filetypes": "^3.0.14", - "@cspell/dict-flutter": "^1.1.1", - "@cspell/dict-fonts": "^4.0.5", - "@cspell/dict-fsharp": "^1.1.1", - "@cspell/dict-fullstack": "^3.2.7", - "@cspell/dict-gaming-terms": "^1.1.2", - "@cspell/dict-git": "^3.0.7", - "@cspell/dict-golang": "^6.0.24", - "@cspell/dict-google": "^1.0.9", - "@cspell/dict-haskell": "^4.0.6", - "@cspell/dict-html": "^4.0.12", - "@cspell/dict-html-symbol-entities": "^4.0.4", - "@cspell/dict-java": "^5.0.12", - "@cspell/dict-julia": "^1.1.1", - "@cspell/dict-k8s": "^1.0.12", - "@cspell/dict-kotlin": "^1.1.1", - "@cspell/dict-latex": "^4.0.4", - "@cspell/dict-lorem-ipsum": "^4.0.5", - "@cspell/dict-lua": "^4.0.8", - "@cspell/dict-makefile": "^1.0.5", - "@cspell/dict-markdown": "^2.0.12", - "@cspell/dict-monkeyc": "^1.0.11", - "@cspell/dict-node": "^5.0.8", - "@cspell/dict-npm": "^5.2.22", - "@cspell/dict-php": "^4.1.0", - "@cspell/dict-powershell": "^5.0.15", - "@cspell/dict-public-licenses": "^2.0.15", - "@cspell/dict-python": "^4.2.21", - "@cspell/dict-r": "^2.1.1", - "@cspell/dict-ruby": "^5.0.9", - "@cspell/dict-rust": "^4.0.12", - "@cspell/dict-scala": "^5.0.8", - "@cspell/dict-shell": "^1.1.2", - "@cspell/dict-software-terms": "^5.1.13", - "@cspell/dict-sql": "^2.2.1", - "@cspell/dict-svelte": "^1.0.7", - "@cspell/dict-swift": "^2.0.6", - "@cspell/dict-terraform": "^1.1.3", - "@cspell/dict-typescript": "^3.2.3", - "@cspell/dict-vue": "^3.0.5", - "@cspell/dict-zig": "^1.0.0" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/cspell-json-reporter": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/cspell-json-reporter/-/cspell-json-reporter-9.3.2.tgz", - "integrity": "sha512-YRgpeHN9uY8kUlIw9q+8zJ0tRTAJMbfBTGzCq9Puah09NeMWlRMFPUkXVrkdic6NA7etboZ+zEdoZwRO9EmhiA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/cspell-types": "9.3.2" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/cspell-pipe": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/cspell-pipe/-/cspell-pipe-9.3.2.tgz", - "integrity": "sha512-REF7ibG79WLEynIMUss/IRDCdYEb1nlE1rj/gt2CbPFzLa6t5MRwW2lajEvXS6/WgbMtsTVHAWi3ALqJzCwxng==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/cspell-resolver": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/cspell-resolver/-/cspell-resolver-9.3.2.tgz", - "integrity": "sha512-jLN2Aa/vxm8+IBvTd884SwPEfjxnDwIEPBT3hmqgLlKuUHQ3FMG27lsM4Ik9L2KWBXMgV/wGz4BaxfhKI41Ttw==", - "dev": true, - "license": "MIT", - "dependencies": { - "global-directory": "^4.0.1" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/cspell-service-bus": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/cspell-service-bus/-/cspell-service-bus-9.3.2.tgz", - "integrity": "sha512-/rB8LazM0JzKL+AvZa5fEpLutmwy5QFMpzw8HJd+rDGkzb5r79hURWSRo84QArgaskUqA9XlOHSieDE9pt+WAA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/cspell-types": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/cspell-types/-/cspell-types-9.3.2.tgz", - "integrity": "sha512-l4H8bMAmdzCbXHO8y1JZiAKszrPEiuLFKWrbhCacHF0iP+PIc/yuQp7cO70m0p70vArRfih6kgGyHFaCy47CfA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/dict-ada": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-ada/-/dict-ada-4.1.1.tgz", - "integrity": "sha512-E+0YW9RhZod/9Qy2gxfNZiHJjCYFlCdI69br1eviQQWB8yOTJX0JHXLs79kOYhSW0kINPVUdvddEBe6Lu6CjGQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-al": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-al/-/dict-al-1.1.1.tgz", - "integrity": "sha512-sD8GCaZetgQL4+MaJLXqbzWcRjfKVp8x+px3HuCaaiATAAtvjwUQ5/Iubiqwfd1boIh2Y1/3EgM3TLQ7Q8e0wQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-aws": { - "version": "4.0.16", - "resolved": "https://registry.npmjs.org/@cspell/dict-aws/-/dict-aws-4.0.16.tgz", - "integrity": "sha512-a681zShZbtTo947NvTYGLer95ZDQw1ROKvIFydak1e0OlfFCsNdtcYTupn0nbbYs53c9AO7G2DU8AcNEAnwXPA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-bash": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/@cspell/dict-bash/-/dict-bash-4.2.2.tgz", - "integrity": "sha512-kyWbwtX3TsCf5l49gGQIZkRLaB/P8g73GDRm41Zu8Mv51kjl2H7Au0TsEvHv7jzcsRLS6aUYaZv6Zsvk1fOz+Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/dict-shell": "1.1.2" - } - }, - "node_modules/@cspell/dict-companies": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/@cspell/dict-companies/-/dict-companies-3.2.7.tgz", - "integrity": "sha512-fEyr3LmpFKTaD0LcRhB4lfW1AmULYBqzg4gWAV0dQCv06l+TsA+JQ+3pZJbUcoaZirtgsgT3dL3RUjmGPhUH0A==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-cpp": { - "version": "6.0.14", - "resolved": "https://registry.npmjs.org/@cspell/dict-cpp/-/dict-cpp-6.0.14.tgz", - "integrity": "sha512-dkmpSwvVfVdtoZ4mW/CK2Ep1v8mJlp6uiKpMNbSMOdJl4kq28nQS4vKNIX3B2bJa0Ha5iHHu+1mNjiLeO3g7Xg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-cryptocurrencies": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/@cspell/dict-cryptocurrencies/-/dict-cryptocurrencies-5.0.5.tgz", - "integrity": "sha512-R68hYYF/rtlE6T/dsObStzN5QZw+0aQBinAXuWCVqwdS7YZo0X33vGMfChkHaiCo3Z2+bkegqHlqxZF4TD3rUA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-csharp": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/@cspell/dict-csharp/-/dict-csharp-4.0.7.tgz", - "integrity": "sha512-H16Hpu8O/1/lgijFt2lOk4/nnldFtQ4t8QHbyqphqZZVE5aS4J/zD/WvduqnLY21aKhZS6jo/xF5PX9jyqPKUA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-css": { - "version": "4.0.18", - "resolved": "https://registry.npmjs.org/@cspell/dict-css/-/dict-css-4.0.18.tgz", - "integrity": "sha512-EF77RqROHL+4LhMGW5NTeKqfUd/e4OOv6EDFQ/UQQiFyWuqkEKyEz0NDILxOFxWUEVdjT2GQ2cC7t12B6pESwg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-dart": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-dart/-/dict-dart-2.3.1.tgz", - "integrity": "sha512-xoiGnULEcWdodXI6EwVyqpZmpOoh8RA2Xk9BNdR7DLamV/QMvEYn8KJ7NlRiTSauJKPNkHHQ5EVHRM6sTS7jdg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-data-science": { - "version": "2.0.12", - "resolved": "https://registry.npmjs.org/@cspell/dict-data-science/-/dict-data-science-2.0.12.tgz", - "integrity": "sha512-vI/mg6cI28IkFcpeINS7cm5M9HWemmXSTnxJiu3nmc4VAGx35SXIEyuLGBcsVzySvDablFYf4hsEpmg1XpVsUQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-django": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/@cspell/dict-django/-/dict-django-4.1.5.tgz", - "integrity": "sha512-AvTWu99doU3T8ifoMYOMLW2CXKvyKLukPh1auOPwFGHzueWYvBBN+OxF8wF7XwjTBMMeRleVdLh3aWCDEX/ZWg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-docker": { - "version": "1.1.16", - "resolved": "https://registry.npmjs.org/@cspell/dict-docker/-/dict-docker-1.1.16.tgz", - "integrity": "sha512-UiVQ5RmCg6j0qGIxrBnai3pIB+aYKL3zaJGvXk1O/ertTKJif9RZikKXCEgqhaCYMweM4fuLqWSVmw3hU164Iw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-dotnet": { - "version": "5.0.10", - "resolved": "https://registry.npmjs.org/@cspell/dict-dotnet/-/dict-dotnet-5.0.10.tgz", - "integrity": "sha512-ooar8BP/RBNP1gzYfJPStKEmpWy4uv/7JCq6FOnJLeD1yyfG3d/LFMVMwiJo+XWz025cxtkM3wuaikBWzCqkmg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-elixir": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/@cspell/dict-elixir/-/dict-elixir-4.0.8.tgz", - "integrity": "sha512-CyfphrbMyl4Ms55Vzuj+mNmd693HjBFr9hvU+B2YbFEZprE5AG+EXLYTMRWrXbpds4AuZcvN3deM2XVB80BN/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-en_us": { - "version": "4.4.24", - "resolved": "https://registry.npmjs.org/@cspell/dict-en_us/-/dict-en_us-4.4.24.tgz", - "integrity": "sha512-JE+/H2YicHJTneRmgH4GSI21rS+1yGZVl1jfOQgl8iHLC+yTTMtCvueNDMK94CgJACzYAoCsQB70MqiFJJfjLQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-en-common-misspellings": { - "version": "2.1.8", - "resolved": "https://registry.npmjs.org/@cspell/dict-en-common-misspellings/-/dict-en-common-misspellings-2.1.8.tgz", - "integrity": "sha512-vDsjRFPQGuAADAiitf82z9Mz3DcqKZi6V5hPAEIFkLLKjFVBcjUsSq59SfL59ElIFb76MtBO0BLifdEbBj+DoQ==", - "dev": true, - "license": "CC BY-SA 4.0" - }, - "node_modules/@cspell/dict-en-gb": { - "version": "5.0.19", - "resolved": "https://registry.npmjs.org/@cspell/dict-en-gb/-/dict-en-gb-5.0.19.tgz", - "integrity": "sha512-/p+p/9q8XTzsE0GxbZZKcC1rTLYmCpilYw8aC9Q1xJbve8YqZnpxk8IxRyaHwfy1TeKMQNs6heZZRtzPag0rCw==", - "dev": true, - "license": "LGPL-3.0" - }, - "node_modules/@cspell/dict-en-gb-mit": { - "version": "3.1.14", - "resolved": "https://registry.npmjs.org/@cspell/dict-en-gb-mit/-/dict-en-gb-mit-3.1.14.tgz", - "integrity": "sha512-b+vEerlHP6rnNf30tmTJb7JZnOq4WAslYUvexOz/L3gDna9YJN3bAnwRJ3At3bdcOcMG7PTv3Pi+C73IR22lNg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-filetypes": { - "version": "3.0.14", - "resolved": "https://registry.npmjs.org/@cspell/dict-filetypes/-/dict-filetypes-3.0.14.tgz", - "integrity": "sha512-KSXaSMYYNMLLdHEnju1DyRRH3eQWPRYRnOXpuHUdOh2jC44VgQoxyMU7oB3NAhDhZKBPCihabzECsAGFbdKfEA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-flutter": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-flutter/-/dict-flutter-1.1.1.tgz", - "integrity": "sha512-UlOzRcH2tNbFhZmHJN48Za/2/MEdRHl2BMkCWZBYs+30b91mWvBfzaN4IJQU7dUZtowKayVIF9FzvLZtZokc5A==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-fonts": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/@cspell/dict-fonts/-/dict-fonts-4.0.5.tgz", - "integrity": "sha512-BbpkX10DUX/xzHs6lb7yzDf/LPjwYIBJHJlUXSBXDtK/1HaeS+Wqol4Mlm2+NAgZ7ikIE5DQMViTgBUY3ezNoQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-fsharp": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-fsharp/-/dict-fsharp-1.1.1.tgz", - "integrity": "sha512-imhs0u87wEA4/cYjgzS0tAyaJpwG7vwtC8UyMFbwpmtw+/bgss+osNfyqhYRyS/ehVCWL17Ewx2UPkexjKyaBA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-fullstack": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/@cspell/dict-fullstack/-/dict-fullstack-3.2.7.tgz", - "integrity": "sha512-IxEk2YAwAJKYCUEgEeOg3QvTL4XLlyArJElFuMQevU1dPgHgzWElFevN5lsTFnvMFA1riYsVinqJJX0BanCFEg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-gaming-terms": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@cspell/dict-gaming-terms/-/dict-gaming-terms-1.1.2.tgz", - "integrity": "sha512-9XnOvaoTBscq0xuD6KTEIkk9hhdfBkkvJAIsvw3JMcnp1214OCGW8+kako5RqQ2vTZR3Tnf3pc57o7VgkM0q1Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-git": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/@cspell/dict-git/-/dict-git-3.0.7.tgz", - "integrity": "sha512-odOwVKgfxCQfiSb+nblQZc4ErXmnWEnv8XwkaI4sNJ7cNmojnvogYVeMqkXPjvfrgEcizEEA4URRD2Ms5PDk1w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-golang": { - "version": "6.0.24", - "resolved": "https://registry.npmjs.org/@cspell/dict-golang/-/dict-golang-6.0.24.tgz", - "integrity": "sha512-rY7PlC3MsHozmjrZWi0HQPUl0BVCV0+mwK0rnMT7pOIXqOe4tWCYMULDIsEk4F0gbIxb5badd2dkCPDYjLnDgA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-google": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@cspell/dict-google/-/dict-google-1.0.9.tgz", - "integrity": "sha512-biL65POqialY0i4g6crj7pR6JnBkbsPovB2WDYkj3H4TuC/QXv7Pu5pdPxeUJA6TSCHI7T5twsO4VSVyRxD9CA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-haskell": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/@cspell/dict-haskell/-/dict-haskell-4.0.6.tgz", - "integrity": "sha512-ib8SA5qgftExpYNjWhpYIgvDsZ/0wvKKxSP+kuSkkak520iPvTJumEpIE+qPcmJQo4NzdKMN8nEfaeci4OcFAQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-html": { - "version": "4.0.12", - "resolved": "https://registry.npmjs.org/@cspell/dict-html/-/dict-html-4.0.12.tgz", - "integrity": "sha512-JFffQ1dDVEyJq6tCDWv0r/RqkdSnV43P2F/3jJ9rwLgdsOIXwQbXrz6QDlvQLVvNSnORH9KjDtenFTGDyzfCaA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-html-symbol-entities": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@cspell/dict-html-symbol-entities/-/dict-html-symbol-entities-4.0.4.tgz", - "integrity": "sha512-afea+0rGPDeOV9gdO06UW183Qg6wRhWVkgCFwiO3bDupAoyXRuvupbb5nUyqSTsLXIKL8u8uXQlJ9pkz07oVXw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-java": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/@cspell/dict-java/-/dict-java-5.0.12.tgz", - "integrity": "sha512-qPSNhTcl7LGJ5Qp6VN71H8zqvRQK04S08T67knMq9hTA8U7G1sTKzLmBaDOFhq17vNX/+rT+rbRYp+B5Nwza1A==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-julia": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-julia/-/dict-julia-1.1.1.tgz", - "integrity": "sha512-WylJR9TQ2cgwd5BWEOfdO3zvDB+L7kYFm0I9u0s9jKHWQ6yKmfKeMjU9oXxTBxIufhCXm92SKwwVNAC7gjv+yA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-k8s": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/@cspell/dict-k8s/-/dict-k8s-1.0.12.tgz", - "integrity": "sha512-2LcllTWgaTfYC7DmkMPOn9GsBWsA4DZdlun4po8s2ysTP7CPEnZc1ZfK6pZ2eI4TsZemlUQQ+NZxMe9/QutQxg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-kotlin": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-kotlin/-/dict-kotlin-1.1.1.tgz", - "integrity": "sha512-J3NzzfgmxRvEeOe3qUXnSJQCd38i/dpF9/t3quuWh6gXM+krsAXP75dY1CzDmS8mrJAlBdVBeAW5eAZTD8g86Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-latex": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@cspell/dict-latex/-/dict-latex-4.0.4.tgz", - "integrity": "sha512-YdTQhnTINEEm/LZgTzr9Voz4mzdOXH7YX+bSFs3hnkUHCUUtX/mhKgf1CFvZ0YNM2afjhQcmLaR9bDQVyYBvpA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-lorem-ipsum": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/@cspell/dict-lorem-ipsum/-/dict-lorem-ipsum-4.0.5.tgz", - "integrity": "sha512-9a4TJYRcPWPBKkQAJ/whCu4uCAEgv/O2xAaZEI0n4y1/l18Yyx8pBKoIX5QuVXjjmKEkK7hi5SxyIsH7pFEK9Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-lua": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/@cspell/dict-lua/-/dict-lua-4.0.8.tgz", - "integrity": "sha512-N4PkgNDMu9JVsRu7JBS/3E/dvfItRgk9w5ga2dKq+JupP2Y3lojNaAVFhXISh4Y0a6qXDn2clA6nvnavQ/jjLA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-makefile": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/@cspell/dict-makefile/-/dict-makefile-1.0.5.tgz", - "integrity": "sha512-4vrVt7bGiK8Rx98tfRbYo42Xo2IstJkAF4tLLDMNQLkQ86msDlYSKG1ZCk8Abg+EdNcFAjNhXIiNO+w4KflGAQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-markdown": { - "version": "2.0.12", - "resolved": "https://registry.npmjs.org/@cspell/dict-markdown/-/dict-markdown-2.0.12.tgz", - "integrity": "sha512-ufwoliPijAgWkD/ivAMC+A9QD895xKiJRF/fwwknQb7kt7NozTLKFAOBtXGPJAB4UjhGBpYEJVo2elQ0FCAH9A==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "@cspell/dict-css": "^4.0.18", - "@cspell/dict-html": "^4.0.12", - "@cspell/dict-html-symbol-entities": "^4.0.4", - "@cspell/dict-typescript": "^3.2.3" - } - }, - "node_modules/@cspell/dict-monkeyc": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@cspell/dict-monkeyc/-/dict-monkeyc-1.0.11.tgz", - "integrity": "sha512-7Q1Ncu0urALI6dPTrEbSTd//UK0qjRBeaxhnm8uY5fgYNFYAG+u4gtnTIo59S6Bw5P++4H3DiIDYoQdY/lha8w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-node": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/@cspell/dict-node/-/dict-node-5.0.8.tgz", - "integrity": "sha512-AirZcN2i84ynev3p2/1NCPEhnNsHKMz9zciTngGoqpdItUb2bDt1nJBjwlsrFI78GZRph/VaqTVFwYikmncpXg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-npm": { - "version": "5.2.23", - "resolved": "https://registry.npmjs.org/@cspell/dict-npm/-/dict-npm-5.2.23.tgz", - "integrity": "sha512-cnlPGzhNkbXFLFURfjzwML2LjHMofqJkemR7lLo9Jwa9IptvzeTn4nOtJMSGfkxNrZPf/IvQ7rH5hamsUQLQ3A==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-php": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@cspell/dict-php/-/dict-php-4.1.0.tgz", - "integrity": "sha512-dTDeabyOj7eFvn2Q4Za3uVXM2+SzeFMqX8ly2P0XTo4AzbCmI2hulFD/QIADwWmwiRrInbbf8cxwFHNIYrXl4w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-powershell": { - "version": "5.0.15", - "resolved": "https://registry.npmjs.org/@cspell/dict-powershell/-/dict-powershell-5.0.15.tgz", - "integrity": "sha512-l4S5PAcvCFcVDMJShrYD0X6Huv9dcsQPlsVsBGbH38wvuN7gS7+GxZFAjTNxDmTY1wrNi1cCatSg6Pu2BW4rgg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-public-licenses": { - "version": "2.0.15", - "resolved": "https://registry.npmjs.org/@cspell/dict-public-licenses/-/dict-public-licenses-2.0.15.tgz", - "integrity": "sha512-cJEOs901H13Pfy0fl4dCD1U+xpWIMaEPq8MeYU83FfDZvellAuSo4GqWCripfIqlhns/L6+UZEIJSOZnjgy7Wg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-python": { - "version": "4.2.22", - "resolved": "https://registry.npmjs.org/@cspell/dict-python/-/dict-python-4.2.22.tgz", - "integrity": "sha512-rgF7DuleVK2lkzlw33jjEfxS2a0CU5kwAhOqf5B6XkuaPbqZ/0g0LBCdwglAGccYu7sBuvxRS8Yubk+ytSAFTg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/dict-data-science": "^2.0.12" - } - }, - "node_modules/@cspell/dict-r": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-r/-/dict-r-2.1.1.tgz", - "integrity": "sha512-71Ka+yKfG4ZHEMEmDxc6+blFkeTTvgKbKAbwiwQAuKl3zpqs1Y0vUtwW2N4b3LgmSPhV3ODVY0y4m5ofqDuKMw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-ruby": { - "version": "5.0.9", - "resolved": "https://registry.npmjs.org/@cspell/dict-ruby/-/dict-ruby-5.0.9.tgz", - "integrity": "sha512-H2vMcERMcANvQshAdrVx0XoWaNX8zmmiQN11dZZTQAZaNJ0xatdJoSqY8C8uhEMW89bfgpN+NQgGuDXW2vmXEw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-rust": { - "version": "4.0.12", - "resolved": "https://registry.npmjs.org/@cspell/dict-rust/-/dict-rust-4.0.12.tgz", - "integrity": "sha512-z2QiH+q9UlNhobBJArvILRxV8Jz0pKIK7gqu4TgmEYyjiu1TvnGZ1tbYHeu9w3I/wOP6UMDoCBTty5AlYfW0mw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-scala": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/@cspell/dict-scala/-/dict-scala-5.0.8.tgz", - "integrity": "sha512-YdftVmumv8IZq9zu1gn2U7A4bfM2yj9Vaupydotyjuc+EEZZSqAafTpvW/jKLWji2TgybM1L2IhmV0s/Iv9BTw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-shell": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@cspell/dict-shell/-/dict-shell-1.1.2.tgz", - "integrity": "sha512-WqOUvnwcHK1X61wAfwyXq04cn7KYyskg90j4lLg3sGGKMW9Sq13hs91pqrjC44Q+lQLgCobrTkMDw9Wyl9nRFA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-software-terms": { - "version": "5.1.14", - "resolved": "https://registry.npmjs.org/@cspell/dict-software-terms/-/dict-software-terms-5.1.14.tgz", - "integrity": "sha512-Eu9h090hxHJiqzVFS0WxOZbYXnmb7F1RFIUEg4Nru+D/78bXVDH4b8BiKGVFNRljaieNQRAHaryzdaKJRCH6ZA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-sql": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-sql/-/dict-sql-2.2.1.tgz", - "integrity": "sha512-qDHF8MpAYCf4pWU8NKbnVGzkoxMNrFqBHyG/dgrlic5EQiKANCLELYtGlX5auIMDLmTf1inA0eNtv74tyRJ/vg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-svelte": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/@cspell/dict-svelte/-/dict-svelte-1.0.7.tgz", - "integrity": "sha512-hGZsGqP0WdzKkdpeVLBivRuSNzOTvN036EBmpOwxH+FTY2DuUH7ecW+cSaMwOgmq5JFSdTcbTNFlNC8HN8lhaQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-swift": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@cspell/dict-swift/-/dict-swift-2.0.6.tgz", - "integrity": "sha512-PnpNbrIbex2aqU1kMgwEKvCzgbkHtj3dlFLPMqW1vSniop7YxaDTtvTUO4zA++ugYAEL+UK8vYrBwDPTjjvSnA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-terraform": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@cspell/dict-terraform/-/dict-terraform-1.1.3.tgz", - "integrity": "sha512-gr6wxCydwSFyyBKhBA2xkENXtVFToheqYYGFvlMZXWjviynXmh+NK/JTvTCk/VHk3+lzbO9EEQKee6VjrAUSbA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-typescript": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/@cspell/dict-typescript/-/dict-typescript-3.2.3.tgz", - "integrity": "sha512-zXh1wYsNljQZfWWdSPYwQhpwiuW0KPW1dSd8idjMRvSD0aSvWWHoWlrMsmZeRl4qM4QCEAjua8+cjflm41cQBg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-vue": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/@cspell/dict-vue/-/dict-vue-3.0.5.tgz", - "integrity": "sha512-Mqutb8jbM+kIcywuPQCCaK5qQHTdaByoEO2J9LKFy3sqAdiBogNkrplqUK0HyyRFgCfbJUgjz3N85iCMcWH0JA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-zig": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@cspell/dict-zig/-/dict-zig-1.0.0.tgz", - "integrity": "sha512-XibBIxBlVosU06+M6uHWkFeT0/pW5WajDRYdXG2CgHnq85b0TI/Ks0FuBJykmsgi2CAD3Qtx8UHFEtl/DSFnAQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dynamic-import": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/dynamic-import/-/dynamic-import-9.3.2.tgz", - "integrity": "sha512-au7FyuIHUNI2r9sO3pUBKVTeD/v7c9x/nPUStaAK1bG4rdKt4w+/jUY2IaldAraW5w29z528BboXbiV87SM1kw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/url": "9.3.2", - "import-meta-resolve": "^4.2.0" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/filetypes": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/filetypes/-/filetypes-9.3.2.tgz", - "integrity": "sha512-0bUxQlmJPRHZrRQD7adbc4lFizO8tGD/6+1cBgU3kV3+NVrpr12y4jU8twCSChhYibZyPr7bnvhkM3cQgb8RzA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/strong-weak-map": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/strong-weak-map/-/strong-weak-map-9.3.2.tgz", - "integrity": "sha512-pFcmOTWCoFMRETb9PCkCmaiZiLb5i2qOZmGH/p/tFEH8kIYhMGfhaulnXwKwS+Ke6PKceQd2YL98bGmo8hL4aQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/url": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/url/-/url-9.3.2.tgz", - "integrity": "sha512-TobUlZl7Z7VehhNOMNAg1ABuGizieseftlG94OZJ934JptOhK8TC/1o2ldKrbDH50jyt6E7rPTMV2BW/vWuTzQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/@docsearch/css": { - "version": "3.8.2", - "resolved": "https://registry.npmjs.org/@docsearch/css/-/css-3.8.2.tgz", - "integrity": "sha512-y05ayQFyUmCXze79+56v/4HpycYF3uFqB78pLPrSV5ZKAlDuIAAJNhaRi8tTdRNXh05yxX/TyNnzD6LwSM89vQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@docsearch/js": { - "version": "3.8.2", - "resolved": "https://registry.npmjs.org/@docsearch/js/-/js-3.8.2.tgz", - "integrity": "sha512-Q5wY66qHn0SwA7Taa0aDbHiJvaFJLOJyHmooQ7y8hlwwQLQ/5WwCcoX0g7ii04Qi2DJlHsd0XXzJ8Ypw9+9YmQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@docsearch/react": "3.8.2", - "preact": "^10.0.0" - } - }, - "node_modules/@docsearch/react": { - "version": "3.8.2", - "resolved": "https://registry.npmjs.org/@docsearch/react/-/react-3.8.2.tgz", - "integrity": "sha512-xCRrJQlTt8N9GU0DG4ptwHRkfnSnD/YpdeaXe02iKfqs97TkZJv60yE+1eq/tjPcVnTW8dP5qLP7itifFVV5eg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/autocomplete-core": "1.17.7", - "@algolia/autocomplete-preset-algolia": "1.17.7", - "@docsearch/css": "3.8.2", - "algoliasearch": "^5.14.2" - }, - "peerDependencies": { - "@types/react": ">= 16.8.0 < 19.0.0", - "react": ">= 16.8.0 < 19.0.0", - "react-dom": ">= 16.8.0 < 19.0.0", - "search-insights": ">= 1 < 3" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "docs", + "version": "1.0.0", + "license": "ISC", + "devDependencies": { + "@cspell/dict-en-gb": "^5.0.19", + "cspell": "^9.3.2", + "prettier": "^3.6.2", + "vitepress": "^1.6.4", + "vue": "^3.5.24" + } }, - "react": { - "optional": true + "node_modules/@algolia/abtesting": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@algolia/abtesting/-/abtesting-1.10.0.tgz", + "integrity": "sha512-mQT3jwuTgX8QMoqbIR7mPlWkqQqBPQaPabQzm37xg2txMlaMogK/4hCiiESGdg39MlHZOVHeV+0VJuE7f5UK8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } }, - "react-dom": { - "optional": true + "node_modules/@algolia/autocomplete-core": { + "version": "1.17.7", + "resolved": "https://registry.npmjs.org/@algolia/autocomplete-core/-/autocomplete-core-1.17.7.tgz", + "integrity": "sha512-BjiPOW6ks90UKl7TwMv7oNQMnzU+t/wk9mgIDi6b1tXpUek7MW0lbNOUHpvam9pe3lVCf4xPFT+lK7s+e+fs7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/autocomplete-plugin-algolia-insights": "1.17.7", + "@algolia/autocomplete-shared": "1.17.7" + } }, - "search-insights": { - "optional": true + "node_modules/@algolia/autocomplete-plugin-algolia-insights": { + "version": "1.17.7", + "resolved": "https://registry.npmjs.org/@algolia/autocomplete-plugin-algolia-insights/-/autocomplete-plugin-algolia-insights-1.17.7.tgz", + "integrity": "sha512-Jca5Ude6yUOuyzjnz57og7Et3aXjbwCSDf/8onLHSQgw1qW3ALl9mrMWaXb5FmPVkV3EtkD2F/+NkT6VHyPu9A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/autocomplete-shared": "1.17.7" + }, + "peerDependencies": { + "search-insights": ">= 1 < 3" + } + }, + "node_modules/@algolia/autocomplete-preset-algolia": { + "version": "1.17.7", + "resolved": "https://registry.npmjs.org/@algolia/autocomplete-preset-algolia/-/autocomplete-preset-algolia-1.17.7.tgz", + "integrity": "sha512-ggOQ950+nwbWROq2MOCIL71RE0DdQZsceqrg32UqnhDz8FlO9rL8ONHNsI2R1MH0tkgVIDKI/D0sMiUchsFdWA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/autocomplete-shared": "1.17.7" + }, + "peerDependencies": { + "@algolia/client-search": ">= 4.9.1 < 6", + "algoliasearch": ">= 4.9.1 < 6" + } + }, + "node_modules/@algolia/autocomplete-shared": { + "version": "1.17.7", + "resolved": "https://registry.npmjs.org/@algolia/autocomplete-shared/-/autocomplete-shared-1.17.7.tgz", + "integrity": "sha512-o/1Vurr42U/qskRSuhBH+VKxMvkkUVTLU6WZQr+L5lGZZLYWyhdzWjW0iGXY7EkwRTjBqvN2EsR81yCTGV/kmg==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@algolia/client-search": ">= 4.9.1 < 6", + "algoliasearch": ">= 4.9.1 < 6" + } + }, + "node_modules/@algolia/client-abtesting": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/client-abtesting/-/client-abtesting-5.44.0.tgz", + "integrity": "sha512-KY5CcrWhRTUo/lV7KcyjrZkPOOF9bjgWpMj9z98VA+sXzVpZtkuskBLCKsWYFp2sbwchZFTd3wJM48H0IGgF7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/client-analytics": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-5.44.0.tgz", + "integrity": "sha512-LKOCE8S4ewI9bN3ot9RZoYASPi8b78E918/DVPW3HHjCMUe6i+NjbNG6KotU4RpP6AhRWZjjswbOkWelUO+OoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/client-common": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/client-common/-/client-common-5.44.0.tgz", + "integrity": "sha512-1yyJm4OYC2cztbS28XYVWwLXdwpLsMG4LoZLOltVglQ2+hc/i9q9fUDZyjRa2Bqt4DmkIfezagfMrokhyH4uxQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/client-insights": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/client-insights/-/client-insights-5.44.0.tgz", + "integrity": "sha512-wVQWK6jYYsbEOjIMI+e5voLGPUIbXrvDj392IckXaCPvQ6vCMTXakQqOYCd+znQdL76S+3wHDo77HZWiAYKrtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/client-personalization": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-5.44.0.tgz", + "integrity": "sha512-lkgRjOjOkqmIkebHjHpU9rLJcJNUDMm+eVSW/KJQYLjGqykEZxal+nYJJTBbLceEU2roByP/+27ZmgIwCdf0iA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/client-query-suggestions": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/client-query-suggestions/-/client-query-suggestions-5.44.0.tgz", + "integrity": "sha512-sYfhgwKu6NDVmZHL1WEKVLsOx/jUXCY4BHKLUOcYa8k4COCs6USGgz6IjFkUf+niwq8NCECMmTC4o/fVQOalsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/client-search": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/client-search/-/client-search-5.44.0.tgz", + "integrity": "sha512-/FRKUM1G4xn3vV8+9xH1WJ9XknU8rkBGlefruq9jDhYUAvYozKimhrmC2pRqw/RyHhPivmgZCRuC8jHP8piz4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/ingestion": { + "version": "1.44.0", + "resolved": "https://registry.npmjs.org/@algolia/ingestion/-/ingestion-1.44.0.tgz", + "integrity": "sha512-5+S5ynwMmpTpCLXGjTDpeIa81J+R4BLH0lAojOhmeGSeGEHQTqacl/4sbPyDTcidvnWhaqtyf8m42ue6lvISAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/monitoring": { + "version": "1.44.0", + "resolved": "https://registry.npmjs.org/@algolia/monitoring/-/monitoring-1.44.0.tgz", + "integrity": "sha512-xhaTN8pXJjR6zkrecg4Cc9YZaQK2LKm2R+LkbAq+AYGBCWJxtSGlNwftozZzkUyq4AXWoyoc0x2SyBtq5LRtqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/recommend": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/recommend/-/recommend-5.44.0.tgz", + "integrity": "sha512-GNcite/uOIS7wgRU1MT7SdNIupGSW+vbK9igIzMePvD2Dl8dy0O3urKPKIbTuZQqiVH1Cb84y5cgLvwNrdCj/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/requester-browser-xhr": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-5.44.0.tgz", + "integrity": "sha512-YZHBk72Cd7pcuNHzbhNzF/FbbYszlc7JhZlDyQAchnX5S7tcemSS96F39Sy8t4O4WQLpFvUf1MTNedlitWdOsQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/requester-fetch": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-fetch/-/requester-fetch-5.44.0.tgz", + "integrity": "sha512-B9WHl+wQ7uf46t9cq+vVM/ypVbOeuldVDq9OtKsX2ApL2g/htx6ImB9ugDOOJmB5+fE31/XPTuCcYz/j03+idA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/requester-node-http": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-5.44.0.tgz", + "integrity": "sha512-MULm0qeAIk4cdzZ/ehJnl1o7uB5NMokg83/3MKhPq0Pk7+I0uELGNbzIfAkvkKKEYcHALemKdArtySF9eKzh/A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.28.5.tgz", + "integrity": "sha512-KKBU1VGYR7ORr3At5HAtUQ+TV3SzRCXmA/8OdDZiLDBIZxVyzXuztPjfLd3BV1PRAQGCMWWSHYhL0F8d5uHBDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.5" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.5.tgz", + "integrity": "sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@cspell/cspell-bundled-dicts": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/cspell-bundled-dicts/-/cspell-bundled-dicts-9.3.2.tgz", + "integrity": "sha512-OmKzq/0FATHU671GKMzBrTyLdm25Wnziva7h4ylumVn1wnwWsXGef5bgXD7iuApqfqH9SzxsU0NtTB8m8vwEHQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/dict-ada": "^4.1.1", + "@cspell/dict-al": "^1.1.1", + "@cspell/dict-aws": "^4.0.16", + "@cspell/dict-bash": "^4.2.2", + "@cspell/dict-companies": "^3.2.7", + "@cspell/dict-cpp": "^6.0.14", + "@cspell/dict-cryptocurrencies": "^5.0.5", + "@cspell/dict-csharp": "^4.0.7", + "@cspell/dict-css": "^4.0.18", + "@cspell/dict-dart": "^2.3.1", + "@cspell/dict-data-science": "^2.0.11", + "@cspell/dict-django": "^4.1.5", + "@cspell/dict-docker": "^1.1.16", + "@cspell/dict-dotnet": "^5.0.10", + "@cspell/dict-elixir": "^4.0.8", + "@cspell/dict-en_us": "^4.4.24", + "@cspell/dict-en-common-misspellings": "^2.1.8", + "@cspell/dict-en-gb-mit": "^3.1.14", + "@cspell/dict-filetypes": "^3.0.14", + "@cspell/dict-flutter": "^1.1.1", + "@cspell/dict-fonts": "^4.0.5", + "@cspell/dict-fsharp": "^1.1.1", + "@cspell/dict-fullstack": "^3.2.7", + "@cspell/dict-gaming-terms": "^1.1.2", + "@cspell/dict-git": "^3.0.7", + "@cspell/dict-golang": "^6.0.24", + "@cspell/dict-google": "^1.0.9", + "@cspell/dict-haskell": "^4.0.6", + "@cspell/dict-html": "^4.0.12", + "@cspell/dict-html-symbol-entities": "^4.0.4", + "@cspell/dict-java": "^5.0.12", + "@cspell/dict-julia": "^1.1.1", + "@cspell/dict-k8s": "^1.0.12", + "@cspell/dict-kotlin": "^1.1.1", + "@cspell/dict-latex": "^4.0.4", + "@cspell/dict-lorem-ipsum": "^4.0.5", + "@cspell/dict-lua": "^4.0.8", + "@cspell/dict-makefile": "^1.0.5", + "@cspell/dict-markdown": "^2.0.12", + "@cspell/dict-monkeyc": "^1.0.11", + "@cspell/dict-node": "^5.0.8", + "@cspell/dict-npm": "^5.2.22", + "@cspell/dict-php": "^4.1.0", + "@cspell/dict-powershell": "^5.0.15", + "@cspell/dict-public-licenses": "^2.0.15", + "@cspell/dict-python": "^4.2.21", + "@cspell/dict-r": "^2.1.1", + "@cspell/dict-ruby": "^5.0.9", + "@cspell/dict-rust": "^4.0.12", + "@cspell/dict-scala": "^5.0.8", + "@cspell/dict-shell": "^1.1.2", + "@cspell/dict-software-terms": "^5.1.13", + "@cspell/dict-sql": "^2.2.1", + "@cspell/dict-svelte": "^1.0.7", + "@cspell/dict-swift": "^2.0.6", + "@cspell/dict-terraform": "^1.1.3", + "@cspell/dict-typescript": "^3.2.3", + "@cspell/dict-vue": "^3.0.5", + "@cspell/dict-zig": "^1.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/cspell-json-reporter": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/cspell-json-reporter/-/cspell-json-reporter-9.3.2.tgz", + "integrity": "sha512-YRgpeHN9uY8kUlIw9q+8zJ0tRTAJMbfBTGzCq9Puah09NeMWlRMFPUkXVrkdic6NA7etboZ+zEdoZwRO9EmhiA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/cspell-types": "9.3.2" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/cspell-pipe": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/cspell-pipe/-/cspell-pipe-9.3.2.tgz", + "integrity": "sha512-REF7ibG79WLEynIMUss/IRDCdYEb1nlE1rj/gt2CbPFzLa6t5MRwW2lajEvXS6/WgbMtsTVHAWi3ALqJzCwxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/cspell-resolver": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/cspell-resolver/-/cspell-resolver-9.3.2.tgz", + "integrity": "sha512-jLN2Aa/vxm8+IBvTd884SwPEfjxnDwIEPBT3hmqgLlKuUHQ3FMG27lsM4Ik9L2KWBXMgV/wGz4BaxfhKI41Ttw==", + "dev": true, + "license": "MIT", + "dependencies": { + "global-directory": "^4.0.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/cspell-service-bus": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/cspell-service-bus/-/cspell-service-bus-9.3.2.tgz", + "integrity": "sha512-/rB8LazM0JzKL+AvZa5fEpLutmwy5QFMpzw8HJd+rDGkzb5r79hURWSRo84QArgaskUqA9XlOHSieDE9pt+WAA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/cspell-types": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/cspell-types/-/cspell-types-9.3.2.tgz", + "integrity": "sha512-l4H8bMAmdzCbXHO8y1JZiAKszrPEiuLFKWrbhCacHF0iP+PIc/yuQp7cO70m0p70vArRfih6kgGyHFaCy47CfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/dict-ada": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-ada/-/dict-ada-4.1.1.tgz", + "integrity": "sha512-E+0YW9RhZod/9Qy2gxfNZiHJjCYFlCdI69br1eviQQWB8yOTJX0JHXLs79kOYhSW0kINPVUdvddEBe6Lu6CjGQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-al": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-al/-/dict-al-1.1.1.tgz", + "integrity": "sha512-sD8GCaZetgQL4+MaJLXqbzWcRjfKVp8x+px3HuCaaiATAAtvjwUQ5/Iubiqwfd1boIh2Y1/3EgM3TLQ7Q8e0wQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-aws": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@cspell/dict-aws/-/dict-aws-4.0.16.tgz", + "integrity": "sha512-a681zShZbtTo947NvTYGLer95ZDQw1ROKvIFydak1e0OlfFCsNdtcYTupn0nbbYs53c9AO7G2DU8AcNEAnwXPA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-bash": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@cspell/dict-bash/-/dict-bash-4.2.2.tgz", + "integrity": "sha512-kyWbwtX3TsCf5l49gGQIZkRLaB/P8g73GDRm41Zu8Mv51kjl2H7Au0TsEvHv7jzcsRLS6aUYaZv6Zsvk1fOz+Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/dict-shell": "1.1.2" + } + }, + "node_modules/@cspell/dict-companies": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@cspell/dict-companies/-/dict-companies-3.2.7.tgz", + "integrity": "sha512-fEyr3LmpFKTaD0LcRhB4lfW1AmULYBqzg4gWAV0dQCv06l+TsA+JQ+3pZJbUcoaZirtgsgT3dL3RUjmGPhUH0A==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-cpp": { + "version": "6.0.14", + "resolved": "https://registry.npmjs.org/@cspell/dict-cpp/-/dict-cpp-6.0.14.tgz", + "integrity": "sha512-dkmpSwvVfVdtoZ4mW/CK2Ep1v8mJlp6uiKpMNbSMOdJl4kq28nQS4vKNIX3B2bJa0Ha5iHHu+1mNjiLeO3g7Xg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-cryptocurrencies": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@cspell/dict-cryptocurrencies/-/dict-cryptocurrencies-5.0.5.tgz", + "integrity": "sha512-R68hYYF/rtlE6T/dsObStzN5QZw+0aQBinAXuWCVqwdS7YZo0X33vGMfChkHaiCo3Z2+bkegqHlqxZF4TD3rUA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-csharp": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/@cspell/dict-csharp/-/dict-csharp-4.0.7.tgz", + "integrity": "sha512-H16Hpu8O/1/lgijFt2lOk4/nnldFtQ4t8QHbyqphqZZVE5aS4J/zD/WvduqnLY21aKhZS6jo/xF5PX9jyqPKUA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-css": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@cspell/dict-css/-/dict-css-4.0.18.tgz", + "integrity": "sha512-EF77RqROHL+4LhMGW5NTeKqfUd/e4OOv6EDFQ/UQQiFyWuqkEKyEz0NDILxOFxWUEVdjT2GQ2cC7t12B6pESwg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-dart": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-dart/-/dict-dart-2.3.1.tgz", + "integrity": "sha512-xoiGnULEcWdodXI6EwVyqpZmpOoh8RA2Xk9BNdR7DLamV/QMvEYn8KJ7NlRiTSauJKPNkHHQ5EVHRM6sTS7jdg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-data-science": { + "version": "2.0.12", + "resolved": "https://registry.npmjs.org/@cspell/dict-data-science/-/dict-data-science-2.0.12.tgz", + "integrity": "sha512-vI/mg6cI28IkFcpeINS7cm5M9HWemmXSTnxJiu3nmc4VAGx35SXIEyuLGBcsVzySvDablFYf4hsEpmg1XpVsUQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-django": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@cspell/dict-django/-/dict-django-4.1.5.tgz", + "integrity": "sha512-AvTWu99doU3T8ifoMYOMLW2CXKvyKLukPh1auOPwFGHzueWYvBBN+OxF8wF7XwjTBMMeRleVdLh3aWCDEX/ZWg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-docker": { + "version": "1.1.16", + "resolved": "https://registry.npmjs.org/@cspell/dict-docker/-/dict-docker-1.1.16.tgz", + "integrity": "sha512-UiVQ5RmCg6j0qGIxrBnai3pIB+aYKL3zaJGvXk1O/ertTKJif9RZikKXCEgqhaCYMweM4fuLqWSVmw3hU164Iw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-dotnet": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/@cspell/dict-dotnet/-/dict-dotnet-5.0.10.tgz", + "integrity": "sha512-ooar8BP/RBNP1gzYfJPStKEmpWy4uv/7JCq6FOnJLeD1yyfG3d/LFMVMwiJo+XWz025cxtkM3wuaikBWzCqkmg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-elixir": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/@cspell/dict-elixir/-/dict-elixir-4.0.8.tgz", + "integrity": "sha512-CyfphrbMyl4Ms55Vzuj+mNmd693HjBFr9hvU+B2YbFEZprE5AG+EXLYTMRWrXbpds4AuZcvN3deM2XVB80BN/Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-en_us": { + "version": "4.4.24", + "resolved": "https://registry.npmjs.org/@cspell/dict-en_us/-/dict-en_us-4.4.24.tgz", + "integrity": "sha512-JE+/H2YicHJTneRmgH4GSI21rS+1yGZVl1jfOQgl8iHLC+yTTMtCvueNDMK94CgJACzYAoCsQB70MqiFJJfjLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-en-common-misspellings": { + "version": "2.1.8", + "resolved": "https://registry.npmjs.org/@cspell/dict-en-common-misspellings/-/dict-en-common-misspellings-2.1.8.tgz", + "integrity": "sha512-vDsjRFPQGuAADAiitf82z9Mz3DcqKZi6V5hPAEIFkLLKjFVBcjUsSq59SfL59ElIFb76MtBO0BLifdEbBj+DoQ==", + "dev": true, + "license": "CC BY-SA 4.0" + }, + "node_modules/@cspell/dict-en-gb": { + "version": "5.0.19", + "resolved": "https://registry.npmjs.org/@cspell/dict-en-gb/-/dict-en-gb-5.0.19.tgz", + "integrity": "sha512-/p+p/9q8XTzsE0GxbZZKcC1rTLYmCpilYw8aC9Q1xJbve8YqZnpxk8IxRyaHwfy1TeKMQNs6heZZRtzPag0rCw==", + "dev": true, + "license": "LGPL-3.0" + }, + "node_modules/@cspell/dict-en-gb-mit": { + "version": "3.1.14", + "resolved": "https://registry.npmjs.org/@cspell/dict-en-gb-mit/-/dict-en-gb-mit-3.1.14.tgz", + "integrity": "sha512-b+vEerlHP6rnNf30tmTJb7JZnOq4WAslYUvexOz/L3gDna9YJN3bAnwRJ3At3bdcOcMG7PTv3Pi+C73IR22lNg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-filetypes": { + "version": "3.0.14", + "resolved": "https://registry.npmjs.org/@cspell/dict-filetypes/-/dict-filetypes-3.0.14.tgz", + "integrity": "sha512-KSXaSMYYNMLLdHEnju1DyRRH3eQWPRYRnOXpuHUdOh2jC44VgQoxyMU7oB3NAhDhZKBPCihabzECsAGFbdKfEA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-flutter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-flutter/-/dict-flutter-1.1.1.tgz", + "integrity": "sha512-UlOzRcH2tNbFhZmHJN48Za/2/MEdRHl2BMkCWZBYs+30b91mWvBfzaN4IJQU7dUZtowKayVIF9FzvLZtZokc5A==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-fonts": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@cspell/dict-fonts/-/dict-fonts-4.0.5.tgz", + "integrity": "sha512-BbpkX10DUX/xzHs6lb7yzDf/LPjwYIBJHJlUXSBXDtK/1HaeS+Wqol4Mlm2+NAgZ7ikIE5DQMViTgBUY3ezNoQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-fsharp": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-fsharp/-/dict-fsharp-1.1.1.tgz", + "integrity": "sha512-imhs0u87wEA4/cYjgzS0tAyaJpwG7vwtC8UyMFbwpmtw+/bgss+osNfyqhYRyS/ehVCWL17Ewx2UPkexjKyaBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-fullstack": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@cspell/dict-fullstack/-/dict-fullstack-3.2.7.tgz", + "integrity": "sha512-IxEk2YAwAJKYCUEgEeOg3QvTL4XLlyArJElFuMQevU1dPgHgzWElFevN5lsTFnvMFA1riYsVinqJJX0BanCFEg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-gaming-terms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@cspell/dict-gaming-terms/-/dict-gaming-terms-1.1.2.tgz", + "integrity": "sha512-9XnOvaoTBscq0xuD6KTEIkk9hhdfBkkvJAIsvw3JMcnp1214OCGW8+kako5RqQ2vTZR3Tnf3pc57o7VgkM0q1Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-git": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/@cspell/dict-git/-/dict-git-3.0.7.tgz", + "integrity": "sha512-odOwVKgfxCQfiSb+nblQZc4ErXmnWEnv8XwkaI4sNJ7cNmojnvogYVeMqkXPjvfrgEcizEEA4URRD2Ms5PDk1w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-golang": { + "version": "6.0.24", + "resolved": "https://registry.npmjs.org/@cspell/dict-golang/-/dict-golang-6.0.24.tgz", + "integrity": "sha512-rY7PlC3MsHozmjrZWi0HQPUl0BVCV0+mwK0rnMT7pOIXqOe4tWCYMULDIsEk4F0gbIxb5badd2dkCPDYjLnDgA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-google": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@cspell/dict-google/-/dict-google-1.0.9.tgz", + "integrity": "sha512-biL65POqialY0i4g6crj7pR6JnBkbsPovB2WDYkj3H4TuC/QXv7Pu5pdPxeUJA6TSCHI7T5twsO4VSVyRxD9CA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-haskell": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@cspell/dict-haskell/-/dict-haskell-4.0.6.tgz", + "integrity": "sha512-ib8SA5qgftExpYNjWhpYIgvDsZ/0wvKKxSP+kuSkkak520iPvTJumEpIE+qPcmJQo4NzdKMN8nEfaeci4OcFAQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-html": { + "version": "4.0.12", + "resolved": "https://registry.npmjs.org/@cspell/dict-html/-/dict-html-4.0.12.tgz", + "integrity": "sha512-JFffQ1dDVEyJq6tCDWv0r/RqkdSnV43P2F/3jJ9rwLgdsOIXwQbXrz6QDlvQLVvNSnORH9KjDtenFTGDyzfCaA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-html-symbol-entities": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@cspell/dict-html-symbol-entities/-/dict-html-symbol-entities-4.0.4.tgz", + "integrity": "sha512-afea+0rGPDeOV9gdO06UW183Qg6wRhWVkgCFwiO3bDupAoyXRuvupbb5nUyqSTsLXIKL8u8uXQlJ9pkz07oVXw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-java": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/@cspell/dict-java/-/dict-java-5.0.12.tgz", + "integrity": "sha512-qPSNhTcl7LGJ5Qp6VN71H8zqvRQK04S08T67knMq9hTA8U7G1sTKzLmBaDOFhq17vNX/+rT+rbRYp+B5Nwza1A==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-julia": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-julia/-/dict-julia-1.1.1.tgz", + "integrity": "sha512-WylJR9TQ2cgwd5BWEOfdO3zvDB+L7kYFm0I9u0s9jKHWQ6yKmfKeMjU9oXxTBxIufhCXm92SKwwVNAC7gjv+yA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-k8s": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/@cspell/dict-k8s/-/dict-k8s-1.0.12.tgz", + "integrity": "sha512-2LcllTWgaTfYC7DmkMPOn9GsBWsA4DZdlun4po8s2ysTP7CPEnZc1ZfK6pZ2eI4TsZemlUQQ+NZxMe9/QutQxg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-kotlin": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-kotlin/-/dict-kotlin-1.1.1.tgz", + "integrity": "sha512-J3NzzfgmxRvEeOe3qUXnSJQCd38i/dpF9/t3quuWh6gXM+krsAXP75dY1CzDmS8mrJAlBdVBeAW5eAZTD8g86Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-latex": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@cspell/dict-latex/-/dict-latex-4.0.4.tgz", + "integrity": "sha512-YdTQhnTINEEm/LZgTzr9Voz4mzdOXH7YX+bSFs3hnkUHCUUtX/mhKgf1CFvZ0YNM2afjhQcmLaR9bDQVyYBvpA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-lorem-ipsum": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@cspell/dict-lorem-ipsum/-/dict-lorem-ipsum-4.0.5.tgz", + "integrity": "sha512-9a4TJYRcPWPBKkQAJ/whCu4uCAEgv/O2xAaZEI0n4y1/l18Yyx8pBKoIX5QuVXjjmKEkK7hi5SxyIsH7pFEK9Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-lua": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/@cspell/dict-lua/-/dict-lua-4.0.8.tgz", + "integrity": "sha512-N4PkgNDMu9JVsRu7JBS/3E/dvfItRgk9w5ga2dKq+JupP2Y3lojNaAVFhXISh4Y0a6qXDn2clA6nvnavQ/jjLA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-makefile": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@cspell/dict-makefile/-/dict-makefile-1.0.5.tgz", + "integrity": "sha512-4vrVt7bGiK8Rx98tfRbYo42Xo2IstJkAF4tLLDMNQLkQ86msDlYSKG1ZCk8Abg+EdNcFAjNhXIiNO+w4KflGAQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-markdown": { + "version": "2.0.12", + "resolved": "https://registry.npmjs.org/@cspell/dict-markdown/-/dict-markdown-2.0.12.tgz", + "integrity": "sha512-ufwoliPijAgWkD/ivAMC+A9QD895xKiJRF/fwwknQb7kt7NozTLKFAOBtXGPJAB4UjhGBpYEJVo2elQ0FCAH9A==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@cspell/dict-css": "^4.0.18", + "@cspell/dict-html": "^4.0.12", + "@cspell/dict-html-symbol-entities": "^4.0.4", + "@cspell/dict-typescript": "^3.2.3" + } + }, + "node_modules/@cspell/dict-monkeyc": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@cspell/dict-monkeyc/-/dict-monkeyc-1.0.11.tgz", + "integrity": "sha512-7Q1Ncu0urALI6dPTrEbSTd//UK0qjRBeaxhnm8uY5fgYNFYAG+u4gtnTIo59S6Bw5P++4H3DiIDYoQdY/lha8w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-node": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/@cspell/dict-node/-/dict-node-5.0.8.tgz", + "integrity": "sha512-AirZcN2i84ynev3p2/1NCPEhnNsHKMz9zciTngGoqpdItUb2bDt1nJBjwlsrFI78GZRph/VaqTVFwYikmncpXg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-npm": { + "version": "5.2.23", + "resolved": "https://registry.npmjs.org/@cspell/dict-npm/-/dict-npm-5.2.23.tgz", + "integrity": "sha512-cnlPGzhNkbXFLFURfjzwML2LjHMofqJkemR7lLo9Jwa9IptvzeTn4nOtJMSGfkxNrZPf/IvQ7rH5hamsUQLQ3A==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-php": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@cspell/dict-php/-/dict-php-4.1.0.tgz", + "integrity": "sha512-dTDeabyOj7eFvn2Q4Za3uVXM2+SzeFMqX8ly2P0XTo4AzbCmI2hulFD/QIADwWmwiRrInbbf8cxwFHNIYrXl4w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-powershell": { + "version": "5.0.15", + "resolved": "https://registry.npmjs.org/@cspell/dict-powershell/-/dict-powershell-5.0.15.tgz", + "integrity": "sha512-l4S5PAcvCFcVDMJShrYD0X6Huv9dcsQPlsVsBGbH38wvuN7gS7+GxZFAjTNxDmTY1wrNi1cCatSg6Pu2BW4rgg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-public-licenses": { + "version": "2.0.15", + "resolved": "https://registry.npmjs.org/@cspell/dict-public-licenses/-/dict-public-licenses-2.0.15.tgz", + "integrity": "sha512-cJEOs901H13Pfy0fl4dCD1U+xpWIMaEPq8MeYU83FfDZvellAuSo4GqWCripfIqlhns/L6+UZEIJSOZnjgy7Wg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-python": { + "version": "4.2.22", + "resolved": "https://registry.npmjs.org/@cspell/dict-python/-/dict-python-4.2.22.tgz", + "integrity": "sha512-rgF7DuleVK2lkzlw33jjEfxS2a0CU5kwAhOqf5B6XkuaPbqZ/0g0LBCdwglAGccYu7sBuvxRS8Yubk+ytSAFTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/dict-data-science": "^2.0.12" + } + }, + "node_modules/@cspell/dict-r": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-r/-/dict-r-2.1.1.tgz", + "integrity": "sha512-71Ka+yKfG4ZHEMEmDxc6+blFkeTTvgKbKAbwiwQAuKl3zpqs1Y0vUtwW2N4b3LgmSPhV3ODVY0y4m5ofqDuKMw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-ruby": { + "version": "5.0.9", + "resolved": "https://registry.npmjs.org/@cspell/dict-ruby/-/dict-ruby-5.0.9.tgz", + "integrity": "sha512-H2vMcERMcANvQshAdrVx0XoWaNX8zmmiQN11dZZTQAZaNJ0xatdJoSqY8C8uhEMW89bfgpN+NQgGuDXW2vmXEw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-rust": { + "version": "4.0.12", + "resolved": "https://registry.npmjs.org/@cspell/dict-rust/-/dict-rust-4.0.12.tgz", + "integrity": "sha512-z2QiH+q9UlNhobBJArvILRxV8Jz0pKIK7gqu4TgmEYyjiu1TvnGZ1tbYHeu9w3I/wOP6UMDoCBTty5AlYfW0mw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-scala": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/@cspell/dict-scala/-/dict-scala-5.0.8.tgz", + "integrity": "sha512-YdftVmumv8IZq9zu1gn2U7A4bfM2yj9Vaupydotyjuc+EEZZSqAafTpvW/jKLWji2TgybM1L2IhmV0s/Iv9BTw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-shell": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@cspell/dict-shell/-/dict-shell-1.1.2.tgz", + "integrity": "sha512-WqOUvnwcHK1X61wAfwyXq04cn7KYyskg90j4lLg3sGGKMW9Sq13hs91pqrjC44Q+lQLgCobrTkMDw9Wyl9nRFA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-software-terms": { + "version": "5.1.14", + "resolved": "https://registry.npmjs.org/@cspell/dict-software-terms/-/dict-software-terms-5.1.14.tgz", + "integrity": "sha512-Eu9h090hxHJiqzVFS0WxOZbYXnmb7F1RFIUEg4Nru+D/78bXVDH4b8BiKGVFNRljaieNQRAHaryzdaKJRCH6ZA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-sql": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-sql/-/dict-sql-2.2.1.tgz", + "integrity": "sha512-qDHF8MpAYCf4pWU8NKbnVGzkoxMNrFqBHyG/dgrlic5EQiKANCLELYtGlX5auIMDLmTf1inA0eNtv74tyRJ/vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-svelte": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/@cspell/dict-svelte/-/dict-svelte-1.0.7.tgz", + "integrity": "sha512-hGZsGqP0WdzKkdpeVLBivRuSNzOTvN036EBmpOwxH+FTY2DuUH7ecW+cSaMwOgmq5JFSdTcbTNFlNC8HN8lhaQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-swift": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/@cspell/dict-swift/-/dict-swift-2.0.6.tgz", + "integrity": "sha512-PnpNbrIbex2aqU1kMgwEKvCzgbkHtj3dlFLPMqW1vSniop7YxaDTtvTUO4zA++ugYAEL+UK8vYrBwDPTjjvSnA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-terraform": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@cspell/dict-terraform/-/dict-terraform-1.1.3.tgz", + "integrity": "sha512-gr6wxCydwSFyyBKhBA2xkENXtVFToheqYYGFvlMZXWjviynXmh+NK/JTvTCk/VHk3+lzbO9EEQKee6VjrAUSbA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-typescript": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/@cspell/dict-typescript/-/dict-typescript-3.2.3.tgz", + "integrity": "sha512-zXh1wYsNljQZfWWdSPYwQhpwiuW0KPW1dSd8idjMRvSD0aSvWWHoWlrMsmZeRl4qM4QCEAjua8+cjflm41cQBg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-vue": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@cspell/dict-vue/-/dict-vue-3.0.5.tgz", + "integrity": "sha512-Mqutb8jbM+kIcywuPQCCaK5qQHTdaByoEO2J9LKFy3sqAdiBogNkrplqUK0HyyRFgCfbJUgjz3N85iCMcWH0JA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-zig": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@cspell/dict-zig/-/dict-zig-1.0.0.tgz", + "integrity": "sha512-XibBIxBlVosU06+M6uHWkFeT0/pW5WajDRYdXG2CgHnq85b0TI/Ks0FuBJykmsgi2CAD3Qtx8UHFEtl/DSFnAQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dynamic-import": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/dynamic-import/-/dynamic-import-9.3.2.tgz", + "integrity": "sha512-au7FyuIHUNI2r9sO3pUBKVTeD/v7c9x/nPUStaAK1bG4rdKt4w+/jUY2IaldAraW5w29z528BboXbiV87SM1kw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/url": "9.3.2", + "import-meta-resolve": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/filetypes": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/filetypes/-/filetypes-9.3.2.tgz", + "integrity": "sha512-0bUxQlmJPRHZrRQD7adbc4lFizO8tGD/6+1cBgU3kV3+NVrpr12y4jU8twCSChhYibZyPr7bnvhkM3cQgb8RzA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/strong-weak-map": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/strong-weak-map/-/strong-weak-map-9.3.2.tgz", + "integrity": "sha512-pFcmOTWCoFMRETb9PCkCmaiZiLb5i2qOZmGH/p/tFEH8kIYhMGfhaulnXwKwS+Ke6PKceQd2YL98bGmo8hL4aQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/url": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/url/-/url-9.3.2.tgz", + "integrity": "sha512-TobUlZl7Z7VehhNOMNAg1ABuGizieseftlG94OZJ934JptOhK8TC/1o2ldKrbDH50jyt6E7rPTMV2BW/vWuTzQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/@docsearch/css": { + "version": "3.8.2", + "resolved": "https://registry.npmjs.org/@docsearch/css/-/css-3.8.2.tgz", + "integrity": "sha512-y05ayQFyUmCXze79+56v/4HpycYF3uFqB78pLPrSV5ZKAlDuIAAJNhaRi8tTdRNXh05yxX/TyNnzD6LwSM89vQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@docsearch/js": { + "version": "3.8.2", + "resolved": "https://registry.npmjs.org/@docsearch/js/-/js-3.8.2.tgz", + "integrity": "sha512-Q5wY66qHn0SwA7Taa0aDbHiJvaFJLOJyHmooQ7y8hlwwQLQ/5WwCcoX0g7ii04Qi2DJlHsd0XXzJ8Ypw9+9YmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@docsearch/react": "3.8.2", + "preact": "^10.0.0" + } + }, + "node_modules/@docsearch/react": { + "version": "3.8.2", + "resolved": "https://registry.npmjs.org/@docsearch/react/-/react-3.8.2.tgz", + "integrity": "sha512-xCRrJQlTt8N9GU0DG4ptwHRkfnSnD/YpdeaXe02iKfqs97TkZJv60yE+1eq/tjPcVnTW8dP5qLP7itifFVV5eg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/autocomplete-core": "1.17.7", + "@algolia/autocomplete-preset-algolia": "1.17.7", + "@docsearch/css": "3.8.2", + "algoliasearch": "^5.14.2" + }, + "peerDependencies": { + "@types/react": ">= 16.8.0 < 19.0.0", + "react": ">= 16.8.0 < 19.0.0", + "react-dom": ">= 16.8.0 < 19.0.0", + "search-insights": ">= 1 < 3" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + }, + "search-insights": { + "optional": true + } + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", + "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@iconify-json/simple-icons": { + "version": "1.2.59", + "resolved": "https://registry.npmjs.org/@iconify-json/simple-icons/-/simple-icons-1.2.59.tgz", + "integrity": "sha512-fYx/InyQsWFW4wVxWka3CGDJ6m/fXoTqWBSl+oA3FBXO5RhPAb6S3Y5bRgCPnrYevErH8VjAL0TZevIqlN2PhQ==", + "dev": true, + "license": "CC0-1.0", + "dependencies": { + "@iconify/types": "*" + } + }, + "node_modules/@iconify/types": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@iconify/types/-/types-2.0.0.tgz", + "integrity": "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.53.3.tgz", + "integrity": "sha512-3EhFi1FU6YL8HTUJZ51imGJWEX//ajQPfqWLI3BQq4TlvHy4X0MOr5q3D2Zof/ka0d5FNdPwZXm3Yyib/UEd+w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.53.3.tgz", + "integrity": "sha512-eoROhjcc6HbZCJr+tvVT8X4fW3/5g/WkGvvmwz/88sDtSJzO7r/blvoBDgISDiCjDRZmHpwud7h+6Q9JxFwq1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@shikijs/core": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-2.5.0.tgz", + "integrity": "sha512-uu/8RExTKtavlpH7XqnVYBrfBkUc20ngXiX9NSrBhOVZYv/7XQRKUyhtkeflY5QsxC0GbJThCerruZfsUaSldg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/engine-javascript": "2.5.0", + "@shikijs/engine-oniguruma": "2.5.0", + "@shikijs/types": "2.5.0", + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4", + "hast-util-to-html": "^9.0.4" + } + }, + "node_modules/@shikijs/engine-javascript": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-2.5.0.tgz", + "integrity": "sha512-VjnOpnQf8WuCEZtNUdjjwGUbtAVKuZkVQ/5cHy/tojVVRIRtlWMYVjyWhxOmIq05AlSOv72z7hRNRGVBgQOl0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "2.5.0", + "@shikijs/vscode-textmate": "^10.0.2", + "oniguruma-to-es": "^3.1.0" + } + }, + "node_modules/@shikijs/engine-oniguruma": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-2.5.0.tgz", + "integrity": "sha512-pGd1wRATzbo/uatrCIILlAdFVKdxImWJGQ5rFiB5VZi2ve5xj3Ax9jny8QvkaV93btQEwR/rSz5ERFpC5mKNIw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "2.5.0", + "@shikijs/vscode-textmate": "^10.0.2" + } + }, + "node_modules/@shikijs/langs": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-2.5.0.tgz", + "integrity": "sha512-Qfrrt5OsNH5R+5tJ/3uYBBZv3SuGmnRPejV9IlIbFH3HTGLDlkqgHymAlzklVmKBjAaVmkPkyikAV/sQ1wSL+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "2.5.0" + } + }, + "node_modules/@shikijs/themes": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-2.5.0.tgz", + "integrity": "sha512-wGrk+R8tJnO0VMzmUExHR+QdSaPUl/NKs+a4cQQRWyoc3YFbUzuLEi/KWK1hj+8BfHRKm2jNhhJck1dfstJpiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "2.5.0" + } + }, + "node_modules/@shikijs/transformers": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@shikijs/transformers/-/transformers-2.5.0.tgz", + "integrity": "sha512-SI494W5X60CaUwgi8u4q4m4s3YAFSxln3tzNjOSYqq54wlVgz0/NbbXEb3mdLbqMBztcmS7bVTaEd2w0qMmfeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/core": "2.5.0", + "@shikijs/types": "2.5.0" + } + }, + "node_modules/@shikijs/types": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-2.5.0.tgz", + "integrity": "sha512-ygl5yhxki9ZLNuNpPitBWvcy9fsSKKaRuO4BAlMyagszQidxcpLAr0qiW/q43DtSIDxO6hEbtYLiFZNXO/hdGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4" + } + }, + "node_modules/@shikijs/vscode-textmate": { + "version": "10.0.2", + "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz", + "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/hast": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", + "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/linkify-it": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz", + "integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/markdown-it": { + "version": "14.1.2", + "resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-14.1.2.tgz", + "integrity": "sha512-promo4eFwuiW+TfGxhi+0x3czqTYJkG8qB17ZUJiVF10Xm7NLVRSLUsfRTU/6h1e24VvRnXCx+hG7li58lkzog==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/linkify-it": "^5", + "@types/mdurl": "^2" + } + }, + "node_modules/@types/mdast": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", + "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/mdurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-2.0.0.tgz", + "integrity": "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/web-bluetooth": { + "version": "0.0.21", + "resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz", + "integrity": "sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@ungap/structured-clone": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz", + "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==", + "dev": true, + "license": "ISC" + }, + "node_modules/@vitejs/plugin-vue": { + "version": "5.2.4", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-5.2.4.tgz", + "integrity": "sha512-7Yx/SXSOcQq5HiiV3orevHUFn+pmMB4cgbEkDYgnkUWb0WfeQ/wa2yFv6D5ICiCQOVpjA7vYDXrC7AGO8yjDHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "peerDependencies": { + "vite": "^5.0.0 || ^6.0.0", + "vue": "^3.2.25" + } + }, + "node_modules/@vue/compiler-core": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.24.tgz", + "integrity": "sha512-eDl5H57AOpNakGNAkFDH+y7kTqrQpJkZFXhWZQGyx/5Wh7B1uQYvcWkvZi11BDhscPgj8N7XV3oRwiPnx1Vrig==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.28.5", + "@vue/shared": "3.5.24", + "entities": "^4.5.0", + "estree-walker": "^2.0.2", + "source-map-js": "^1.2.1" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.24.tgz", + "integrity": "sha512-1QHGAvs53gXkWdd3ZMGYuvQFXHW4ksKWPG8HP8/2BscrbZ0brw183q2oNWjMrSWImYLHxHrx1ItBQr50I/q2zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/compiler-core": "3.5.24", + "@vue/shared": "3.5.24" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.24.tgz", + "integrity": "sha512-8EG5YPRgmTB+YxYBM3VXy8zHD9SWHUJLIGPhDovo3Z8VOgvP+O7UP5vl0J4BBPWYD9vxtBabzW1EuEZ+Cqs14g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.28.5", + "@vue/compiler-core": "3.5.24", + "@vue/compiler-dom": "3.5.24", + "@vue/compiler-ssr": "3.5.24", + "@vue/shared": "3.5.24", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.21", + "postcss": "^8.5.6", + "source-map-js": "^1.2.1" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.24.tgz", + "integrity": "sha512-trOvMWNBMQ/odMRHW7Ae1CdfYx+7MuiQu62Jtu36gMLXcaoqKvAyh+P73sYG9ll+6jLB6QPovqoKGGZROzkFFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.24", + "@vue/shared": "3.5.24" + } + }, + "node_modules/@vue/devtools-api": { + "version": "7.7.9", + "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-7.7.9.tgz", + "integrity": "sha512-kIE8wvwlcZ6TJTbNeU2HQNtaxLx3a84aotTITUuL/4bzfPxzajGBOoqjMhwZJ8L9qFYDU/lAYMEEm11dnZOD6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/devtools-kit": "^7.7.9" + } + }, + "node_modules/@vue/devtools-kit": { + "version": "7.7.9", + "resolved": "https://registry.npmjs.org/@vue/devtools-kit/-/devtools-kit-7.7.9.tgz", + "integrity": "sha512-PyQ6odHSgiDVd4hnTP+aDk2X4gl2HmLDfiyEnn3/oV+ckFDuswRs4IbBT7vacMuGdwY/XemxBoh302ctbsptuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/devtools-shared": "^7.7.9", + "birpc": "^2.3.0", + "hookable": "^5.5.3", + "mitt": "^3.0.1", + "perfect-debounce": "^1.0.0", + "speakingurl": "^14.0.1", + "superjson": "^2.2.2" + } + }, + "node_modules/@vue/devtools-shared": { + "version": "7.7.9", + "resolved": "https://registry.npmjs.org/@vue/devtools-shared/-/devtools-shared-7.7.9.tgz", + "integrity": "sha512-iWAb0v2WYf0QWmxCGy0seZNDPdO3Sp5+u78ORnyeonS6MT4PC7VPrryX2BpMJrwlDeaZ6BD4vP4XKjK0SZqaeA==", + "dev": true, + "license": "MIT", + "dependencies": { + "rfdc": "^1.4.1" + } + }, + "node_modules/@vue/reactivity": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.24.tgz", + "integrity": "sha512-BM8kBhtlkkbnyl4q+HiF5R5BL0ycDPfihowulm02q3WYp2vxgPcJuZO866qa/0u3idbMntKEtVNuAUp5bw4teg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/shared": "3.5.24" + } + }, + "node_modules/@vue/runtime-core": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.24.tgz", + "integrity": "sha512-RYP/byyKDgNIqfX/gNb2PB55dJmM97jc9wyF3jK7QUInYKypK2exmZMNwnjueWwGceEkP6NChd3D2ZVEp9undQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.24", + "@vue/shared": "3.5.24" + } + }, + "node_modules/@vue/runtime-dom": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.24.tgz", + "integrity": "sha512-Z8ANhr/i0XIluonHVjbUkjvn+CyrxbXRIxR7wn7+X7xlcb7dJsfITZbkVOeJZdP8VZwfrWRsWdShH6pngMxRjw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.24", + "@vue/runtime-core": "3.5.24", + "@vue/shared": "3.5.24", + "csstype": "^3.1.3" + } + }, + "node_modules/@vue/server-renderer": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.24.tgz", + "integrity": "sha512-Yh2j2Y4G/0/4z/xJ1Bad4mxaAk++C2v4kaa8oSYTMJBJ00/ndPuxCnWeot0/7/qafQFLh5pr6xeV6SdMcE/G1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/compiler-ssr": "3.5.24", + "@vue/shared": "3.5.24" + }, + "peerDependencies": { + "vue": "3.5.24" + } + }, + "node_modules/@vue/shared": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.24.tgz", + "integrity": "sha512-9cwHL2EsJBdi8NY22pngYYWzkTDhld6fAD6jlaeloNGciNSJL6bLpbxVgXl96X00Jtc6YWQv96YA/0sxex/k1A==", + "dev": true, + "license": "MIT" + }, + "node_modules/@vueuse/core": { + "version": "12.8.2", + "resolved": "https://registry.npmjs.org/@vueuse/core/-/core-12.8.2.tgz", + "integrity": "sha512-HbvCmZdzAu3VGi/pWYm5Ut+Kd9mn1ZHnn4L5G8kOQTPs/IwIAmJoBrmYk2ckLArgMXZj0AW3n5CAejLUO+PhdQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/web-bluetooth": "^0.0.21", + "@vueuse/metadata": "12.8.2", + "@vueuse/shared": "12.8.2", + "vue": "^3.5.13" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@vueuse/integrations": { + "version": "12.8.2", + "resolved": "https://registry.npmjs.org/@vueuse/integrations/-/integrations-12.8.2.tgz", + "integrity": "sha512-fbGYivgK5uBTRt7p5F3zy6VrETlV9RtZjBqd1/HxGdjdckBgBM4ugP8LHpjolqTj14TXTxSK1ZfgPbHYyGuH7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vueuse/core": "12.8.2", + "@vueuse/shared": "12.8.2", + "vue": "^3.5.13" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "async-validator": "^4", + "axios": "^1", + "change-case": "^5", + "drauu": "^0.4", + "focus-trap": "^7", + "fuse.js": "^7", + "idb-keyval": "^6", + "jwt-decode": "^4", + "nprogress": "^0.2", + "qrcode": "^1.5", + "sortablejs": "^1", + "universal-cookie": "^7" + }, + "peerDependenciesMeta": { + "async-validator": { + "optional": true + }, + "axios": { + "optional": true + }, + "change-case": { + "optional": true + }, + "drauu": { + "optional": true + }, + "focus-trap": { + "optional": true + }, + "fuse.js": { + "optional": true + }, + "idb-keyval": { + "optional": true + }, + "jwt-decode": { + "optional": true + }, + "nprogress": { + "optional": true + }, + "qrcode": { + "optional": true + }, + "sortablejs": { + "optional": true + }, + "universal-cookie": { + "optional": true + } + } + }, + "node_modules/@vueuse/metadata": { + "version": "12.8.2", + "resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-12.8.2.tgz", + "integrity": "sha512-rAyLGEuoBJ/Il5AmFHiziCPdQzRt88VxR+Y/A/QhJ1EWtWqPBBAxTAFaSkviwEuOEZNtW8pvkPgoCZQ+HxqW1A==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@vueuse/shared": { + "version": "12.8.2", + "resolved": "https://registry.npmjs.org/@vueuse/shared/-/shared-12.8.2.tgz", + "integrity": "sha512-dznP38YzxZoNloI0qpEfpkms8knDtaoQ6Y/sfS0L7Yki4zh40LFHEhur0odJC6xTHG5dxWVPiUWBXn+wCG2s5w==", + "dev": true, + "license": "MIT", + "dependencies": { + "vue": "^3.5.13" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/algoliasearch": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-5.44.0.tgz", + "integrity": "sha512-f8IpsbdQjzTjr/4mJ/jv5UplrtyMnnciGax6/B0OnLCs2/GJTK13O4Y7Ff1AvJVAaztanH+m5nzPoUq6EAy+aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/abtesting": "1.10.0", + "@algolia/client-abtesting": "5.44.0", + "@algolia/client-analytics": "5.44.0", + "@algolia/client-common": "5.44.0", + "@algolia/client-insights": "5.44.0", + "@algolia/client-personalization": "5.44.0", + "@algolia/client-query-suggestions": "5.44.0", + "@algolia/client-search": "5.44.0", + "@algolia/ingestion": "1.44.0", + "@algolia/monitoring": "1.44.0", + "@algolia/recommend": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/array-timsort": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/array-timsort/-/array-timsort-1.0.3.tgz", + "integrity": "sha512-/+3GRL7dDAGEfM6TseQk/U+mi18TU2Ms9I3UlLdUMhz2hbvGNTKdj9xniwXfUqgYhHxRx0+8UnKkvlNwVU+cWQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/birpc": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/birpc/-/birpc-2.8.0.tgz", + "integrity": "sha512-Bz2a4qD/5GRhiHSwj30c/8kC8QGj12nNDwz3D4ErQ4Xhy35dsSDvF+RA/tWpjyU0pdGtSDiEk6B5fBGE1qNVhw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/ccount": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", + "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk-template": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/chalk-template/-/chalk-template-1.1.2.tgz", + "integrity": "sha512-2bxTP2yUH7AJj/VAXfcA+4IcWGdQ87HwBANLt5XxGTeomo8yG0y95N1um9i5StvhT/Bl0/2cARA5v1PpPXUxUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^5.2.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/chalk/chalk-template?sponsor=1" + } + }, + "node_modules/character-entities-html4": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", + "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-legacy": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", + "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/clear-module": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/clear-module/-/clear-module-4.1.2.tgz", + "integrity": "sha512-LWAxzHqdHsAZlPlEyJ2Poz6AIs384mPeqLVCru2p0BrP9G/kVGuhNyZYClLO6cXlnuJjzC8xtsJIuMjKqLXoAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^2.0.0", + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/comma-separated-tokens": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", + "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/commander": { + "version": "14.0.2", + "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.2.tgz", + "integrity": "sha512-TywoWNNRbhoD0BXs1P3ZEScW8W5iKrnbithIl0YH+uCmBd0QpPOA8yc82DS3BIE5Ma6FnBVUsJ7wVUDz4dvOWQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/comment-json": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/comment-json/-/comment-json-4.4.1.tgz", + "integrity": "sha512-r1To31BQD5060QdkC+Iheai7gHwoSZobzunqkf2/kQ6xIAfJyrKNAFUwdKvkK7Qgu7pVTKQEa7ok7Ed3ycAJgg==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-timsort": "^1.0.3", + "core-util-is": "^1.0.3", + "esprima": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/copy-anything": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-4.0.5.tgz", + "integrity": "sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-what": "^5.2.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/mesqueeb" + } + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/cspell": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell/-/cspell-9.3.2.tgz", + "integrity": "sha512-3xFyVSTYrYa/QJzLfzsCRMkMXqOsytP8E26DuGrVMJQoLPFmbOXNNtnMu4wrtr17QVloxpvutW77U4vb2L/LDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/cspell-json-reporter": "9.3.2", + "@cspell/cspell-pipe": "9.3.2", + "@cspell/cspell-types": "9.3.2", + "@cspell/dynamic-import": "9.3.2", + "@cspell/url": "9.3.2", + "chalk": "^5.6.2", + "chalk-template": "^1.1.2", + "commander": "^14.0.2", + "cspell-config-lib": "9.3.2", + "cspell-dictionary": "9.3.2", + "cspell-gitignore": "9.3.2", + "cspell-glob": "9.3.2", + "cspell-io": "9.3.2", + "cspell-lib": "9.3.2", + "fast-json-stable-stringify": "^2.1.0", + "flatted": "^3.3.3", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15" + }, + "bin": { + "cspell": "bin.mjs", + "cspell-esm": "bin.mjs" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/streetsidesoftware/cspell?sponsor=1" + } + }, + "node_modules/cspell-config-lib": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell-config-lib/-/cspell-config-lib-9.3.2.tgz", + "integrity": "sha512-zXhmA4rqgWQRTVijI+g/mgiep76TvTO4d+P3CHwcqLG57BKVzoW+jkO4qDLC+Neh4b8+CcNWEIr3w16BfuEJAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/cspell-types": "9.3.2", + "comment-json": "^4.4.1", + "smol-toml": "^1.5.2", + "yaml": "^2.8.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cspell-dictionary": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell-dictionary/-/cspell-dictionary-9.3.2.tgz", + "integrity": "sha512-E3YhOhZzZt1a+AEbFV2B3THCyZ576PDg0mDNUDrU1Y65SyIhf4DC6itfPoAb6R3FI/DI218RqWZg/FTT8lJ2gA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/cspell-pipe": "9.3.2", + "@cspell/cspell-types": "9.3.2", + "cspell-trie-lib": "9.3.2", + "fast-equals": "^5.3.3" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cspell-gitignore": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell-gitignore/-/cspell-gitignore-9.3.2.tgz", + "integrity": "sha512-G2bLR+Dfb9GX4Sdm75GfCCa9V/sQYkRbLckuCuVmJxvcDB0xfczAtb6TfAXIziF3oUI6cOB1g+PoNLWBelcK5w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/url": "9.3.2", + "cspell-glob": "9.3.2", + "cspell-io": "9.3.2" + }, + "bin": { + "cspell-gitignore": "bin.mjs" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cspell-glob": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell-glob/-/cspell-glob-9.3.2.tgz", + "integrity": "sha512-TuSupENEKyOCupOUZ3vnPxaTOghxY/rD1JIkb8e5kjzRprYVilO/rYqEk/52iLwJVd+4Npe8fNhR3KhU7u/UUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/url": "9.3.2", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cspell-grammar": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell-grammar/-/cspell-grammar-9.3.2.tgz", + "integrity": "sha512-ysonrFu9vJvF/derDlEjUfmvLeCfNOWPh00t6Yh093AKrJFoWQiyaS/5bEN/uB5/n1sa4k3ItnWvuTp3+YuZsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/cspell-pipe": "9.3.2", + "@cspell/cspell-types": "9.3.2" + }, + "bin": { + "cspell-grammar": "bin.mjs" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cspell-io": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell-io/-/cspell-io-9.3.2.tgz", + "integrity": "sha512-ahoULCp0j12TyXXmIcdO/7x65A/2mzUQO1IkOC65OXEbNT+evt0yswSO5Nr1F6kCHDuEKc46EZWwsYAzj78pMg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/cspell-service-bus": "9.3.2", + "@cspell/url": "9.3.2" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cspell-lib": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell-lib/-/cspell-lib-9.3.2.tgz", + "integrity": "sha512-kdk11kib68zNANNICuOA8h4oA9kENQUAdeX/uvT4+7eHbHHV8WSgjXm4k4o/pRIbg164UJTX/XxKb/65ftn5jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/cspell-bundled-dicts": "9.3.2", + "@cspell/cspell-pipe": "9.3.2", + "@cspell/cspell-resolver": "9.3.2", + "@cspell/cspell-types": "9.3.2", + "@cspell/dynamic-import": "9.3.2", + "@cspell/filetypes": "9.3.2", + "@cspell/strong-weak-map": "9.3.2", + "@cspell/url": "9.3.2", + "clear-module": "^4.1.2", + "cspell-config-lib": "9.3.2", + "cspell-dictionary": "9.3.2", + "cspell-glob": "9.3.2", + "cspell-grammar": "9.3.2", + "cspell-io": "9.3.2", + "cspell-trie-lib": "9.3.2", + "env-paths": "^3.0.0", + "gensequence": "^8.0.8", + "import-fresh": "^3.3.1", + "resolve-from": "^5.0.0", + "vscode-languageserver-textdocument": "^1.0.12", + "vscode-uri": "^3.1.0", + "xdg-basedir": "^5.1.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cspell-trie-lib": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell-trie-lib/-/cspell-trie-lib-9.3.2.tgz", + "integrity": "sha512-1Af7Mq9jIccFQyJl/ZCcqQbtJwuDqpQVkk8xfs/92x4OI6gW1iTVRMtsrh0RTw1HZoR8aQD7tRRCiLPf/D+UiQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/cspell-pipe": "9.3.2", + "@cspell/cspell-types": "9.3.2", + "gensequence": "^8.0.8" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/devlop": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", + "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", + "dev": true, + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/emoji-regex-xs": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex-xs/-/emoji-regex-xs-1.0.0.tgz", + "integrity": "sha512-LRlerrMYoIDrT6jgpeZ2YYl/L8EulRTt5hQcYjy5AInh7HWXKimpqx68aknBFpGL2+/IcogTcaydJEgaTmOpDg==", + "dev": true, + "license": "MIT" + }, + "node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/env-paths": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz", + "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/esbuild": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", + "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true, + "license": "BSD-2-Clause", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-equals": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.3.3.tgz", + "integrity": "sha512-/boTcHZeIAQ2r/tL11voclBHDeP9WPxLt+tyAbVSyyXuUFyh0Tne7gJZTqGbxnvj79TjLdCXLOY7UIPhyG5MTw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/flatted": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz", + "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==", + "dev": true, + "license": "ISC" + }, + "node_modules/focus-trap": { + "version": "7.6.6", + "resolved": "https://registry.npmjs.org/focus-trap/-/focus-trap-7.6.6.tgz", + "integrity": "sha512-v/Z8bvMCajtx4mEXmOo7QEsIzlIOqRXTIwgUfsFOF9gEsespdbD0AkPIka1bSXZ8Y8oZ+2IVDQZePkTfEHZl7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "tabbable": "^6.3.0" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensequence": { + "version": "8.0.8", + "resolved": "https://registry.npmjs.org/gensequence/-/gensequence-8.0.8.tgz", + "integrity": "sha512-omMVniXEXpdx/vKxGnPRoO2394Otlze28TyxECbFVyoSpZ9H3EO7lemjcB12OpQJzRW4e5tt/dL1rOxry6aMHg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/global-directory": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/global-directory/-/global-directory-4.0.1.tgz", + "integrity": "sha512-wHTUcDUoZ1H5/0iVqEudYW4/kAlN5cZ3j/bXn0Dpbizl9iaUVeWSHqiOjsgk6OW2bkLclbBjzewBz6weQ1zA2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ini": "4.1.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/hast-util-to-html": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz", + "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "ccount": "^2.0.0", + "comma-separated-tokens": "^2.0.0", + "hast-util-whitespace": "^3.0.0", + "html-void-elements": "^3.0.0", + "mdast-util-to-hast": "^13.0.0", + "property-information": "^7.0.0", + "space-separated-tokens": "^2.0.0", + "stringify-entities": "^4.0.0", + "zwitch": "^2.0.4" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-whitespace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", + "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hookable": { + "version": "5.5.3", + "resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz", + "integrity": "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/html-void-elements": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz", + "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/import-fresh/node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/import-fresh/node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/import-meta-resolve": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/import-meta-resolve/-/import-meta-resolve-4.2.0.tgz", + "integrity": "sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/ini": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ini/-/ini-4.1.1.tgz", + "integrity": "sha512-QQnnxNyfvmHFIsj7gkPcYymR8Jdw/o7mp5ZFihxn6h8Ci6fh3Dx4E1gPjpQEpIuPo9XVNY/ZUwh4BPMjGyL01g==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/is-what": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/is-what/-/is-what-5.5.0.tgz", + "integrity": "sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/mesqueeb" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/mark.js": { + "version": "8.11.1", + "resolved": "https://registry.npmjs.org/mark.js/-/mark.js-8.11.1.tgz", + "integrity": "sha512-1I+1qpDt4idfgLQG+BNWmrqku+7/2bi5nLf4YwF8y8zXvmfiTBY3PV3ZibfrjBueCByROpuBjLLFCajqkgYoLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/mdast-util-to-hast": { + "version": "13.2.1", + "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz", + "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@ungap/structured-clone": "^1.0.0", + "devlop": "^1.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "trim-lines": "^3.0.0", + "unist-util-position": "^5.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-util-character": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", + "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-encode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", + "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-sanitize-uri": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", + "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-symbol": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", + "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-types": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz", + "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/minisearch": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/minisearch/-/minisearch-7.2.0.tgz", + "integrity": "sha512-dqT2XBYUOZOiC5t2HRnwADjhNS2cecp9u+TJRiJ1Qp/f5qjkeT5APcGPjHw+bz89Ms8Jp+cG4AlE+QZ/QnDglg==", + "dev": true, + "license": "MIT" + }, + "node_modules/mitt": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz", + "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/oniguruma-to-es": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-3.1.1.tgz", + "integrity": "sha512-bUH8SDvPkH3ho3dvwJwfonjlQ4R80vjyvrU8YpxuROddv55vAEJrTuCuCVUhhsHbtlD9tGGbaNApGQckXhS8iQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex-xs": "^1.0.0", + "regex": "^6.0.1", + "regex-recursion": "^6.0.2" + } + }, + "node_modules/parent-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-2.0.0.tgz", + "integrity": "sha512-uo0Z9JJeWzv8BG+tRcapBKNJ0dro9cLyczGzulS6EfeyAdeC9sbojtW6XwvYxJkEne9En+J2XEl4zyglVeIwFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/perfect-debounce": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz", + "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.6", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", + "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/preact": { + "version": "10.27.2", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.27.2.tgz", + "integrity": "sha512-5SYSgFKSyhCbk6SrXyMpqjb5+MQBgfvEKE/OC+PujcY34sOpqtr+0AZQtPYx5IA6VxynQ7rUPCtKzyovpj9Bpg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } + }, + "node_modules/prettier": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz", + "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/property-information": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz", + "integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/regex": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/regex/-/regex-6.0.1.tgz", + "integrity": "sha512-uorlqlzAKjKQZ5P+kTJr3eeJGSVroLKoHmquUj4zHWuR+hEyNqlXsSKlYYF5F4NI6nl7tWCs0apKJ0lmfsXAPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "regex-utilities": "^2.3.0" + } + }, + "node_modules/regex-recursion": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz", + "integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==", + "dev": true, + "license": "MIT", + "dependencies": { + "regex-utilities": "^2.3.0" + } + }, + "node_modules/regex-utilities": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz", + "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==", + "dev": true, + "license": "MIT" + }, + "node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/rfdc": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "dev": true, + "license": "MIT" + }, + "node_modules/rollup": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.53.3.tgz", + "integrity": "sha512-w8GmOxZfBmKknvdXU1sdM9NHcoQejwF/4mNgj2JuEEdRaHwwF12K7e9eXn1nLZ07ad+du76mkVsyeb2rKGllsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.53.3", + "@rollup/rollup-android-arm64": "4.53.3", + "@rollup/rollup-darwin-arm64": "4.53.3", + "@rollup/rollup-darwin-x64": "4.53.3", + "@rollup/rollup-freebsd-arm64": "4.53.3", + "@rollup/rollup-freebsd-x64": "4.53.3", + "@rollup/rollup-linux-arm-gnueabihf": "4.53.3", + "@rollup/rollup-linux-arm-musleabihf": "4.53.3", + "@rollup/rollup-linux-arm64-gnu": "4.53.3", + "@rollup/rollup-linux-arm64-musl": "4.53.3", + "@rollup/rollup-linux-loong64-gnu": "4.53.3", + "@rollup/rollup-linux-ppc64-gnu": "4.53.3", + "@rollup/rollup-linux-riscv64-gnu": "4.53.3", + "@rollup/rollup-linux-riscv64-musl": "4.53.3", + "@rollup/rollup-linux-s390x-gnu": "4.53.3", + "@rollup/rollup-linux-x64-gnu": "4.53.3", + "@rollup/rollup-linux-x64-musl": "4.53.3", + "@rollup/rollup-openharmony-arm64": "4.53.3", + "@rollup/rollup-win32-arm64-msvc": "4.53.3", + "@rollup/rollup-win32-ia32-msvc": "4.53.3", + "@rollup/rollup-win32-x64-gnu": "4.53.3", + "@rollup/rollup-win32-x64-msvc": "4.53.3", + "fsevents": "~2.3.2" + } + }, + "node_modules/search-insights": { + "version": "2.17.3", + "resolved": "https://registry.npmjs.org/search-insights/-/search-insights-2.17.3.tgz", + "integrity": "sha512-RQPdCYTa8A68uM2jwxoY842xDhvx3E5LFL1LxvxCNMev4o5mLuokczhzjAgGwUZBAmOKZknArSxLKmXtIi2AxQ==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shiki": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/shiki/-/shiki-2.5.0.tgz", + "integrity": "sha512-mI//trrsaiCIPsja5CNfsyNOqgAZUb6VpJA+340toL42UpzQlXpwRV9nch69X6gaUxrr9kaOOa6e3y3uAkGFxQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/core": "2.5.0", + "@shikijs/engine-javascript": "2.5.0", + "@shikijs/engine-oniguruma": "2.5.0", + "@shikijs/langs": "2.5.0", + "@shikijs/themes": "2.5.0", + "@shikijs/types": "2.5.0", + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4" + } + }, + "node_modules/smol-toml": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.5.2.tgz", + "integrity": "sha512-QlaZEqcAH3/RtNyet1IPIYPsEWAaYyXXv1Krsi+1L/QHppjX4Ifm8MQsBISz9vE8cHicIq3clogsheili5vhaQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">= 18" + }, + "funding": { + "url": "https://github.com/sponsors/cyyynthia" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/space-separated-tokens": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", + "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/speakingurl": { + "version": "14.0.1", + "resolved": "https://registry.npmjs.org/speakingurl/-/speakingurl-14.0.1.tgz", + "integrity": "sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stringify-entities": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", + "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", + "dev": true, + "license": "MIT", + "dependencies": { + "character-entities-html4": "^2.0.0", + "character-entities-legacy": "^3.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/superjson": { + "version": "2.2.5", + "resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.5.tgz", + "integrity": "sha512-zWPTX96LVsA/eVYnqOM2+ofcdPqdS1dAF1LN4TS2/MWuUpfitd9ctTa87wt4xrYnZnkLtS69xpBdSxVBP5Rm6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "copy-anything": "^4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tabbable": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.3.0.tgz", + "integrity": "sha512-EIHvdY5bPLuWForiR/AN2Bxngzpuwn1is4asboytXtpTgsArc+WmSJKVLlhdh71u7jFcryDqB2A8lQvj78MkyQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/trim-lines": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", + "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/unist-util-is": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz", + "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-position": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz", + "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-stringify-position": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", + "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.0.0.tgz", + "integrity": "sha512-MR04uvD+07cwl/yhVuVWAtw+3GOR/knlL55Nd/wAdblk27GCVt3lqpTivy/tkJcZoNPzTwS1Y+KMojlLDhoTzg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit-parents": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", + "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", + "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile-message": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz", + "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vite": { + "version": "5.4.21", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz", + "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/vitepress": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/vitepress/-/vitepress-1.6.4.tgz", + "integrity": "sha512-+2ym1/+0VVrbhNyRoFFesVvBvHAVMZMK0rw60E3X/5349M1GuVdKeazuksqopEdvkKwKGs21Q729jX81/bkBJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@docsearch/css": "3.8.2", + "@docsearch/js": "3.8.2", + "@iconify-json/simple-icons": "^1.2.21", + "@shikijs/core": "^2.1.0", + "@shikijs/transformers": "^2.1.0", + "@shikijs/types": "^2.1.0", + "@types/markdown-it": "^14.1.2", + "@vitejs/plugin-vue": "^5.2.1", + "@vue/devtools-api": "^7.7.0", + "@vue/shared": "^3.5.13", + "@vueuse/core": "^12.4.0", + "@vueuse/integrations": "^12.4.0", + "focus-trap": "^7.6.4", + "mark.js": "8.11.1", + "minisearch": "^7.1.1", + "shiki": "^2.1.0", + "vite": "^5.4.14", + "vue": "^3.5.13" + }, + "bin": { + "vitepress": "bin/vitepress.js" + }, + "peerDependencies": { + "markdown-it-mathjax3": "^4", + "postcss": "^8" + }, + "peerDependenciesMeta": { + "markdown-it-mathjax3": { + "optional": true + }, + "postcss": { + "optional": true + } + } + }, + "node_modules/vscode-languageserver-textdocument": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.12.tgz", + "integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==", + "dev": true, + "license": "MIT" + }, + "node_modules/vscode-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz", + "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/vue": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.24.tgz", + "integrity": "sha512-uTHDOpVQTMjcGgrqFPSb8iO2m1DUvo+WbGqoXQz8Y1CeBYQ0FXf2z1gLRaBtHjlRz7zZUBHxjVB5VTLzYkvftg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.24", + "@vue/compiler-sfc": "3.5.24", + "@vue/runtime-dom": "3.5.24", + "@vue/server-renderer": "3.5.24", + "@vue/shared": "3.5.24" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/xdg-basedir": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-5.1.0.tgz", + "integrity": "sha512-GCPAHLvrIH13+c0SuacwvRYj2SxJXQ4kaVTT5xgL3kPrz56XxkF21IGhjSE1+W0aw7gpBWRGXLCPnPby6lSpmQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yaml": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.1.tgz", + "integrity": "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + } + }, + "node_modules/zwitch": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", + "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } } } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", - "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@iconify-json/simple-icons": { - "version": "1.2.59", - "resolved": "https://registry.npmjs.org/@iconify-json/simple-icons/-/simple-icons-1.2.59.tgz", - "integrity": "sha512-fYx/InyQsWFW4wVxWka3CGDJ6m/fXoTqWBSl+oA3FBXO5RhPAb6S3Y5bRgCPnrYevErH8VjAL0TZevIqlN2PhQ==", - "dev": true, - "license": "CC0-1.0", - "dependencies": { - "@iconify/types": "*" - } - }, - "node_modules/@iconify/types": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@iconify/types/-/types-2.0.0.tgz", - "integrity": "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", - "dev": true, - "license": "MIT" - }, - "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.53.3.tgz", - "integrity": "sha512-3EhFi1FU6YL8HTUJZ51imGJWEX//ajQPfqWLI3BQq4TlvHy4X0MOr5q3D2Zof/ka0d5FNdPwZXm3Yyib/UEd+w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.53.3.tgz", - "integrity": "sha512-eoROhjcc6HbZCJr+tvVT8X4fW3/5g/WkGvvmwz/88sDtSJzO7r/blvoBDgISDiCjDRZmHpwud7h+6Q9JxFwq1Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@shikijs/core": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-2.5.0.tgz", - "integrity": "sha512-uu/8RExTKtavlpH7XqnVYBrfBkUc20ngXiX9NSrBhOVZYv/7XQRKUyhtkeflY5QsxC0GbJThCerruZfsUaSldg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/engine-javascript": "2.5.0", - "@shikijs/engine-oniguruma": "2.5.0", - "@shikijs/types": "2.5.0", - "@shikijs/vscode-textmate": "^10.0.2", - "@types/hast": "^3.0.4", - "hast-util-to-html": "^9.0.4" - } - }, - "node_modules/@shikijs/engine-javascript": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-2.5.0.tgz", - "integrity": "sha512-VjnOpnQf8WuCEZtNUdjjwGUbtAVKuZkVQ/5cHy/tojVVRIRtlWMYVjyWhxOmIq05AlSOv72z7hRNRGVBgQOl0w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/types": "2.5.0", - "@shikijs/vscode-textmate": "^10.0.2", - "oniguruma-to-es": "^3.1.0" - } - }, - "node_modules/@shikijs/engine-oniguruma": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-2.5.0.tgz", - "integrity": "sha512-pGd1wRATzbo/uatrCIILlAdFVKdxImWJGQ5rFiB5VZi2ve5xj3Ax9jny8QvkaV93btQEwR/rSz5ERFpC5mKNIw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/types": "2.5.0", - "@shikijs/vscode-textmate": "^10.0.2" - } - }, - "node_modules/@shikijs/langs": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-2.5.0.tgz", - "integrity": "sha512-Qfrrt5OsNH5R+5tJ/3uYBBZv3SuGmnRPejV9IlIbFH3HTGLDlkqgHymAlzklVmKBjAaVmkPkyikAV/sQ1wSL+w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/types": "2.5.0" - } - }, - "node_modules/@shikijs/themes": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-2.5.0.tgz", - "integrity": "sha512-wGrk+R8tJnO0VMzmUExHR+QdSaPUl/NKs+a4cQQRWyoc3YFbUzuLEi/KWK1hj+8BfHRKm2jNhhJck1dfstJpiw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/types": "2.5.0" - } - }, - "node_modules/@shikijs/transformers": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/transformers/-/transformers-2.5.0.tgz", - "integrity": "sha512-SI494W5X60CaUwgi8u4q4m4s3YAFSxln3tzNjOSYqq54wlVgz0/NbbXEb3mdLbqMBztcmS7bVTaEd2w0qMmfeg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/core": "2.5.0", - "@shikijs/types": "2.5.0" - } - }, - "node_modules/@shikijs/types": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-2.5.0.tgz", - "integrity": "sha512-ygl5yhxki9ZLNuNpPitBWvcy9fsSKKaRuO4BAlMyagszQidxcpLAr0qiW/q43DtSIDxO6hEbtYLiFZNXO/hdGw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/vscode-textmate": "^10.0.2", - "@types/hast": "^3.0.4" - } - }, - "node_modules/@shikijs/vscode-textmate": { - "version": "10.0.2", - "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz", - "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/estree": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", - "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/hast": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", - "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "*" - } - }, - "node_modules/@types/linkify-it": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz", - "integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/markdown-it": { - "version": "14.1.2", - "resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-14.1.2.tgz", - "integrity": "sha512-promo4eFwuiW+TfGxhi+0x3czqTYJkG8qB17ZUJiVF10Xm7NLVRSLUsfRTU/6h1e24VvRnXCx+hG7li58lkzog==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/linkify-it": "^5", - "@types/mdurl": "^2" - } - }, - "node_modules/@types/mdast": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", - "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "*" - } - }, - "node_modules/@types/mdurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-2.0.0.tgz", - "integrity": "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/unist": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", - "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/web-bluetooth": { - "version": "0.0.21", - "resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz", - "integrity": "sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@ungap/structured-clone": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz", - "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==", - "dev": true, - "license": "ISC" - }, - "node_modules/@vitejs/plugin-vue": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-5.2.4.tgz", - "integrity": "sha512-7Yx/SXSOcQq5HiiV3orevHUFn+pmMB4cgbEkDYgnkUWb0WfeQ/wa2yFv6D5ICiCQOVpjA7vYDXrC7AGO8yjDHA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.0.0 || >=20.0.0" - }, - "peerDependencies": { - "vite": "^5.0.0 || ^6.0.0", - "vue": "^3.2.25" - } - }, - "node_modules/@vue/compiler-core": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.24.tgz", - "integrity": "sha512-eDl5H57AOpNakGNAkFDH+y7kTqrQpJkZFXhWZQGyx/5Wh7B1uQYvcWkvZi11BDhscPgj8N7XV3oRwiPnx1Vrig==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.28.5", - "@vue/shared": "3.5.24", - "entities": "^4.5.0", - "estree-walker": "^2.0.2", - "source-map-js": "^1.2.1" - } - }, - "node_modules/@vue/compiler-dom": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.24.tgz", - "integrity": "sha512-1QHGAvs53gXkWdd3ZMGYuvQFXHW4ksKWPG8HP8/2BscrbZ0brw183q2oNWjMrSWImYLHxHrx1ItBQr50I/q2zw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/compiler-core": "3.5.24", - "@vue/shared": "3.5.24" - } - }, - "node_modules/@vue/compiler-sfc": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.24.tgz", - "integrity": "sha512-8EG5YPRgmTB+YxYBM3VXy8zHD9SWHUJLIGPhDovo3Z8VOgvP+O7UP5vl0J4BBPWYD9vxtBabzW1EuEZ+Cqs14g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.28.5", - "@vue/compiler-core": "3.5.24", - "@vue/compiler-dom": "3.5.24", - "@vue/compiler-ssr": "3.5.24", - "@vue/shared": "3.5.24", - "estree-walker": "^2.0.2", - "magic-string": "^0.30.21", - "postcss": "^8.5.6", - "source-map-js": "^1.2.1" - } - }, - "node_modules/@vue/compiler-ssr": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.24.tgz", - "integrity": "sha512-trOvMWNBMQ/odMRHW7Ae1CdfYx+7MuiQu62Jtu36gMLXcaoqKvAyh+P73sYG9ll+6jLB6QPovqoKGGZROzkFFg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/compiler-dom": "3.5.24", - "@vue/shared": "3.5.24" - } - }, - "node_modules/@vue/devtools-api": { - "version": "7.7.9", - "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-7.7.9.tgz", - "integrity": "sha512-kIE8wvwlcZ6TJTbNeU2HQNtaxLx3a84aotTITUuL/4bzfPxzajGBOoqjMhwZJ8L9qFYDU/lAYMEEm11dnZOD6g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/devtools-kit": "^7.7.9" - } - }, - "node_modules/@vue/devtools-kit": { - "version": "7.7.9", - "resolved": "https://registry.npmjs.org/@vue/devtools-kit/-/devtools-kit-7.7.9.tgz", - "integrity": "sha512-PyQ6odHSgiDVd4hnTP+aDk2X4gl2HmLDfiyEnn3/oV+ckFDuswRs4IbBT7vacMuGdwY/XemxBoh302ctbsptuA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/devtools-shared": "^7.7.9", - "birpc": "^2.3.0", - "hookable": "^5.5.3", - "mitt": "^3.0.1", - "perfect-debounce": "^1.0.0", - "speakingurl": "^14.0.1", - "superjson": "^2.2.2" - } - }, - "node_modules/@vue/devtools-shared": { - "version": "7.7.9", - "resolved": "https://registry.npmjs.org/@vue/devtools-shared/-/devtools-shared-7.7.9.tgz", - "integrity": "sha512-iWAb0v2WYf0QWmxCGy0seZNDPdO3Sp5+u78ORnyeonS6MT4PC7VPrryX2BpMJrwlDeaZ6BD4vP4XKjK0SZqaeA==", - "dev": true, - "license": "MIT", - "dependencies": { - "rfdc": "^1.4.1" - } - }, - "node_modules/@vue/reactivity": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.24.tgz", - "integrity": "sha512-BM8kBhtlkkbnyl4q+HiF5R5BL0ycDPfihowulm02q3WYp2vxgPcJuZO866qa/0u3idbMntKEtVNuAUp5bw4teg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/shared": "3.5.24" - } - }, - "node_modules/@vue/runtime-core": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.24.tgz", - "integrity": "sha512-RYP/byyKDgNIqfX/gNb2PB55dJmM97jc9wyF3jK7QUInYKypK2exmZMNwnjueWwGceEkP6NChd3D2ZVEp9undQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/reactivity": "3.5.24", - "@vue/shared": "3.5.24" - } - }, - "node_modules/@vue/runtime-dom": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.24.tgz", - "integrity": "sha512-Z8ANhr/i0XIluonHVjbUkjvn+CyrxbXRIxR7wn7+X7xlcb7dJsfITZbkVOeJZdP8VZwfrWRsWdShH6pngMxRjw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/reactivity": "3.5.24", - "@vue/runtime-core": "3.5.24", - "@vue/shared": "3.5.24", - "csstype": "^3.1.3" - } - }, - "node_modules/@vue/server-renderer": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.24.tgz", - "integrity": "sha512-Yh2j2Y4G/0/4z/xJ1Bad4mxaAk++C2v4kaa8oSYTMJBJ00/ndPuxCnWeot0/7/qafQFLh5pr6xeV6SdMcE/G1w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/compiler-ssr": "3.5.24", - "@vue/shared": "3.5.24" - }, - "peerDependencies": { - "vue": "3.5.24" - } - }, - "node_modules/@vue/shared": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.24.tgz", - "integrity": "sha512-9cwHL2EsJBdi8NY22pngYYWzkTDhld6fAD6jlaeloNGciNSJL6bLpbxVgXl96X00Jtc6YWQv96YA/0sxex/k1A==", - "dev": true, - "license": "MIT" - }, - "node_modules/@vueuse/core": { - "version": "12.8.2", - "resolved": "https://registry.npmjs.org/@vueuse/core/-/core-12.8.2.tgz", - "integrity": "sha512-HbvCmZdzAu3VGi/pWYm5Ut+Kd9mn1ZHnn4L5G8kOQTPs/IwIAmJoBrmYk2ckLArgMXZj0AW3n5CAejLUO+PhdQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/web-bluetooth": "^0.0.21", - "@vueuse/metadata": "12.8.2", - "@vueuse/shared": "12.8.2", - "vue": "^3.5.13" - }, - "funding": { - "url": "https://github.com/sponsors/antfu" - } - }, - "node_modules/@vueuse/integrations": { - "version": "12.8.2", - "resolved": "https://registry.npmjs.org/@vueuse/integrations/-/integrations-12.8.2.tgz", - "integrity": "sha512-fbGYivgK5uBTRt7p5F3zy6VrETlV9RtZjBqd1/HxGdjdckBgBM4ugP8LHpjolqTj14TXTxSK1ZfgPbHYyGuH7g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vueuse/core": "12.8.2", - "@vueuse/shared": "12.8.2", - "vue": "^3.5.13" - }, - "funding": { - "url": "https://github.com/sponsors/antfu" - }, - "peerDependencies": { - "async-validator": "^4", - "axios": "^1", - "change-case": "^5", - "drauu": "^0.4", - "focus-trap": "^7", - "fuse.js": "^7", - "idb-keyval": "^6", - "jwt-decode": "^4", - "nprogress": "^0.2", - "qrcode": "^1.5", - "sortablejs": "^1", - "universal-cookie": "^7" - }, - "peerDependenciesMeta": { - "async-validator": { - "optional": true - }, - "axios": { - "optional": true - }, - "change-case": { - "optional": true - }, - "drauu": { - "optional": true - }, - "focus-trap": { - "optional": true - }, - "fuse.js": { - "optional": true - }, - "idb-keyval": { - "optional": true - }, - "jwt-decode": { - "optional": true - }, - "nprogress": { - "optional": true - }, - "qrcode": { - "optional": true - }, - "sortablejs": { - "optional": true - }, - "universal-cookie": { - "optional": true - } - } - }, - "node_modules/@vueuse/metadata": { - "version": "12.8.2", - "resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-12.8.2.tgz", - "integrity": "sha512-rAyLGEuoBJ/Il5AmFHiziCPdQzRt88VxR+Y/A/QhJ1EWtWqPBBAxTAFaSkviwEuOEZNtW8pvkPgoCZQ+HxqW1A==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/antfu" - } - }, - "node_modules/@vueuse/shared": { - "version": "12.8.2", - "resolved": "https://registry.npmjs.org/@vueuse/shared/-/shared-12.8.2.tgz", - "integrity": "sha512-dznP38YzxZoNloI0qpEfpkms8knDtaoQ6Y/sfS0L7Yki4zh40LFHEhur0odJC6xTHG5dxWVPiUWBXn+wCG2s5w==", - "dev": true, - "license": "MIT", - "dependencies": { - "vue": "^3.5.13" - }, - "funding": { - "url": "https://github.com/sponsors/antfu" - } - }, - "node_modules/algoliasearch": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-5.44.0.tgz", - "integrity": "sha512-f8IpsbdQjzTjr/4mJ/jv5UplrtyMnnciGax6/B0OnLCs2/GJTK13O4Y7Ff1AvJVAaztanH+m5nzPoUq6EAy+aA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/abtesting": "1.10.0", - "@algolia/client-abtesting": "5.44.0", - "@algolia/client-analytics": "5.44.0", - "@algolia/client-common": "5.44.0", - "@algolia/client-insights": "5.44.0", - "@algolia/client-personalization": "5.44.0", - "@algolia/client-query-suggestions": "5.44.0", - "@algolia/client-search": "5.44.0", - "@algolia/ingestion": "1.44.0", - "@algolia/monitoring": "1.44.0", - "@algolia/recommend": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/array-timsort": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/array-timsort/-/array-timsort-1.0.3.tgz", - "integrity": "sha512-/+3GRL7dDAGEfM6TseQk/U+mi18TU2Ms9I3UlLdUMhz2hbvGNTKdj9xniwXfUqgYhHxRx0+8UnKkvlNwVU+cWQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/birpc": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/birpc/-/birpc-2.8.0.tgz", - "integrity": "sha512-Bz2a4qD/5GRhiHSwj30c/8kC8QGj12nNDwz3D4ErQ4Xhy35dsSDvF+RA/tWpjyU0pdGtSDiEk6B5fBGE1qNVhw==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/antfu" - } - }, - "node_modules/callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/ccount": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", - "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/chalk": { - "version": "5.6.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", - "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.17.0 || ^14.13 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/chalk-template": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/chalk-template/-/chalk-template-1.1.2.tgz", - "integrity": "sha512-2bxTP2yUH7AJj/VAXfcA+4IcWGdQ87HwBANLt5XxGTeomo8yG0y95N1um9i5StvhT/Bl0/2cARA5v1PpPXUxUA==", - "dev": true, - "license": "MIT", - "dependencies": { - "chalk": "^5.2.0" - }, - "engines": { - "node": ">=14.16" - }, - "funding": { - "url": "https://github.com/chalk/chalk-template?sponsor=1" - } - }, - "node_modules/character-entities-html4": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", - "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/character-entities-legacy": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", - "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/clear-module": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/clear-module/-/clear-module-4.1.2.tgz", - "integrity": "sha512-LWAxzHqdHsAZlPlEyJ2Poz6AIs384mPeqLVCru2p0BrP9G/kVGuhNyZYClLO6cXlnuJjzC8xtsJIuMjKqLXoAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "parent-module": "^2.0.0", - "resolve-from": "^5.0.0" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/comma-separated-tokens": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", - "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/commander": { - "version": "14.0.2", - "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.2.tgz", - "integrity": "sha512-TywoWNNRbhoD0BXs1P3ZEScW8W5iKrnbithIl0YH+uCmBd0QpPOA8yc82DS3BIE5Ma6FnBVUsJ7wVUDz4dvOWQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/comment-json": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/comment-json/-/comment-json-4.4.1.tgz", - "integrity": "sha512-r1To31BQD5060QdkC+Iheai7gHwoSZobzunqkf2/kQ6xIAfJyrKNAFUwdKvkK7Qgu7pVTKQEa7ok7Ed3ycAJgg==", - "dev": true, - "license": "MIT", - "dependencies": { - "array-timsort": "^1.0.3", - "core-util-is": "^1.0.3", - "esprima": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/copy-anything": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-4.0.5.tgz", - "integrity": "sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-what": "^5.2.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/mesqueeb" - } - }, - "node_modules/core-util-is": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", - "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/cspell": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell/-/cspell-9.3.2.tgz", - "integrity": "sha512-3xFyVSTYrYa/QJzLfzsCRMkMXqOsytP8E26DuGrVMJQoLPFmbOXNNtnMu4wrtr17QVloxpvutW77U4vb2L/LDQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/cspell-json-reporter": "9.3.2", - "@cspell/cspell-pipe": "9.3.2", - "@cspell/cspell-types": "9.3.2", - "@cspell/dynamic-import": "9.3.2", - "@cspell/url": "9.3.2", - "chalk": "^5.6.2", - "chalk-template": "^1.1.2", - "commander": "^14.0.2", - "cspell-config-lib": "9.3.2", - "cspell-dictionary": "9.3.2", - "cspell-gitignore": "9.3.2", - "cspell-glob": "9.3.2", - "cspell-io": "9.3.2", - "cspell-lib": "9.3.2", - "fast-json-stable-stringify": "^2.1.0", - "flatted": "^3.3.3", - "semver": "^7.7.3", - "tinyglobby": "^0.2.15" - }, - "bin": { - "cspell": "bin.mjs", - "cspell-esm": "bin.mjs" - }, - "engines": { - "node": ">=20" - }, - "funding": { - "url": "https://github.com/streetsidesoftware/cspell?sponsor=1" - } - }, - "node_modules/cspell-config-lib": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell-config-lib/-/cspell-config-lib-9.3.2.tgz", - "integrity": "sha512-zXhmA4rqgWQRTVijI+g/mgiep76TvTO4d+P3CHwcqLG57BKVzoW+jkO4qDLC+Neh4b8+CcNWEIr3w16BfuEJAA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/cspell-types": "9.3.2", - "comment-json": "^4.4.1", - "smol-toml": "^1.5.2", - "yaml": "^2.8.1" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/cspell-dictionary": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell-dictionary/-/cspell-dictionary-9.3.2.tgz", - "integrity": "sha512-E3YhOhZzZt1a+AEbFV2B3THCyZ576PDg0mDNUDrU1Y65SyIhf4DC6itfPoAb6R3FI/DI218RqWZg/FTT8lJ2gA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/cspell-pipe": "9.3.2", - "@cspell/cspell-types": "9.3.2", - "cspell-trie-lib": "9.3.2", - "fast-equals": "^5.3.3" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/cspell-gitignore": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell-gitignore/-/cspell-gitignore-9.3.2.tgz", - "integrity": "sha512-G2bLR+Dfb9GX4Sdm75GfCCa9V/sQYkRbLckuCuVmJxvcDB0xfczAtb6TfAXIziF3oUI6cOB1g+PoNLWBelcK5w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/url": "9.3.2", - "cspell-glob": "9.3.2", - "cspell-io": "9.3.2" - }, - "bin": { - "cspell-gitignore": "bin.mjs" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/cspell-glob": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell-glob/-/cspell-glob-9.3.2.tgz", - "integrity": "sha512-TuSupENEKyOCupOUZ3vnPxaTOghxY/rD1JIkb8e5kjzRprYVilO/rYqEk/52iLwJVd+4Npe8fNhR3KhU7u/UUg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/url": "9.3.2", - "picomatch": "^4.0.3" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/cspell-grammar": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell-grammar/-/cspell-grammar-9.3.2.tgz", - "integrity": "sha512-ysonrFu9vJvF/derDlEjUfmvLeCfNOWPh00t6Yh093AKrJFoWQiyaS/5bEN/uB5/n1sa4k3ItnWvuTp3+YuZsA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/cspell-pipe": "9.3.2", - "@cspell/cspell-types": "9.3.2" - }, - "bin": { - "cspell-grammar": "bin.mjs" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/cspell-io": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell-io/-/cspell-io-9.3.2.tgz", - "integrity": "sha512-ahoULCp0j12TyXXmIcdO/7x65A/2mzUQO1IkOC65OXEbNT+evt0yswSO5Nr1F6kCHDuEKc46EZWwsYAzj78pMg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/cspell-service-bus": "9.3.2", - "@cspell/url": "9.3.2" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/cspell-lib": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell-lib/-/cspell-lib-9.3.2.tgz", - "integrity": "sha512-kdk11kib68zNANNICuOA8h4oA9kENQUAdeX/uvT4+7eHbHHV8WSgjXm4k4o/pRIbg164UJTX/XxKb/65ftn5jw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/cspell-bundled-dicts": "9.3.2", - "@cspell/cspell-pipe": "9.3.2", - "@cspell/cspell-resolver": "9.3.2", - "@cspell/cspell-types": "9.3.2", - "@cspell/dynamic-import": "9.3.2", - "@cspell/filetypes": "9.3.2", - "@cspell/strong-weak-map": "9.3.2", - "@cspell/url": "9.3.2", - "clear-module": "^4.1.2", - "cspell-config-lib": "9.3.2", - "cspell-dictionary": "9.3.2", - "cspell-glob": "9.3.2", - "cspell-grammar": "9.3.2", - "cspell-io": "9.3.2", - "cspell-trie-lib": "9.3.2", - "env-paths": "^3.0.0", - "gensequence": "^8.0.8", - "import-fresh": "^3.3.1", - "resolve-from": "^5.0.0", - "vscode-languageserver-textdocument": "^1.0.12", - "vscode-uri": "^3.1.0", - "xdg-basedir": "^5.1.0" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/cspell-trie-lib": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell-trie-lib/-/cspell-trie-lib-9.3.2.tgz", - "integrity": "sha512-1Af7Mq9jIccFQyJl/ZCcqQbtJwuDqpQVkk8xfs/92x4OI6gW1iTVRMtsrh0RTw1HZoR8aQD7tRRCiLPf/D+UiQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/cspell-pipe": "9.3.2", - "@cspell/cspell-types": "9.3.2", - "gensequence": "^8.0.8" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/csstype": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", - "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/dequal": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", - "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/devlop": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", - "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", - "dev": true, - "license": "MIT", - "dependencies": { - "dequal": "^2.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/emoji-regex-xs": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex-xs/-/emoji-regex-xs-1.0.0.tgz", - "integrity": "sha512-LRlerrMYoIDrT6jgpeZ2YYl/L8EulRTt5hQcYjy5AInh7HWXKimpqx68aknBFpGL2+/IcogTcaydJEgaTmOpDg==", - "dev": true, - "license": "MIT" - }, - "node_modules/entities": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", - "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, - "node_modules/env-paths": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz", - "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/esbuild": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", - "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=12" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.21.5", - "@esbuild/android-arm": "0.21.5", - "@esbuild/android-arm64": "0.21.5", - "@esbuild/android-x64": "0.21.5", - "@esbuild/darwin-arm64": "0.21.5", - "@esbuild/darwin-x64": "0.21.5", - "@esbuild/freebsd-arm64": "0.21.5", - "@esbuild/freebsd-x64": "0.21.5", - "@esbuild/linux-arm": "0.21.5", - "@esbuild/linux-arm64": "0.21.5", - "@esbuild/linux-ia32": "0.21.5", - "@esbuild/linux-loong64": "0.21.5", - "@esbuild/linux-mips64el": "0.21.5", - "@esbuild/linux-ppc64": "0.21.5", - "@esbuild/linux-riscv64": "0.21.5", - "@esbuild/linux-s390x": "0.21.5", - "@esbuild/linux-x64": "0.21.5", - "@esbuild/netbsd-x64": "0.21.5", - "@esbuild/openbsd-x64": "0.21.5", - "@esbuild/sunos-x64": "0.21.5", - "@esbuild/win32-arm64": "0.21.5", - "@esbuild/win32-ia32": "0.21.5", - "@esbuild/win32-x64": "0.21.5" - } - }, - "node_modules/esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true, - "license": "BSD-2-Clause", - "bin": { - "esparse": "bin/esparse.js", - "esvalidate": "bin/esvalidate.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/estree-walker": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", - "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-equals": { - "version": "5.3.3", - "resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.3.3.tgz", - "integrity": "sha512-/boTcHZeIAQ2r/tL11voclBHDeP9WPxLt+tyAbVSyyXuUFyh0Tne7gJZTqGbxnvj79TjLdCXLOY7UIPhyG5MTw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/fast-json-stable-stringify": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "dev": true, - "license": "MIT" - }, - "node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "picomatch": "^3 || ^4" - }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } - } - }, - "node_modules/flatted": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz", - "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==", - "dev": true, - "license": "ISC" - }, - "node_modules/focus-trap": { - "version": "7.6.6", - "resolved": "https://registry.npmjs.org/focus-trap/-/focus-trap-7.6.6.tgz", - "integrity": "sha512-v/Z8bvMCajtx4mEXmOo7QEsIzlIOqRXTIwgUfsFOF9gEsespdbD0AkPIka1bSXZ8Y8oZ+2IVDQZePkTfEHZl7Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "tabbable": "^6.3.0" - } - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/gensequence": { - "version": "8.0.8", - "resolved": "https://registry.npmjs.org/gensequence/-/gensequence-8.0.8.tgz", - "integrity": "sha512-omMVniXEXpdx/vKxGnPRoO2394Otlze28TyxECbFVyoSpZ9H3EO7lemjcB12OpQJzRW4e5tt/dL1rOxry6aMHg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/global-directory": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/global-directory/-/global-directory-4.0.1.tgz", - "integrity": "sha512-wHTUcDUoZ1H5/0iVqEudYW4/kAlN5cZ3j/bXn0Dpbizl9iaUVeWSHqiOjsgk6OW2bkLclbBjzewBz6weQ1zA2Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "ini": "4.1.1" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/hast-util-to-html": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz", - "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/hast": "^3.0.0", - "@types/unist": "^3.0.0", - "ccount": "^2.0.0", - "comma-separated-tokens": "^2.0.0", - "hast-util-whitespace": "^3.0.0", - "html-void-elements": "^3.0.0", - "mdast-util-to-hast": "^13.0.0", - "property-information": "^7.0.0", - "space-separated-tokens": "^2.0.0", - "stringify-entities": "^4.0.0", - "zwitch": "^2.0.4" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/hast-util-whitespace": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", - "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/hast": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/hookable": { - "version": "5.5.3", - "resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz", - "integrity": "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/html-void-elements": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz", - "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/import-fresh": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", - "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "parent-module": "^1.0.0", - "resolve-from": "^4.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/import-fresh/node_modules/parent-module": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", - "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", - "dev": true, - "license": "MIT", - "dependencies": { - "callsites": "^3.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/import-fresh/node_modules/resolve-from": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/import-meta-resolve": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/import-meta-resolve/-/import-meta-resolve-4.2.0.tgz", - "integrity": "sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/ini": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/ini/-/ini-4.1.1.tgz", - "integrity": "sha512-QQnnxNyfvmHFIsj7gkPcYymR8Jdw/o7mp5ZFihxn6h8Ci6fh3Dx4E1gPjpQEpIuPo9XVNY/ZUwh4BPMjGyL01g==", - "dev": true, - "license": "ISC", - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/is-what": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/is-what/-/is-what-5.5.0.tgz", - "integrity": "sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/mesqueeb" - } - }, - "node_modules/magic-string": { - "version": "0.30.21", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", - "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.5" - } - }, - "node_modules/mark.js": { - "version": "8.11.1", - "resolved": "https://registry.npmjs.org/mark.js/-/mark.js-8.11.1.tgz", - "integrity": "sha512-1I+1qpDt4idfgLQG+BNWmrqku+7/2bi5nLf4YwF8y8zXvmfiTBY3PV3ZibfrjBueCByROpuBjLLFCajqkgYoLQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/mdast-util-to-hast": { - "version": "13.2.1", - "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz", - "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/hast": "^3.0.0", - "@types/mdast": "^4.0.0", - "@ungap/structured-clone": "^1.0.0", - "devlop": "^1.0.0", - "micromark-util-sanitize-uri": "^2.0.0", - "trim-lines": "^3.0.0", - "unist-util-position": "^5.0.0", - "unist-util-visit": "^5.0.0", - "vfile": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/micromark-util-character": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", - "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==", - "dev": true, - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-util-encode": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", - "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==", - "dev": true, - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT" - }, - "node_modules/micromark-util-sanitize-uri": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", - "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==", - "dev": true, - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-character": "^2.0.0", - "micromark-util-encode": "^2.0.0", - "micromark-util-symbol": "^2.0.0" - } - }, - "node_modules/micromark-util-symbol": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", - "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==", - "dev": true, - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT" - }, - "node_modules/micromark-util-types": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz", - "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==", - "dev": true, - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT" - }, - "node_modules/minisearch": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/minisearch/-/minisearch-7.2.0.tgz", - "integrity": "sha512-dqT2XBYUOZOiC5t2HRnwADjhNS2cecp9u+TJRiJ1Qp/f5qjkeT5APcGPjHw+bz89Ms8Jp+cG4AlE+QZ/QnDglg==", - "dev": true, - "license": "MIT" - }, - "node_modules/mitt": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz", - "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==", - "dev": true, - "license": "MIT" - }, - "node_modules/nanoid": { - "version": "3.3.11", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", - "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/oniguruma-to-es": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-3.1.1.tgz", - "integrity": "sha512-bUH8SDvPkH3ho3dvwJwfonjlQ4R80vjyvrU8YpxuROddv55vAEJrTuCuCVUhhsHbtlD9tGGbaNApGQckXhS8iQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex-xs": "^1.0.0", - "regex": "^6.0.1", - "regex-recursion": "^6.0.2" - } - }, - "node_modules/parent-module": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-2.0.0.tgz", - "integrity": "sha512-uo0Z9JJeWzv8BG+tRcapBKNJ0dro9cLyczGzulS6EfeyAdeC9sbojtW6XwvYxJkEne9En+J2XEl4zyglVeIwFg==", - "dev": true, - "license": "MIT", - "dependencies": { - "callsites": "^3.1.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/perfect-debounce": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz", - "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==", - "dev": true, - "license": "MIT" - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true, - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", - "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/postcss": { - "version": "8.5.6", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", - "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.11", - "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/preact": { - "version": "10.27.2", - "resolved": "https://registry.npmjs.org/preact/-/preact-10.27.2.tgz", - "integrity": "sha512-5SYSgFKSyhCbk6SrXyMpqjb5+MQBgfvEKE/OC+PujcY34sOpqtr+0AZQtPYx5IA6VxynQ7rUPCtKzyovpj9Bpg==", - "dev": true, - "license": "MIT", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/preact" - } - }, - "node_modules/prettier": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz", - "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==", - "dev": true, - "license": "MIT", - "bin": { - "prettier": "bin/prettier.cjs" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/prettier/prettier?sponsor=1" - } - }, - "node_modules/property-information": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz", - "integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/regex": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/regex/-/regex-6.0.1.tgz", - "integrity": "sha512-uorlqlzAKjKQZ5P+kTJr3eeJGSVroLKoHmquUj4zHWuR+hEyNqlXsSKlYYF5F4NI6nl7tWCs0apKJ0lmfsXAPA==", - "dev": true, - "license": "MIT", - "dependencies": { - "regex-utilities": "^2.3.0" - } - }, - "node_modules/regex-recursion": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz", - "integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==", - "dev": true, - "license": "MIT", - "dependencies": { - "regex-utilities": "^2.3.0" - } - }, - "node_modules/regex-utilities": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz", - "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==", - "dev": true, - "license": "MIT" - }, - "node_modules/resolve-from": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/rfdc": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", - "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", - "dev": true, - "license": "MIT" - }, - "node_modules/rollup": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.53.3.tgz", - "integrity": "sha512-w8GmOxZfBmKknvdXU1sdM9NHcoQejwF/4mNgj2JuEEdRaHwwF12K7e9eXn1nLZ07ad+du76mkVsyeb2rKGllsA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "1.0.8" - }, - "bin": { - "rollup": "dist/bin/rollup" - }, - "engines": { - "node": ">=18.0.0", - "npm": ">=8.0.0" - }, - "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.53.3", - "@rollup/rollup-android-arm64": "4.53.3", - "@rollup/rollup-darwin-arm64": "4.53.3", - "@rollup/rollup-darwin-x64": "4.53.3", - "@rollup/rollup-freebsd-arm64": "4.53.3", - "@rollup/rollup-freebsd-x64": "4.53.3", - "@rollup/rollup-linux-arm-gnueabihf": "4.53.3", - "@rollup/rollup-linux-arm-musleabihf": "4.53.3", - "@rollup/rollup-linux-arm64-gnu": "4.53.3", - "@rollup/rollup-linux-arm64-musl": "4.53.3", - "@rollup/rollup-linux-loong64-gnu": "4.53.3", - "@rollup/rollup-linux-ppc64-gnu": "4.53.3", - "@rollup/rollup-linux-riscv64-gnu": "4.53.3", - "@rollup/rollup-linux-riscv64-musl": "4.53.3", - "@rollup/rollup-linux-s390x-gnu": "4.53.3", - "@rollup/rollup-linux-x64-gnu": "4.53.3", - "@rollup/rollup-linux-x64-musl": "4.53.3", - "@rollup/rollup-openharmony-arm64": "4.53.3", - "@rollup/rollup-win32-arm64-msvc": "4.53.3", - "@rollup/rollup-win32-ia32-msvc": "4.53.3", - "@rollup/rollup-win32-x64-gnu": "4.53.3", - "@rollup/rollup-win32-x64-msvc": "4.53.3", - "fsevents": "~2.3.2" - } - }, - "node_modules/search-insights": { - "version": "2.17.3", - "resolved": "https://registry.npmjs.org/search-insights/-/search-insights-2.17.3.tgz", - "integrity": "sha512-RQPdCYTa8A68uM2jwxoY842xDhvx3E5LFL1LxvxCNMev4o5mLuokczhzjAgGwUZBAmOKZknArSxLKmXtIi2AxQ==", - "dev": true, - "license": "MIT", - "peer": true - }, - "node_modules/semver": { - "version": "7.7.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", - "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/shiki": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/shiki/-/shiki-2.5.0.tgz", - "integrity": "sha512-mI//trrsaiCIPsja5CNfsyNOqgAZUb6VpJA+340toL42UpzQlXpwRV9nch69X6gaUxrr9kaOOa6e3y3uAkGFxQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/core": "2.5.0", - "@shikijs/engine-javascript": "2.5.0", - "@shikijs/engine-oniguruma": "2.5.0", - "@shikijs/langs": "2.5.0", - "@shikijs/themes": "2.5.0", - "@shikijs/types": "2.5.0", - "@shikijs/vscode-textmate": "^10.0.2", - "@types/hast": "^3.0.4" - } - }, - "node_modules/smol-toml": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.5.2.tgz", - "integrity": "sha512-QlaZEqcAH3/RtNyet1IPIYPsEWAaYyXXv1Krsi+1L/QHppjX4Ifm8MQsBISz9vE8cHicIq3clogsheili5vhaQ==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">= 18" - }, - "funding": { - "url": "https://github.com/sponsors/cyyynthia" - } - }, - "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/space-separated-tokens": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", - "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/speakingurl": { - "version": "14.0.1", - "resolved": "https://registry.npmjs.org/speakingurl/-/speakingurl-14.0.1.tgz", - "integrity": "sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/stringify-entities": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", - "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", - "dev": true, - "license": "MIT", - "dependencies": { - "character-entities-html4": "^2.0.0", - "character-entities-legacy": "^3.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/superjson": { - "version": "2.2.5", - "resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.5.tgz", - "integrity": "sha512-zWPTX96LVsA/eVYnqOM2+ofcdPqdS1dAF1LN4TS2/MWuUpfitd9ctTa87wt4xrYnZnkLtS69xpBdSxVBP5Rm6w==", - "dev": true, - "license": "MIT", - "dependencies": { - "copy-anything": "^4" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/tabbable": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.3.0.tgz", - "integrity": "sha512-EIHvdY5bPLuWForiR/AN2Bxngzpuwn1is4asboytXtpTgsArc+WmSJKVLlhdh71u7jFcryDqB2A8lQvj78MkyQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/tinyglobby": { - "version": "0.2.15", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", - "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "fdir": "^6.5.0", - "picomatch": "^4.0.3" - }, - "engines": { - "node": ">=12.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/SuperchupuDev" - } - }, - "node_modules/trim-lines": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", - "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/unist-util-is": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz", - "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unist-util-position": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz", - "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unist-util-stringify-position": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", - "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unist-util-visit": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.0.0.tgz", - "integrity": "sha512-MR04uvD+07cwl/yhVuVWAtw+3GOR/knlL55Nd/wAdblk27GCVt3lqpTivy/tkJcZoNPzTwS1Y+KMojlLDhoTzg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "unist-util-is": "^6.0.0", - "unist-util-visit-parents": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unist-util-visit-parents": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", - "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "unist-util-is": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/vfile": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", - "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "vfile-message": "^4.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/vfile-message": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz", - "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "unist-util-stringify-position": "^4.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/vite": { - "version": "5.4.21", - "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz", - "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==", - "dev": true, - "license": "MIT", - "dependencies": { - "esbuild": "^0.21.3", - "postcss": "^8.4.43", - "rollup": "^4.20.0" - }, - "bin": { - "vite": "bin/vite.js" - }, - "engines": { - "node": "^18.0.0 || >=20.0.0" - }, - "funding": { - "url": "https://github.com/vitejs/vite?sponsor=1" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - }, - "peerDependencies": { - "@types/node": "^18.0.0 || >=20.0.0", - "less": "*", - "lightningcss": "^1.21.0", - "sass": "*", - "sass-embedded": "*", - "stylus": "*", - "sugarss": "*", - "terser": "^5.4.0" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "less": { - "optional": true - }, - "lightningcss": { - "optional": true - }, - "sass": { - "optional": true - }, - "sass-embedded": { - "optional": true - }, - "stylus": { - "optional": true - }, - "sugarss": { - "optional": true - }, - "terser": { - "optional": true - } - } - }, - "node_modules/vitepress": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/vitepress/-/vitepress-1.6.4.tgz", - "integrity": "sha512-+2ym1/+0VVrbhNyRoFFesVvBvHAVMZMK0rw60E3X/5349M1GuVdKeazuksqopEdvkKwKGs21Q729jX81/bkBJg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@docsearch/css": "3.8.2", - "@docsearch/js": "3.8.2", - "@iconify-json/simple-icons": "^1.2.21", - "@shikijs/core": "^2.1.0", - "@shikijs/transformers": "^2.1.0", - "@shikijs/types": "^2.1.0", - "@types/markdown-it": "^14.1.2", - "@vitejs/plugin-vue": "^5.2.1", - "@vue/devtools-api": "^7.7.0", - "@vue/shared": "^3.5.13", - "@vueuse/core": "^12.4.0", - "@vueuse/integrations": "^12.4.0", - "focus-trap": "^7.6.4", - "mark.js": "8.11.1", - "minisearch": "^7.1.1", - "shiki": "^2.1.0", - "vite": "^5.4.14", - "vue": "^3.5.13" - }, - "bin": { - "vitepress": "bin/vitepress.js" - }, - "peerDependencies": { - "markdown-it-mathjax3": "^4", - "postcss": "^8" - }, - "peerDependenciesMeta": { - "markdown-it-mathjax3": { - "optional": true - }, - "postcss": { - "optional": true - } - } - }, - "node_modules/vscode-languageserver-textdocument": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.12.tgz", - "integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==", - "dev": true, - "license": "MIT" - }, - "node_modules/vscode-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz", - "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/vue": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.24.tgz", - "integrity": "sha512-uTHDOpVQTMjcGgrqFPSb8iO2m1DUvo+WbGqoXQz8Y1CeBYQ0FXf2z1gLRaBtHjlRz7zZUBHxjVB5VTLzYkvftg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/compiler-dom": "3.5.24", - "@vue/compiler-sfc": "3.5.24", - "@vue/runtime-dom": "3.5.24", - "@vue/server-renderer": "3.5.24", - "@vue/shared": "3.5.24" - }, - "peerDependencies": { - "typescript": "*" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/xdg-basedir": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-5.1.0.tgz", - "integrity": "sha512-GCPAHLvrIH13+c0SuacwvRYj2SxJXQ4kaVTT5xgL3kPrz56XxkF21IGhjSE1+W0aw7gpBWRGXLCPnPby6lSpmQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/yaml": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.1.tgz", - "integrity": "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw==", - "dev": true, - "license": "ISC", - "bin": { - "yaml": "bin.mjs" - }, - "engines": { - "node": ">= 14.6" - } - }, - "node_modules/zwitch": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", - "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - } - } } diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..a669e690 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,6 @@ +{ + "name": "vault-link", + "lockfileVersion": 3, + "requires": true, + "packages": {} +} diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 00000000..a9107050 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,11 @@ +# Rustfmt configuration +# This should match the .editorconfig settings + +# Use spaces for indentation (matches .editorconfig indent_style = space) +hard_tabs = false + +# Use 4 spaces for indentation (matches .editorconfig indent_size = 4) +tab_spaces = 4 + +# Use Unix line endings (matches .editorconfig end_of_line = lf) +newline_style = "Unix" diff --git a/scripts/bump-version.sh b/scripts/bump-version.sh index fb953e2a..bea3d982 100755 --- a/scripts/bump-version.sh +++ b/scripts/bump-version.sh @@ -35,7 +35,8 @@ cd .. cp frontend/obsidian-plugin/manifest.json manifest.json # for BRAT, otherwise it wouldn't update -git ls-files | xargs npx eclint fix +# Format all files across the project (frontend and backend) +npx -C frontend prettier --write "**/*.{ts,js,json,md,yml,yaml}" # Commit and tag git add . diff --git a/scripts/check.sh b/scripts/check.sh index 7c3c87e5..2ee0dd62 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -30,8 +30,11 @@ fi which cargo-machete || cargo install cargo-machete cargo machete --with-metadata +cd .. +scripts/update-api-types.sh # this will dirty up the git state if not up-to-date + echo "Running checks in frontend" -cd ../frontend +cd frontend if [[ "$FIX_MODE" == true ]]; then npm install @@ -45,10 +48,11 @@ cd frontend npm run build npm run test npm run lint +cd .. -# Use git ls-files to only check tracked files, respecting .gitignore -# We always run in fix mode and then check with git status -git ls-files | xargs npx eclint fix +# Format all files across the project (frontend and backend) +# Prettier respects .gitignore by default +npx -C frontend prettier --write "**/*.{ts,js,json,md,yml,yaml}" if [[ "$FIX_MODE" == false ]] && [[ $(git status --porcelain) ]]; then git status --porcelain @@ -56,6 +60,4 @@ if [[ "$FIX_MODE" == false ]] && [[ $(git status --porcelain) ]]; then exit 1 fi -cd .. - echo "Success" diff --git a/scripts/clean-up.sh b/scripts/clean-up.sh index 4dfbf4a0..dcf400bb 100755 --- a/scripts/clean-up.sh +++ b/scripts/clean-up.sh @@ -1,4 +1,4 @@ #!/bin/bash -rm -rf sync-server/databases +rm -rf /host/tmp/vaultlink-e2e-databases rm -rf logs diff --git a/scripts/e2e.sh b/scripts/e2e.sh index 6c66e835..7ab8d90c 100755 --- a/scripts/e2e.sh +++ b/scripts/e2e.sh @@ -19,35 +19,51 @@ process_count=$1 mkdir -p logs +# Build and restart the server +echo "Building server..." +cd sync-server +cargo build --release + +# Kill any existing server process +echo "Stopping existing server..." +pkill -f "sync_server" 2>/dev/null || true +sleep 1 + +# Clean databases (uses tmpfs via /dev/shm for zero disk I/O) +echo "Cleaning databases..." +rm -rf /host/tmp/vaultlink-e2e-databases + +# Start the server in the background +echo "Starting server..." +./target/release/sync_server config-e2e.yml & +server_pid=$! +echo "Server started with PID: $server_pid" + +# Ensure server is killed on script exit +cleanup_server() { + if [ -n "$server_pid" ]; then + echo "Stopping server (PID: $server_pid)..." + kill $server_pid 2>/dev/null || true + wait $server_pid 2>/dev/null || true + server_pid="" + fi +} +trap cleanup_server EXIT + +cd .. + cd frontend npm ci npm run build ../scripts/utils/wait-for-server.sh -cd .. -scripts/update-api-types.sh -if [[ $(git status --porcelain) ]]; then - git status --porcelain - echo "Failing CI because the working directory is not clean after generating api types" - exit 1 -fi -cd frontend - pids=() for i in $(seq 1 $process_count); do - # Create a named pipe for this process - pipe="/tmp/vaultlink_pipe_$$_$i" - mkfifo "$pipe" - - # Start the node process writing to the pipe - node test-client/dist/cli.js > "$pipe" 2>&1 & + node test-client/dist/cli.js > "../logs/log_${i}.log" 2>&1 & pid=$! pids+=($pid) - echo "Started process $i with PID: $pid" - - # Read from pipe, prefix with PID - (sed "s/^/[PID $pid] /" < "$pipe" > "../logs/log_${i}.log"; rm "$pipe") & + echo "Started process $i with PID: $pid (log: logs/log_${i}.log)" done cd .. @@ -75,10 +91,25 @@ print_failed_log() { return 1 } -echo "Monitoring $process_count processes" +E2E_TIMEOUT=${2:-3600} +start_time=$(date +%s) +echo "Monitoring $process_count processes (timeout: ${E2E_TIMEOUT}s)" # Monitor processes while true; do + # Script-level timeout to prevent indefinite hangs + current_time=$(date +%s) + elapsed=$((current_time - start_time)) + if [ $elapsed -ge $E2E_TIMEOUT ]; then + echo "E2E timeout reached (${E2E_TIMEOUT}s). Killing remaining processes." + for pid in "${pids[@]}"; do + if [ -n "$pid" ]; then + kill $pid 2>/dev/null || true + fi + done + exit 1 + fi + if print_failed_log; then # Kill remaining processes for pid in "${pids[@]}"; do @@ -99,6 +130,7 @@ while true; do done if $all_done; then + cleanup_server echo "All processes completed successfully" exit 0 fi diff --git a/scripts/update-api-types.sh b/scripts/update-api-types.sh index 4b947ee8..3f4a9e2a 100755 --- a/scripts/update-api-types.sh +++ b/scripts/update-api-types.sh @@ -8,9 +8,15 @@ cd sync-server cargo test export_bindings cd - +# Both target directories contain only generated bindings — wipe and copy +rm -f frontend/sync-client/src/services/types/*.ts +rm -f frontend/history-ui/src/lib/types/*.ts cp -r sync-server/bindings/* frontend/sync-client/src/services/types/ +cp -r sync-server/bindings/* frontend/history-ui/src/lib/types/ cd frontend npm run lint -git ls-files | xargs npx eclint fix -cd - +cd .. + +# Format all files across the project (frontend and backend) +npx -C frontend prettier --write "**/*.{ts,js,json,md,yml,yaml}" diff --git a/scripts/utils/check-node.sh b/scripts/utils/check-node.sh index c9ede47e..d93f2f27 100755 --- a/scripts/utils/check-node.sh +++ b/scripts/utils/check-node.sh @@ -2,8 +2,10 @@ set -e +TARGET_NODE_VERSION=25 + node_version=$(node -v | sed 's/^v\([0-9]*\).*/\1/') -if [ "$node_version" != "22" ]; then - echo "Error: This script requires Node.js version 22, found: $node_version" +if [ "$node_version" != "$TARGET_NODE_VERSION" ]; then + echo "Error: This script requires Node.js version $TARGET_NODE_VERSION, found: $node_version" exit 1 fi diff --git a/scripts/utils/wait-for-server.sh b/scripts/utils/wait-for-server.sh index 7824c405..71103477 100755 --- a/scripts/utils/wait-for-server.sh +++ b/scripts/utils/wait-for-server.sh @@ -2,14 +2,14 @@ set -e -SERVER_URL="http://localhost:3000" +SERVER_URL="http://localhost:3010" MAX_RETRIES=30 RETRY_INTERVAL_IN_SECONDS=5 echo "Waiting for $SERVER_URL to become available..." count=0 while [ $count -lt $MAX_RETRIES ]; do - if curl -s -f -o /dev/null $SERVER_URL; then + if curl -s -o /dev/null $SERVER_URL; then echo "$SERVER_URL is now available!" break fi From a9ce09b59d398b739cdc00ddf6c7d79ab357ff31 Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Fri, 8 May 2026 21:35:18 +0100 Subject: [PATCH 02/17] split: server foundation (Cargo, config, errors, utils, main) Cargo.{toml,lock} bumps, build.rs, config-e2e.yml, rust-toolchain.toml, src/config/* (database/logging/server/user configs), src/consts.rs, src/errors.rs, src/main.rs, and src/utils/* (dedup_paths, find_first_available_path, rotating_file_writer, sanitize_path). --- sync-server/Cargo.lock | 193 ++++++++++++++++-- sync-server/Cargo.toml | 10 +- sync-server/build.rs | 13 +- sync-server/config-e2e.yml | 40 ++-- sync-server/rust-toolchain.toml | 2 +- sync-server/src/config.rs | 42 ++-- sync-server/src/config/database_config.rs | 19 ++ sync-server/src/config/logging_config.rs | 19 +- sync-server/src/config/server_config.rs | 75 ++++++- sync-server/src/config/user_config.rs | 20 +- sync-server/src/consts.rs | 22 +- sync-server/src/errors.rs | 45 +++- sync-server/src/main.rs | 28 ++- sync-server/src/utils/dedup_paths.rs | 16 +- .../src/utils/find_first_available_path.rs | 11 +- sync-server/src/utils/rotating_file_writer.rs | 23 ++- sync-server/src/utils/sanitize_path.rs | 56 ++++- 17 files changed, 535 insertions(+), 99 deletions(-) diff --git a/sync-server/Cargo.lock b/sync-server/Cargo.lock index b3da1486..82a7ce92 100644 --- a/sync-server/Cargo.lock +++ b/sync-server/Cargo.lock @@ -337,10 +337,11 @@ checksum = "325918d6fe32f23b19878fe4b34794ae41fc19ddbe53b10571a4874d44ffd39b" [[package]] name = "cc" -version = "1.2.2" +version = "1.2.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f34d93e62b03caf570cccc334cbc6c2fceca82f39211051345108adcba3eebdc" +checksum = "7a0dd1ca384932ff3641c8718a02769f1698e7563dc6974ffd03346116310423" dependencies = [ + "find-msvc-tools", "shlex", ] @@ -456,6 +457,15 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" +[[package]] +name = "crossbeam-channel" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-queue" version = "0.3.11" @@ -533,6 +543,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "powerfmt", +] + [[package]] name = "digest" version = "0.10.7" @@ -624,6 +643,12 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "486f806e73c5707928240ddc295403b1b93c96a02038563881c4a2fd84b81ac4" +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + [[package]] name = "flume" version = "0.11.1" @@ -1272,6 +1297,16 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + [[package]] name = "miniz_oxide" version = "0.8.0" @@ -1335,6 +1370,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "num-conv" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" + [[package]] name = "num-integer" version = "0.1.46" @@ -1463,6 +1504,12 @@ version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2" +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "ppv-lite86" version = "0.2.20" @@ -1582,12 +1629,12 @@ dependencies = [ [[package]] name = "reconcile-text" -version = "0.8.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "599cf9539996a2a19e501110404c59ba62f4974009f8fb864a8b7151c15ee5a5" +checksum = "52e0cf361887ea64c479ca871c1170dda761f84e122f2616b5579906a38d7557" dependencies = [ "serde", - "thiserror 2.0.17", + "thiserror 2.0.18", ] [[package]] @@ -1648,6 +1695,40 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rust-embed" +version = "8.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04113cb9355a377d83f06ef1f0a45b8ab8cd7d8b1288160717d66df5c7988d27" +dependencies = [ + "rust-embed-impl", + "rust-embed-utils", + "walkdir", +] + +[[package]] +name = "rust-embed-impl" +version = "8.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0902e4c7c8e997159ab384e6d0fc91c221375f6894346ae107f47dd0f3ccaa" +dependencies = [ + "proc-macro2", + "quote", + "rust-embed-utils", + "syn 2.0.90", + "walkdir", +] + +[[package]] +name = "rust-embed-utils" +version = "8.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bcdef0be6fe7f6fa333b1073c949729274b05f123a0ad7efcb8efd878e5c3b1" +dependencies = [ + "sha2", + "walkdir", +] + [[package]] name = "rustc-demangle" version = "0.1.24" @@ -1679,6 +1760,15 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + [[package]] name = "sanitize-filename" version = "0.6.0" @@ -1916,7 +2006,7 @@ dependencies = [ "serde_json", "sha2", "smallvec", - "thiserror 2.0.17", + "thiserror 2.0.18", "tokio", "tokio-stream", "tracing", @@ -2000,7 +2090,7 @@ dependencies = [ "smallvec", "sqlx-core", "stringprep", - "thiserror 2.0.17", + "thiserror 2.0.18", "tracing", "uuid", "whoami", @@ -2039,7 +2129,7 @@ dependencies = [ "smallvec", "sqlx-core", "stringprep", - "thiserror 2.0.17", + "thiserror 2.0.18", "tracing", "uuid", "whoami", @@ -2065,7 +2155,7 @@ dependencies = [ "serde", "serde_urlencoded", "sqlx-core", - "thiserror 2.0.17", + "thiserror 2.0.18", "tracing", "url", "uuid", @@ -2100,6 +2190,12 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "symlink" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" + [[package]] name = "syn" version = "1.0.109" @@ -2136,18 +2232,22 @@ dependencies = [ "futures", "humantime-serde", "log", + "mime_guess", "rand 0.9.0", "reconcile-text", "regex", + "rust-embed", "sanitize-filename", "serde", "serde_json", "serde_yaml", "sqlx", - "thiserror 2.0.17", + "subtle", + "thiserror 2.0.18", "tokio", "tower-http", "tracing", + "tracing-appender", "tracing-subscriber", "ts-rs", "uuid", @@ -2203,11 +2303,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.17" +version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" dependencies = [ - "thiserror-impl 2.0.17", + "thiserror-impl 2.0.18", ] [[package]] @@ -2223,9 +2323,9 @@ dependencies = [ [[package]] name = "thiserror-impl" -version = "2.0.17" +version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" dependencies = [ "proc-macro2", "quote", @@ -2242,6 +2342,37 @@ dependencies = [ "once_cell", ] +[[package]] +name = "time" +version = "0.3.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" + +[[package]] +name = "time-macros" +version = "0.2.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tinystr" version = "0.7.6" @@ -2276,7 +2407,6 @@ dependencies = [ "bytes", "libc", "mio", - "parking_lot", "pin-project-lite", "signal-hook-registry", "socket2", @@ -2376,6 +2506,19 @@ dependencies = [ "tracing-core", ] +[[package]] +name = "tracing-appender" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" +dependencies = [ + "crossbeam-channel", + "symlink", + "thiserror 2.0.18", + "time", + "tracing-subscriber", +] + [[package]] name = "tracing-attributes" version = "0.1.28" @@ -2434,7 +2577,7 @@ checksum = "e640d9b0964e9d39df633548591090ab92f7a4567bc31d3891af23471a3365c6" dependencies = [ "chrono", "lazy_static", - "thiserror 2.0.17", + "thiserror 2.0.18", "ts-rs-macros", "uuid", ] @@ -2481,6 +2624,12 @@ version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f720def6ce1ee2fc44d40ac9ed6d3a59c361c80a75a7aa8e75bb9baed31cf2ea" +[[package]] +name = "unicase" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" + [[package]] name = "unicode-bidi" version = "0.3.17" @@ -2577,6 +2726,16 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" diff --git a/sync-server/Cargo.toml b/sync-server/Cargo.toml index fac06efa..6de17653 100644 --- a/sync-server/Cargo.toml +++ b/sync-server/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sync_server" -rust-version = "1.89.0" +rust-version = "1.94.0" authors = ["Andras Schmelczer "] edition = "2024" license = "MIT" @@ -10,7 +10,7 @@ version = "0.14.0" [dependencies] serde = { version = "1.0.219", default-features = false, features = ["derive"] } thiserror = { version = "2.0.12", default-features = false } -tokio = { version = "1.48.0", features = ["full"]} +tokio = { version = "1.48.0", features = ["macros", "rt-multi-thread", "sync", "time", "net", "fs", "signal"]} uuid = { version = "1.16.0", features = ["v4", "serde"] } log = { version = "0.4.28" } anyhow = { version = "1.0.100", features = ["backtrace"] } @@ -20,6 +20,7 @@ axum_typed_multipart = "0.11.0" tower-http = { version = "0.6.1", features = ["cors", "trace", "limit", "timeout"] } tracing = "0.1.41" tracing-subscriber = { version = "0.3.20", features = ["fmt", "env-filter"]} +tracing-appender = "0.2.5" humantime-serde = "1.1.1" sqlx = { version = "0.8.6", features = ["sqlite", "runtime-tokio", "uuid", "chrono"] } chrono = { version = "0.4.41", features = ["serde"] } @@ -33,7 +34,10 @@ serde_json = "1.0.140" bimap = "0.6.3" ts-rs = { version = "10.1", features = ["uuid-impl", "chrono-impl"] } base64 = "0.22.1" -reconcile-text = { version = "0.8.0", features = ["serde"] } +reconcile-text = { version = "0.11.0", features = ["serde"] } +rust-embed = "8.5" +mime_guess = "2.0" +subtle = "2.6.1" [profile.release] codegen-units = 1 diff --git a/sync-server/build.rs b/sync-server/build.rs index d5068697..53bd111b 100644 --- a/sync-server/build.rs +++ b/sync-server/build.rs @@ -1,5 +1,16 @@ -// generated by `sqlx migrate build-script` fn main() { // trigger recompilation when a new migration is added println!("cargo:rerun-if-changed=migrations"); + + // Ensure the history-ui dist directory exists so rust-embed can compile + // even when the frontend hasn't been built yet. + let dist_path = std::path::Path::new("../frontend/history-ui/dist"); + if !dist_path.exists() { + std::fs::create_dir_all(dist_path).expect("Failed to create history-ui dist directory"); + std::fs::write( + dist_path.join("index.html"), + "

Run npm run build -w history-ui first.

", + ) + .expect("Failed to write placeholder index.html"); + } } diff --git a/sync-server/config-e2e.yml b/sync-server/config-e2e.yml index 1f235b01..03b860b7 100644 --- a/sync-server/config-e2e.yml +++ b/sync-server/config-e2e.yml @@ -1,32 +1,34 @@ database: - databases_directory_path: databases - max_connections_per_vault: 12 + databases_directory_path: /host/tmp/vaultlink-e2e-databases + max_connections_per_vault: 8 cursor_timeout: 1m server: host: 0.0.0.0 - port: 3000 + port: 3010 max_body_size_mb: 512 max_clients_per_vault: 256 + max_pending_websocket_connections: 4096 + broadcast_channel_capacity: 1024 response_timeout: 30m mergeable_file_extensions: - - md - - txt + - md + - txt users: user_configs: - - name: admin - token: test-token-change-me - vault_access: - type: allow_access_to_all - - name: other-admin - token: test-token-change-me2 - vault_access: - type: allow_access_to_all - - name: test - token: other-test-token - vault_access: - type: allow_list - allowed: - - default + - name: admin + token: test-token-change-me + vault_access: + type: allow_access_to_all + - name: other-admin + token: test-token-change-me2 + vault_access: + type: allow_access_to_all + - name: test + token: other-test-token + vault_access: + type: allow_list + allowed: + - default logging: log_directory: logs log_rotation: 7days diff --git a/sync-server/rust-toolchain.toml b/sync-server/rust-toolchain.toml index 010956cc..567721ef 100644 --- a/sync-server/rust-toolchain.toml +++ b/sync-server/rust-toolchain.toml @@ -1,5 +1,5 @@ [toolchain] -channel = "1.89.0" +channel = "1.94.0" targets = [ "x86_64-unknown-linux-gnu", "x86_64-unknown-linux-musl", diff --git a/sync-server/src/config.rs b/sync-server/src/config.rs index 6a003d2e..26b11a4c 100644 --- a/sync-server/src/config.rs +++ b/sync-server/src/config.rs @@ -27,24 +27,34 @@ pub struct Config { } impl Config { + pub fn validate(&self) -> Result<()> { + self.server + .validate() + .context("Invalid server configuration")?; + self.logging + .validate() + .context("Invalid logging configuration")?; + self.database + .validate() + .context("Invalid database configuration")?; + Ok(()) + } + pub async fn read_or_create(path: &Path) -> Result { - let config = if path.exists() { - info!( - "Loading configuration from `{}`", - path.canonicalize().unwrap().display() - ); - Self::load_from_file(path).await? + let display_path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); + + if path.exists() { + info!("Loading configuration from `{}`", display_path.display()); + Self::load_from_file(path).await } else { - Self::default() - }; - - config.write(path).await?; - info!( - "Updated configuration at `{}`", - path.canonicalize().unwrap().display() - ); - - Ok(config) + let config = Self::default(); + config.write(path).await?; + info!( + "Created default configuration at `{}`", + display_path.display() + ); + Ok(config) + } } pub async fn load_from_file(path: &Path) -> Result { diff --git a/sync-server/src/config/database_config.rs b/sync-server/src/config/database_config.rs index 20a9a21e..a6f57e1f 100644 --- a/sync-server/src/config/database_config.rs +++ b/sync-server/src/config/database_config.rs @@ -1,5 +1,6 @@ use std::{path::PathBuf, time::Duration}; +use anyhow::{Result, ensure}; use log::debug; use serde::{Deserialize, Serialize}; @@ -34,6 +35,24 @@ fn default_cursor_timeout() -> Duration { DEFAULT_CURSOR_TIMEOUT } +impl DatabaseConfig { + pub fn validate(&self) -> Result<()> { + ensure!( + !self.databases_directory_path.as_os_str().is_empty(), + "databases_directory_path must not be empty" + ); + ensure!( + self.max_connections_per_vault > 0, + "max_connections_per_vault must be greater than 0" + ); + ensure!( + !self.cursor_timeout.is_zero(), + "cursor_timeout must be greater than 0" + ); + Ok(()) + } +} + impl Default for DatabaseConfig { fn default() -> Self { Self { diff --git a/sync-server/src/config/logging_config.rs b/sync-server/src/config/logging_config.rs index ad449d1a..dae67288 100644 --- a/sync-server/src/config/logging_config.rs +++ b/sync-server/src/config/logging_config.rs @@ -1,10 +1,13 @@ use std::time::Duration; +use anyhow::{Result, ensure}; use log::debug; use serde::{Deserialize, Serialize}; use crate::{ - consts::{DEFAULT_LOG_DIRECTORY, DEFAULT_LOG_LEVEL, DEFAULT_LOG_ROTATION_INTERVAL}, + consts::{ + DEFAULT_LOG_DIRECTORY, DEFAULT_LOG_LEVEL, DEFAULT_LOG_ROTATION_INTERVAL, DURATION_ZERO, + }, utils::log_level::LogLevel, }; @@ -20,6 +23,20 @@ pub struct LoggingConfig { pub log_level: LogLevel, } +impl LoggingConfig { + pub fn validate(&self) -> Result<()> { + ensure!( + !self.log_directory.is_empty(), + "log_directory must not be an empty string" + ); + ensure!( + self.log_rotation > DURATION_ZERO, + "log_rotation must be greater than 0" + ); + Ok(()) + } +} + impl Default for LoggingConfig { fn default() -> Self { Self { diff --git a/sync-server/src/config/server_config.rs b/sync-server/src/config/server_config.rs index 4a9da0f4..715d216c 100644 --- a/sync-server/src/config/server_config.rs +++ b/sync-server/src/config/server_config.rs @@ -1,10 +1,13 @@ +use anyhow::{Result, ensure}; use log::debug; use serde::{Deserialize, Serialize}; use std::time::Duration; use crate::consts::{ - DEFAULT_HOST, DEFAULT_MAX_BODY_SIZE_MB, DEFAULT_MAX_CLIENTS_PER_VAULT, - DEFAULT_MERGEABLE_FILE_EXTENSIONS, DEFAULT_PORT, DEFAULT_RESPONSE_TIMEOUT_SECONDS, + DEFAULT_ALLOWED_ORIGINS, DEFAULT_BROADCAST_CHANNEL_CAPACITY, DEFAULT_HOST, + DEFAULT_MAX_BODY_SIZE_MB, DEFAULT_MAX_CLIENTS_PER_VAULT, DEFAULT_MAX_PENDING_WS_CONNECTIONS, + DEFAULT_MERGEABLE_FILE_EXTENSIONS, DEFAULT_PORT, DEFAULT_RATE_LIMIT_PER_USER_PER_SECOND, + DEFAULT_RESPONSE_TIMEOUT_SECONDS, DURATION_ZERO, }; #[derive(Debug, Deserialize, Serialize, Clone, Default)] @@ -21,11 +24,56 @@ pub struct ServerConfig { #[serde(default = "default_max_clients_per_vault")] pub max_clients_per_vault: usize, + #[serde(default = "default_broadcast_channel_capacity")] + pub broadcast_channel_capacity: usize, + #[serde(default = "default_response_timeout", with = "humantime_serde")] pub response_timeout: Duration, #[serde(default = "default_mergeable_file_extensions")] pub mergeable_file_extensions: Vec, + + /// Per-user maximum requests per second (keyed by bearer token). + /// `None` disables rate limiting. + #[serde(default = "default_rate_limit_per_user_per_second")] + pub rate_limit_per_user_per_second: Option, + + /// Allowed CORS origins. Default: `["*"]` (allow all). + #[serde(default = "default_allowed_origins")] + pub allowed_origins: Vec, + + /// Maximum concurrent unauthenticated WebSocket connections waiting for + /// handshake. Limits resource consumption from clients that connect but + /// never authenticate. + #[serde(default = "default_max_pending_websocket_connections")] + pub max_pending_websocket_connections: usize, +} + +impl ServerConfig { + pub fn validate(&self) -> Result<()> { + ensure!( + self.response_timeout > DURATION_ZERO, + "response_timeout must be greater than 0" + ); + ensure!( + self.max_body_size_mb > 0, + "max_body_size_mb must be greater than 0" + ); + ensure!( + self.max_clients_per_vault > 0, + "max_clients_per_vault must be greater than 0" + ); + ensure!( + self.broadcast_channel_capacity > 0, + "broadcast_channel_capacity must be greater than 0" + ); + ensure!( + self.max_pending_websocket_connections > 0, + "max_pending_websocket_connections must be greater than 0" + ); + + Ok(()) + } } fn default_host() -> String { @@ -48,6 +96,11 @@ fn default_max_clients_per_vault() -> usize { DEFAULT_MAX_CLIENTS_PER_VAULT } +fn default_broadcast_channel_capacity() -> usize { + debug!("Using default broadcast channel capacity: {DEFAULT_BROADCAST_CHANNEL_CAPACITY}"); + DEFAULT_BROADCAST_CHANNEL_CAPACITY +} + fn default_response_timeout() -> Duration { debug!("Using default response timeout: {DEFAULT_RESPONSE_TIMEOUT_SECONDS:?}"); DEFAULT_RESPONSE_TIMEOUT_SECONDS @@ -60,3 +113,21 @@ fn default_mergeable_file_extensions() -> Vec { .map(|s| (*s).to_owned()) .collect() } + +fn default_rate_limit_per_user_per_second() -> Option { + debug!("Using default rate limit per second: {DEFAULT_RATE_LIMIT_PER_USER_PER_SECOND:?}"); + DEFAULT_RATE_LIMIT_PER_USER_PER_SECOND +} + +fn default_allowed_origins() -> Vec { + debug!("Using default allowed origins: {DEFAULT_ALLOWED_ORIGINS:?}"); + DEFAULT_ALLOWED_ORIGINS + .iter() + .map(|s| (*s).to_owned()) + .collect() +} + +fn default_max_pending_websocket_connections() -> usize { + debug!("Using default max pending WebSocket connections: {DEFAULT_MAX_PENDING_WS_CONNECTIONS}"); + DEFAULT_MAX_PENDING_WS_CONNECTIONS +} diff --git a/sync-server/src/config/user_config.rs b/sync-server/src/config/user_config.rs index 8b2537f0..fd824f39 100644 --- a/sync-server/src/config/user_config.rs +++ b/sync-server/src/config/user_config.rs @@ -1,6 +1,7 @@ use bimap::BiHashMap; use rand::{Rng, distr::Alphanumeric, rng}; use serde::{Deserialize, Deserializer, Serialize, de::Error}; +use subtle::ConstantTimeEq; use crate::app_state::database::models::VaultId; @@ -19,10 +20,19 @@ where let mut user_token_map = BiHashMap::new(); for user in &users { if let Some(existing_name) = user_token_map.get_by_right(&user.token) { + let redacted = if user.token.len() > 6 { + format!( + "{}...{}", + &user.token[..3], + &user.token[user.token.len() - 3..] + ) + } else { + "***".to_owned() + }; return Err(D::Error::custom(format!( - "Duplicate user token found: `{}` for users `{}` and `{}`. User tokens must be \ - unique.", - user.token, existing_name, user.name + "Duplicate user token found: `{redacted}` for users `{}` and `{}`. User tokens \ + must be unique.", + existing_name, user.name ))); } @@ -41,7 +51,9 @@ where impl UserConfig { pub fn get_user(&self, token: &str) -> Option<&User> { - self.user_configs.iter().find(|u| u.token == token) + self.user_configs + .iter() + .find(|u| u.token.as_bytes().ct_eq(token.as_bytes()).into()) } } diff --git a/sync-server/src/consts.rs b/sync-server/src/consts.rs index 98ed1c1f..e03b848f 100644 --- a/sync-server/src/consts.rs +++ b/sync-server/src/consts.rs @@ -2,22 +2,36 @@ use std::time::Duration; use crate::utils::log_level::LogLevel; +pub const DURATION_ZERO: Duration = Duration::from_secs(0); + pub const DEFAULT_CONFIG_PATH: &str = "config.yml"; pub const DEFAULT_DATABASES_DIRECTORY_PATH: &str = "databases"; -pub const DEFAULT_MAX_CONNECTIONS_PER_VAULT: u32 = 12; +pub const DEFAULT_MAX_CONNECTIONS_PER_VAULT: u32 = 6; pub const DEFAULT_CURSOR_TIMEOUT: Duration = Duration::from_secs(60); pub const DEFAULT_HOST: &str = "127.0.0.1"; pub const DEFAULT_PORT: u16 = 3000; pub const DEFAULT_MAX_BODY_SIZE_MB: usize = 4096; -pub const DEFAULT_RESPONSE_TIMEOUT_SECONDS: Duration = Duration::from_secs(1800); +pub const DEFAULT_RESPONSE_TIMEOUT_SECONDS: Duration = Duration::from_mins(30); pub const DEFAULT_MAX_CLIENTS_PER_VAULT: usize = 256; +pub const DEFAULT_BROADCAST_CHANNEL_CAPACITY: usize = 4096; +pub const DEFAULT_MAX_PENDING_WS_CONNECTIONS: usize = 128; pub const DEFAULT_LOG_DIRECTORY: &str = "logs"; -pub const DEFAULT_LOG_ROTATION_INTERVAL: Duration = Duration::from_secs(60 * 60 * 24); // 1 day +pub const DEFAULT_LOG_ROTATION_INTERVAL: Duration = Duration::from_hours(24); +pub const IDLE_POOL_TIMEOUT: Duration = Duration::from_mins(5); +pub const GRACEFUL_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10); +pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10); + +pub const MAX_CURSOR_DOCUMENTS: usize = 1000; +pub const MAX_CURSORS_PER_DOCUMENT: usize = 100; +pub const MAX_RELATIVE_PATH_LEN: usize = 4096; + pub const DEFAULT_LOG_LEVEL: LogLevel = LogLevel::Info; pub const DEFAULT_MERGEABLE_FILE_EXTENSIONS: &[&str] = &["md", "txt"]; -pub const SUPPORTED_API_VERSION: u32 = 2; +pub const DEFAULT_RATE_LIMIT_PER_USER_PER_SECOND: Option = None; +pub const DEFAULT_ALLOWED_ORIGINS: &[&str] = &["*"]; +pub const SUPPORTED_API_VERSION: u32 = 3; diff --git a/sync-server/src/errors.rs b/sync-server/src/errors.rs index 831b0e86..892db36f 100644 --- a/sync-server/src/errors.rs +++ b/sync-server/src/errors.rs @@ -5,7 +5,7 @@ use axum::{ http::StatusCode, response::{IntoResponse, Response}, }; -use log::{debug, error}; +use log::{debug, error, warn}; use serde::Serialize; use thiserror::Error; use ts_rs::TS; @@ -29,6 +29,9 @@ pub enum SyncServerError { #[error("Permission denied error: {0}")] PermissionDeniedError(#[source] anyhow::Error), + + #[error("Too many requests: {0}")] + TooManyRequests(#[source] anyhow::Error), } impl SyncServerError { @@ -39,7 +42,8 @@ impl SyncServerError { | Self::ServerError(error) | Self::NotFound(error) | Self::Unauthenticated(error) - | Self::PermissionDeniedError(error) => error.into(), + | Self::PermissionDeniedError(error) + | Self::TooManyRequests(error) => error.into(), } } } @@ -69,7 +73,22 @@ impl Display for SerializedError { impl IntoResponse for SyncServerError { fn into_response(self) -> Response { - let body = Json(self.serialize()); + let serialized = self.serialize(); + + match &self { + Self::InitError(_) | Self::ServerError(_) => { + error!("{serialized}"); + } + Self::ClientError(_) | Self::NotFound(_) => { + warn!("{serialized}"); + } + Self::TooManyRequests(_) => { + warn!("{serialized}"); + } + Self::Unauthenticated(_) | Self::PermissionDeniedError(_) => {} + } + + let body = Json(serialized); match self { Self::InitError(_) | Self::ServerError(_) => { @@ -79,6 +98,7 @@ impl IntoResponse for SyncServerError { Self::NotFound(_) => (StatusCode::NOT_FOUND, body).into_response(), Self::Unauthenticated(_) => (StatusCode::UNAUTHORIZED, body).into_response(), Self::PermissionDeniedError(_) => (StatusCode::FORBIDDEN, body).into_response(), + Self::TooManyRequests(_) => (StatusCode::TOO_MANY_REQUESTS, body).into_response(), } } } @@ -102,6 +122,7 @@ impl From<&anyhow::Error> for SerializedError { SyncServerError::NotFound(_) => "NotFound", SyncServerError::Unauthenticated(_) => "Unauthenticated", SyncServerError::PermissionDeniedError(_) => "PermissionDeniedError", + SyncServerError::TooManyRequests(_) => "TooManyRequests", }, ), message: error.to_string(), @@ -139,3 +160,21 @@ pub fn permission_denied_error(error: anyhow::Error) -> SyncServerError { debug!("Permission denied: {error:?}"); SyncServerError::PermissionDeniedError(error) } + +pub fn too_many_requests_error(error: anyhow::Error) -> SyncServerError { + debug!("Too many requests: {error:?}"); + SyncServerError::TooManyRequests(error) +} + +/// Maps a `create_write_transaction` error to 429 if the database is busy, +/// or 500 for all other failures. +pub fn write_transaction_error(error: anyhow::Error) -> SyncServerError { + if error + .downcast_ref::() + .is_some() + { + too_many_requests_error(error) + } else { + server_error(error) + } +} diff --git a/sync-server/src/main.rs b/sync-server/src/main.rs index 1285ed7b..dc00d4d5 100644 --- a/sync-server/src/main.rs +++ b/sync-server/src/main.rs @@ -16,6 +16,7 @@ use consts::DEFAULT_CONFIG_PATH; use errors::{SyncServerError, init_error}; use log::info; use server::create_server; +use tracing_appender::non_blocking::WorkerGuard; use tracing_subscriber::{EnvFilter, fmt::format, layer::SubscriberExt, util::SubscriberInitExt}; use utils::rotating_file_writer::RotatingFileWriter; @@ -41,11 +42,14 @@ async fn main() -> ExitCode { } }; - let mut result = set_up_logging(&args, &config.logging); - - if result.is_ok() { - result = start_server(config).await; + let result = async { + config.validate().map_err(init_error)?; + // Hold the non-blocking writer guards until shutdown so the + // dedicated writer threads stay alive and flush queued log lines. + let _log_guards = set_up_logging(&args, &config.logging)?; + start_server(config).await } + .await; match result { Ok(()) => ExitCode::SUCCESS, @@ -59,7 +63,7 @@ async fn main() -> ExitCode { fn set_up_logging( args: &Args, logging_config: &config::logging_config::LoggingConfig, -) -> Result<(), SyncServerError> { +) -> Result<[WorkerGuard; 2], SyncServerError> { let level_filter = logging_config.log_level.as_tracing_level(); let env_filter = EnvFilter::builder() @@ -80,6 +84,14 @@ fn set_up_logging( .context("Failed to create rotating file writer") .map_err(init_error)?; + // Decouple log emission from disk/stderr I/O. Without this, a tokio + // worker that holds the writer's std::sync::Mutex while a `write(2)` + // is throttled by the kernel (e.g. btrfs writeback) cascades the + // stall to every other worker that tries to log, freezing the whole + // runtime. The guards must outlive every emitter. + let (file_writer, file_guard) = tracing_appender::non_blocking(file_appender); + let (stderr_writer, stderr_guard) = tracing_appender::non_blocking(std::io::stderr()); + let format = format() .with_target(is_debug_mode) .with_line_number(is_debug_mode) @@ -87,12 +99,12 @@ fn set_up_logging( let stderr_layer = tracing_subscriber::fmt::layer() .with_ansi(use_colors) - .with_writer(std::io::stderr) + .with_writer(stderr_writer) .event_format(format.clone()); let file_layer = tracing_subscriber::fmt::layer() .with_ansi(false) - .with_writer(file_appender) + .with_writer(file_writer) .event_format(format); tracing_subscriber::registry() @@ -103,7 +115,7 @@ fn set_up_logging( .context("Failed to initialise tracing") .map_err(init_error)?; - Ok(()) + Ok([file_guard, stderr_guard]) } async fn start_server(config: Config) -> Result<(), SyncServerError> { diff --git a/sync-server/src/utils/dedup_paths.rs b/sync-server/src/utils/dedup_paths.rs index bc687f6a..0baf8ba8 100644 --- a/sync-server/src/utils/dedup_paths.rs +++ b/sync-server/src/utils/dedup_paths.rs @@ -1,8 +1,17 @@ +use std::sync::LazyLock; + use regex::Regex; +static DEDUP_SUFFIX_REGEX: LazyLock = + LazyLock::new(|| Regex::new(r" \((\d+)\)$").expect("invalid regex")); + pub fn dedup_paths(path: &str) -> impl Iterator { let mut path_parts = path.split('/').collect::>(); - let file_name = path_parts.pop().unwrap().to_owned(); + let file_name = path_parts + .pop() + .filter(|s| !s.is_empty()) + .unwrap_or(path) + .to_owned(); let mut directory = path_parts.join("/"); if !directory.is_empty() { @@ -29,14 +38,13 @@ pub fn dedup_paths(path: &str) -> impl Iterator { } }; - let regex = Regex::new(r" \((\d+)\)$").unwrap(); - let start_number = regex + let start_number = DEDUP_SUFFIX_REGEX .captures(&stem) .and_then(|caps| caps.get(1)) .and_then(|m| m.as_str().parse::().ok()) .unwrap_or(0); - let clean_stem = regex.replace(&stem, "").to_string(); + let clean_stem = DEDUP_SUFFIX_REGEX.replace(&stem, "").to_string(); (start_number..).map(move |dedup_number| { if dedup_number == 0 { diff --git a/sync-server/src/utils/find_first_available_path.rs b/sync-server/src/utils/find_first_available_path.rs index 7629d8f1..eddd81d2 100644 --- a/sync-server/src/utils/find_first_available_path.rs +++ b/sync-server/src/utils/find_first_available_path.rs @@ -1,25 +1,30 @@ use crate::app_state::database::models::VaultId; -use crate::{app_state::database::Transaction, utils::dedup_paths::dedup_paths}; +use crate::utils::dedup_paths::dedup_paths; use anyhow::Result; use log::{debug, info}; +use sqlx::sqlite::SqliteConnection; pub async fn find_first_available_path( vault_id: &VaultId, sanitized_relative_path: &str, database: &crate::app_state::database::Database, - transaction: &mut Transaction<'_>, + connection: &mut SqliteConnection, ) -> Result { info!("Finding first available path for `{sanitized_relative_path}` in vault `{vault_id}`"); for candidate in dedup_paths(sanitized_relative_path) { debug!("Checking candidate path for deconflicting names: `{candidate}`"); if database - .get_latest_document_by_path(vault_id, &candidate, Some(transaction)) + .get_latest_non_deleted_document_by_path(vault_id, &candidate, Some(connection)) .await? .is_none() { info!("Selected available path: `{candidate}`"); return Ok(candidate); } + + info!( + "Finding first available path for `{sanitized_relative_path}` in vault `{vault_id}` as `{candidate}` is already taken" + ); } unreachable!("dedup_paths produces infinite paths"); diff --git a/sync-server/src/utils/rotating_file_writer.rs b/sync-server/src/utils/rotating_file_writer.rs index f04f9ba9..1c5c86c5 100644 --- a/sync-server/src/utils/rotating_file_writer.rs +++ b/sync-server/src/utils/rotating_file_writer.rs @@ -6,7 +6,7 @@ use std::{ time::{Duration, SystemTime, UNIX_EPOCH}, }; -use chrono::{Local, NaiveDateTime}; +use chrono::NaiveDateTime; use tracing_subscriber::fmt::MakeWriter; #[derive(Clone)] @@ -55,7 +55,7 @@ impl RotatingFileWriter { let timestamp_str = filename.get(prefix_len..filename.len().checked_sub(4)?)?; let dt = NaiveDateTime::parse_from_str(timestamp_str, "%Y-%m-%d_%H-%M-%S").ok()?; - let timestamp = dt.and_local_timezone(Local).single()?; + let timestamp = dt.and_utc(); let secs: u64 = timestamp.timestamp().try_into().ok()?; Some(UNIX_EPOCH + Duration::from_secs(secs)) @@ -114,7 +114,7 @@ impl RotatingFileWriter { } fn rotate(inner: &mut RotatingFileWriterInner) -> io::Result<()> { - let timestamp = Local::now().format("%Y-%m-%d_%H-%M-%S"); + let timestamp = chrono::Utc::now().format("%Y-%m-%d_%H-%M-%S"); let filename = format!("{}.{}.log", inner.file_prefix, timestamp); let filepath = inner.directory.join(filename); @@ -132,8 +132,14 @@ impl RotatingFileWriter { impl Write for RotatingFileWriter { fn write(&mut self, buf: &[u8]) -> io::Result { - let mut inner = self.inner.lock().unwrap(); + let mut inner = self.inner.lock().unwrap_or_else(|poisoned| { + eprintln!("RotatingFileWriter mutex was poisoned, recovering"); + poisoned.into_inner() + }); + // Reset file handle after poison recovery so the next branch + // re-opens a valid file rather than writing to a potentially + // half-closed handle. if inner.current_file.is_none() { Self::open_or_create_log_file(&mut inner)?; } else if Self::should_rotate(&inner) { @@ -148,7 +154,10 @@ impl Write for RotatingFileWriter { } fn flush(&mut self) -> io::Result<()> { - let mut inner = self.inner.lock().unwrap(); + let mut inner = self.inner.lock().unwrap_or_else(|poisoned| { + eprintln!("RotatingFileWriter mutex was poisoned, recovering"); + poisoned.into_inner() + }); if let Some(ref mut file) = inner.current_file { file.flush() } else { @@ -267,7 +276,7 @@ mod tests { // Parse the expected time let expected_dt = NaiveDateTime::parse_from_str(timestamp_str, "%Y-%m-%d_%H-%M-%S").unwrap(); - let expected_timestamp = expected_dt.and_local_timezone(Local).single().unwrap(); + let expected_timestamp = expected_dt.and_utc(); let expected_duration = Duration::from_secs(expected_timestamp.timestamp().try_into().unwrap()); let expected_next = UNIX_EPOCH + expected_duration + rotation_duration; @@ -306,7 +315,7 @@ mod tests { // Should use the latest file (2025-10-26_14-00-00) let expected_dt = NaiveDateTime::parse_from_str("2025-10-26_14-00-00", "%Y-%m-%d_%H-%M-%S").unwrap(); - let expected_timestamp = expected_dt.and_local_timezone(Local).single().unwrap(); + let expected_timestamp = expected_dt.and_utc(); let expected_duration = Duration::from_secs(expected_timestamp.timestamp().try_into().unwrap()); let expected_next = UNIX_EPOCH + expected_duration + rotation_duration; diff --git a/sync-server/src/utils/sanitize_path.rs b/sync-server/src/utils/sanitize_path.rs index 9703225c..05100f68 100644 --- a/sync-server/src/utils/sanitize_path.rs +++ b/sync-server/src/utils/sanitize_path.rs @@ -1,14 +1,28 @@ +use anyhow::{Result, ensure}; + +use crate::consts::MAX_RELATIVE_PATH_LEN; + /// Sanitize the document's path to allow all clients to create the same path in /// their filesystem. If we didn't do this server-side, client's would need to /// deal with mapping invalid names to valid ones and then back. -pub fn sanitize_path(path: &str) -> String { +pub fn sanitize_path(path: &str) -> Result { + // Enforce the length cap at the single chokepoint every create/update + // handler goes through, so clients can't blow up axum's JSON/multipart + // parser with a 1 MB `relative_path` before the handler ever runs. + // The WebSocket cursor handler enforces this separately. + ensure!( + path.len() <= MAX_RELATIVE_PATH_LEN, + "Relative path exceeds the maximum length of {MAX_RELATIVE_PATH_LEN} bytes" + ); + let options = sanitize_filename::Options { truncate: true, windows: true, // Windows is the lowest common denominator replacement: "", }; - path.split('/') + let result = path + .split('/') .map(|part| { let proposal = sanitize_filename::sanitize_with_options(part, options.clone()); if !part.is_empty() && proposal.is_empty() { @@ -18,7 +32,13 @@ pub fn sanitize_path(path: &str) -> String { } }) .collect::>() - .join("/") + .join("/"); + + ensure!( + !result.is_empty(), + "Relative path is empty after sanitization" + ); + Ok(result) } #[cfg(test)] @@ -27,8 +47,32 @@ mod test { #[test] fn test_sanitize_path() { - assert_eq!(sanitize_path("/my/path/what?"), "/my/path/what"); - assert_eq!(sanitize_path("file (1).md"), "file (1).md"); - assert_eq!(sanitize_path("/my/path/\\\\:?"), "/my/path/_"); + assert_eq!(sanitize_path("/my/path/what?").unwrap(), "/my/path/what"); + assert_eq!(sanitize_path("file (1).md").unwrap(), "file (1).md"); + assert_eq!(sanitize_path("/my/path/\\\\:?").unwrap(), "/my/path/_"); + } + + #[test] + fn test_sanitize_path_empty() { + assert!(sanitize_path("").is_err()); + } + + #[test] + fn test_sanitize_path_idempotent_simple() { + let mut result = sanitize_path("notes/my file.md").unwrap(); + for _ in 0..5 { + result = sanitize_path(&result).unwrap(); + } + assert_eq!(result, "notes/my file.md"); + } + + #[test] + fn test_sanitize_path_idempotent_special_chars() { + let first = sanitize_path("/my/path/what?/file:name<>.md").unwrap(); + let mut result = first.clone(); + for _ in 0..5 { + result = sanitize_path(&result).unwrap(); + } + assert_eq!(result, first); } } From 2d5edc6ec50e7ac9112a3735b7b924413399ae77 Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Fri, 8 May 2026 21:35:30 +0100 Subject: [PATCH 03/17] split: server database (app_state, migrations, models) src/app_state.rs, src/app_state/database.rs (large schema/query rewrite), two new migrations (add_idempotency_key, add_creation_vault_update_id), and src/app_state/database/models.rs. --- sync-server/src/app_state.rs | 27 +- sync-server/src/app_state/database.rs | 925 ++++++++++++++---- .../20260314000000_add_idempotency_key.sql | 2 + ...421000000_add_creation_vault_update_id.sql | 20 + sync-server/src/app_state/database/models.rs | 31 +- 5 files changed, 827 insertions(+), 178 deletions(-) create mode 100644 sync-server/src/app_state/database/migrations/20260314000000_add_idempotency_key.sql create mode 100644 sync-server/src/app_state/database/migrations/20260421000000_add_creation_vault_update_id.sql diff --git a/sync-server/src/app_state.rs b/sync-server/src/app_state.rs index 2019e08e..1bd3222e 100644 --- a/sync-server/src/app_state.rs +++ b/sync-server/src/app_state.rs @@ -2,6 +2,8 @@ pub mod cursors; pub mod database; pub mod websocket; +use std::sync::{Arc, atomic::AtomicUsize}; + use anyhow::Result; use cursors::Cursors; use database::Database; @@ -15,21 +17,42 @@ pub struct AppState { pub database: Database, pub cursors: Cursors, pub broadcasts: Broadcasts, + /// Tracks WebSocket connections that have upgraded but not yet completed + /// the authentication handshake + pub pending_ws_connections: Arc, + /// Send on this channel to stop background tasks (cursor cleanup, + /// idle-pool cleanup) + shutdown_tx: Arc>, } impl AppState { pub async fn try_new(config: Config) -> Result { + let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(()); + let broadcasts = Broadcasts::new(&config.server); - let database = Database::try_new(&config.database, &broadcasts).await?; + let database = + Database::try_new(&config.database, &broadcasts, shutdown_rx.clone()).await?; let cursors: Cursors = Cursors::new(&config.database, &broadcasts); - Cursors::start_background_task(cursors.clone()); + Cursors::start_background_task(cursors.clone(), shutdown_rx); Ok(Self { config, database, cursors, broadcasts, + pending_ws_connections: Arc::new(AtomicUsize::new(0)), + shutdown_tx: Arc::new(shutdown_tx), }) } + + /// Signal all background tasks (idle pool cleanup, cursor cleanup) to stop + pub fn shutdown(&self) { + let _ = self.shutdown_tx.send(()); + } + + /// Get a receiver to be notified when shutdown is triggered + pub fn subscribe_shutdown(&self) -> tokio::sync::watch::Receiver<()> { + self.shutdown_tx.subscribe() + } } diff --git a/sync-server/src/app_state/database.rs b/sync-server/src/app_state/database.rs index 75ce6df4..28acde41 100644 --- a/sync-server/src/app_state/database.rs +++ b/sync-server/src/app_state/database.rs @@ -1,16 +1,29 @@ use core::time::Duration; -use std::{collections::HashMap, sync::Arc}; +use std::{ + collections::HashMap, + sync::Arc, + sync::atomic::{AtomicU64, Ordering}, +}; use anyhow::{Context as _, Result}; use log::info; use models::{ DocumentId, DocumentVersionWithoutContent, StoredDocumentVersion, VaultId, VaultUpdateId, }; -use sqlx::{ConnectOptions, sqlite::SqliteConnectOptions, types::chrono::Utc}; +use sqlx::{ConnectOptions, Connection, sqlite::SqliteConnectOptions, types::chrono::Utc}; pub mod models; -use sqlx::{Pool, Sqlite, sqlite::SqlitePoolOptions}; -use tokio::sync::Mutex; + +/// Sentinel error indicating the `SQLite` database is busy (`SQLITE_BUSY`). +/// Handlers can downcast to this to return 429 instead of 500. +#[derive(Debug, thiserror::Error)] +#[error("Database is busy")] +pub struct WriteBusyError; + +use sqlx::{ + Pool, Sqlite, pool::PoolConnection, sqlite::SqliteConnection, sqlite::SqlitePoolOptions, +}; +use tokio::sync::{Mutex, OnceCell}; use tokio::time::Instant; use uuid::fmt::Hyphenated; @@ -19,33 +32,200 @@ use super::websocket::{ models::{WebSocketServerMessage, WebSocketServerMessageWithOrigin, WebSocketVaultUpdate}, }; use crate::config::database_config::DatabaseConfig; +use crate::consts::IDLE_POOL_TIMEOUT; -#[derive(Clone)] -struct PoolWithTimestamp { - pool: Pool, - last_accessed: Instant, +/// Holds separate reader and writer pools for a single vault. +/// The writer pool has exactly 1 connection so writes never compete +/// with reads for pool slots. +#[derive(Debug, Clone)] +struct VaultPools { + reader: Pool, + writer: Pool, } -impl std::fmt::Debug for PoolWithTimestamp { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("PoolWithTimestamp") - .field("pool", &"Pool") - .field("last_accessed", &self.last_accessed) - .finish() - } +#[derive(Debug)] +struct VaultPool { + cell: Arc>, + /// Monotonic timestamp in milliseconds (from `Instant::now()` at server start) + last_accessed_ms: AtomicU64, } #[derive(Clone, Debug)] pub struct Database { config: DatabaseConfig, broadcasts: Broadcasts, - connection_pools: Arc>>, + connection_pools: Arc>>>, + /// Per-vault write serialization. `SQLite` allows only one writer at a + /// time; `BEGIN IMMEDIATE` on a second connection blocks until the first + /// commits (up to `busy_timeout`). Under concurrent load the blocked + /// connections consume the pool, starving even read-only requests. + /// This mutex moves the wait from the `SQLite` layer (where it holds a + /// pool connection) to the Tokio layer (where it holds nothing). + write_locks: Arc>>>>, + /// Monotonic epoch for lock-free `last_accessed_ms` timestamps + epoch: Instant, } -pub type Transaction<'a> = sqlx::Transaction<'a, Sqlite>; +/// A write transaction backed by a raw `BEGIN IMMEDIATE` instead of sqlx's +/// savepoint-based `Transaction`. This avoids the savepoint mismatch caused +/// by the old `END; BEGIN IMMEDIATE;` workaround. +/// +/// Holds an `OwnedMutexGuard` that serializes write transactions per vault +/// at the application level (see `Database::write_locks`). The guard is +/// released when the transaction is committed, rolled back, or dropped. +pub struct WriteTransaction { + conn: Option>, + _write_guard: tokio::sync::OwnedMutexGuard<()>, +} + +impl WriteTransaction { + async fn new( + pool: &Pool, + write_guard: tokio::sync::OwnedMutexGuard<()>, + ) -> Result { + let mut conn = pool + .acquire() + .await + .context("Cannot acquire connection for write transaction")?; + if let Err(e) = sqlx::query("BEGIN IMMEDIATE").execute(&mut *conn).await { + let is_busy = match &e { + sqlx::Error::Database(db_err) => { + // SQLITE_BUSY base code is 5. Extended codes share base 5. + let busy_by_code = db_err + .code() + .is_some_and(|c| c.parse::().is_ok_and(|n| n & 0xFF == 5)); + busy_by_code || db_err.message().contains("database is locked") + } + _ => false, + }; + if is_busy { + return Err(WriteBusyError.into()); + } + return Err(e).context("Cannot begin immediate transaction"); + } + Ok(Self { + conn: Some(conn), + _write_guard: write_guard, + }) + } + + pub async fn commit(mut self) -> Result<()> { + if let Some(mut conn) = self.conn.take() { + sqlx::query("COMMIT") + .execute(&mut *conn) + .await + .context("Failed to commit transaction")?; + } + Ok(()) + } + + pub async fn rollback(mut self) -> Result<()> { + if let Some(mut conn) = self.conn.take() { + sqlx::query("ROLLBACK") + .execute(&mut *conn) + .await + .context("Failed to rollback transaction")?; + } + Ok(()) + } +} + +impl Drop for WriteTransaction { + fn drop(&mut self) { + if self.conn.is_some() { + // The connection is returned to the pool with an open transaction. + // The pool's `before_acquire` hook issues a ROLLBACK before + // handing it to the next consumer, so no async work is needed + // here. If the pool is being shut down, SQLite itself rolls back + // uncommitted transactions when the connection closes. + log::warn!("WriteTransaction dropped without commit or rollback"); + } + } +} + +impl std::ops::Deref for WriteTransaction { + type Target = SqliteConnection; + fn deref(&self) -> &Self::Target { + self.conn + .as_ref() + .expect("BUG: WriteTransaction dereferenced after being consumed") + .deref() + } +} + +impl std::ops::DerefMut for WriteTransaction { + fn deref_mut(&mut self) -> &mut Self::Target { + self.conn + .as_mut() + .expect("BUG: WriteTransaction dereferenced after being consumed") + .deref_mut() + } +} + +/// Ensure the connection has no leftover open transaction (e.g. from a +/// `WriteTransaction` that was dropped without commit/rollback). ROLLBACK +/// is a harmless no-op if no transaction is active. +fn rollback_before_acquire( + conn: &mut SqliteConnection, + _meta: sqlx::pool::PoolConnectionMetadata, +) -> futures::future::BoxFuture<'_, Result> { + Box::pin(async move { + if let Err(e) = sqlx::query("ROLLBACK").execute(&mut *conn).await { + // "cannot rollback - no transaction is active" is the common + // case (connection returned cleanly). Only unexpected errors + // deserve attention. + log::debug!("before_acquire ROLLBACK failed: {e}"); + } + Ok(true) + }) +} impl Database { - pub async fn try_new(config: &DatabaseConfig, broadcasts: &Broadcasts) -> Result { + fn now_ms(&self) -> u64 { + self.epoch.elapsed().as_millis() as u64 + } + + /// Lists all vault IDs that exist on disk (have a `.sqlite` file). + pub async fn list_vaults(&self) -> Result> { + let mut vaults = Vec::new(); + let mut entries = tokio::fs::read_dir(&self.config.databases_directory_path) + .await + .context("Failed to read databases directory")?; + while let Some(entry) = entries.next_entry().await? { + let name = entry.file_name().to_string_lossy().to_string(); + if let Some(vault) = name.strip_suffix(".sqlite") { + vaults.push(vault.to_owned()); + } + } + vaults.sort(); + Ok(vaults) + } + + pub async fn get_vault_stats(&self, vault: &VaultId) -> Result { + let pool = self.get_connection_pool(vault).await?; + let row = sqlx::query!( + r#" + SELECT + (SELECT MIN(updated_date) FROM documents) + AS "created_at: chrono::DateTime", + (SELECT COUNT(DISTINCT document_id) FROM latest_document_versions + WHERE is_deleted = false) + AS "document_count!: u32" + "#, + ) + .fetch_one(&pool) + .await?; + Ok(models::VaultStats { + created_at: row.created_at, + document_count: row.document_count, + }) + } + + pub async fn try_new( + config: &DatabaseConfig, + broadcasts: &Broadcasts, + shutdown: tokio::sync::watch::Receiver<()>, + ) -> Result { tokio::fs::create_dir_all(&config.databases_directory_path) .await .with_context(|| { @@ -70,122 +250,207 @@ impl Database { .trim_end_matches(".sqlite") .to_owned(); - let pool = Self::create_vault_database(config, &vault).await?; + Self::validate_vault_id(&vault)?; + + let pools = Self::create_vault_database(config, &vault).await?; + let cell = Arc::new(OnceCell::new()); + cell.set(pools).expect("cell is new"); connection_pools.insert( vault.clone(), - PoolWithTimestamp { - pool, - last_accessed: Instant::now(), - }, + Arc::new(VaultPool { + cell, + last_accessed_ms: AtomicU64::new(0), + }), ); } + info!("Database migrations applied"); let database = Self { config: config.clone(), connection_pools: Arc::new(Mutex::new(connection_pools)), broadcasts: broadcasts.clone(), + write_locks: Arc::new(Mutex::new(HashMap::new())), + epoch: Instant::now(), }; - // Start background task to cleanup idle connection pools - database.start_idle_pool_cleanup(); + database.start_idle_pool_cleanup(shutdown); Ok(database) } - async fn create_vault_database( - config: &DatabaseConfig, - vault: &VaultId, - ) -> Result> { + async fn create_vault_database(config: &DatabaseConfig, vault: &VaultId) -> Result { let file_name = config .databases_directory_path .join(format!("{vault}.sqlite")); - let connection_options = SqliteConnectOptions::new() + // Database-level PRAGMAs (auto_vacuum, journal_mode) require a write + // lock and persist across connections. Set them once with a dedicated + // init connection so pool connections never need the write lock just to + // open. + let init_options = SqliteConnectOptions::new() .filename(file_name.clone()) .create_if_missing(true) - .auto_vacuum(sqlx::sqlite::SqliteAutoVacuum::Full) - .busy_timeout(Duration::from_secs(3600)) - .journal_mode(sqlx::sqlite::SqliteJournalMode::Wal) - .log_slow_statements(log::LevelFilter::Warn, Duration::from_secs(30)); + .auto_vacuum(sqlx::sqlite::SqliteAutoVacuum::Incremental) + .journal_mode(sqlx::sqlite::SqliteJournalMode::Wal); - let pool = SqlitePoolOptions::new() + // Run migrations on a dedicated connection, NOT through the pool. + // The pool's `before_acquire` hook issues ROLLBACK on every checkout, + // which can roll back the migration's bookkeeping transaction (the + // _sqlx_migrations INSERT) while the DDL (ALTER TABLE) has already + // auto-committed — leaving the migration in a dirty state. + // + // Uses `run_direct` instead of `run` because `run` takes + // `impl Acquire<'_>`, whose lifetime bound prevents the enclosing + // future from satisfying the `Send` requirement of axum handlers. + let mut init_conn = sqlx::SqliteConnection::connect_with(&init_options).await?; + sqlx::migrate!("src/app_state/database/migrations") + .run_direct(&mut init_conn) + .await + .context("Cannot run pending migrations")?; + drop(init_conn); + + // Per-connection PRAGMAs shared by both reader and writer pools. + // journal_mode = WAL is a no-op on an already-WAL database. + let base_options = SqliteConnectOptions::new() + .filename(file_name.clone()) + .journal_mode(sqlx::sqlite::SqliteJournalMode::Wal) + .busy_timeout(Duration::from_secs(30)) + .log_slow_statements(log::LevelFilter::Warn, Duration::from_secs(30)) + // In WAL mode, NORMAL is safe: data survives OS crashes, only the + // last transaction can be lost on power failure. The default FULL + // forces an extra fsync() per commit, roughly halving write throughput. + .pragma("synchronous", "NORMAL") + // 16 MB page cache per connection (negative = KiB). Reduces disk + // reads for the latest_document_versions GROUP BY view. + .pragma("cache_size", "-16384") + // Memory-mapped I/O avoids read() syscalls. SQLite falls back to + // regular I/O for writes and beyond the mapped region. 256 MB is + // conservative; the OS handles actual memory pressure. + .pragma("mmap_size", "268435456") + // Keep temp tables and sort spillovers in memory instead of temp files. + .pragma("temp_store", "MEMORY") + // Cap WAL file growth at 64 MB. Without this, the WAL can grow + // unbounded during heavy write bursts (e.g. E2E tests with many + // concurrent clients). SQLite truncates to this size on checkpoint. + .pragma("journal_size_limit", "67108864"); + + // Reader pool: multiple connections for concurrent reads. + let reader = SqlitePoolOptions::new() .max_connections(config.max_connections_per_vault) .acquire_slow_threshold(Duration::from_secs(30)) - .test_before_acquire(true) - .connect_with(connection_options) + // Disabled: the health-check query is subject to busy_timeout + // and blocks all connection checkouts when a write is active, + // starving the pool for up to 30s even for simple reads. + // The before_acquire ROLLBACK hook is sufficient for cleanup. + .test_before_acquire(false) + .before_acquire(rollback_before_acquire) + .connect_with(base_options.clone()) .await - .with_context(|| format!("Cannot open database at `{}`", file_name.display()))?; + .with_context(|| format!("Cannot open reader pool at `{}`", file_name.display()))?; - Self::run_migrations(&pool).await?; + // Writer pool: exactly 1 connection, dedicated to writes. + // Since the Tokio mutex already serializes writers per vault, this + // single connection is never contended. Separating it from the + // reader pool ensures writes never compete with reads for pool slots. + let writer = SqlitePoolOptions::new() + .max_connections(1) + .acquire_slow_threshold(Duration::from_secs(30)) + .test_before_acquire(false) + .before_acquire(rollback_before_acquire) + .connect_with(base_options) + .await + .with_context(|| format!("Cannot open writer pool at `{}`", file_name.display()))?; - Ok(pool) + Ok(VaultPools { reader, writer }) } - async fn run_migrations(pool: &Pool) -> Result<()> { - sqlx::migrate!("src/app_state/database/migrations") - .run(pool) - .await - .context("Cannot check for pending migrations") - } - - async fn get_connection_pool(&self, vault: &VaultId) -> Result> { - let mut pools = self.connection_pools.lock().await; - - if !pools.contains_key(vault) { - let pool = Self::create_vault_database(&self.config, vault).await?; - pools.insert( - vault.clone(), - PoolWithTimestamp { - pool, - last_accessed: Instant::now(), - }, + fn validate_vault_id(vault: &VaultId) -> Result<()> { + if vault.is_empty() { + anyhow::bail!("Vault ID must not be empty"); + } + if vault.contains('/') + || vault.contains('\\') + || vault.contains("..") + || vault.contains('\0') + { + anyhow::bail!( + "Invalid vault ID: must not contain path separators, '..', or null bytes" ); } - - let pool_with_timestamp = pools - .get_mut(vault) - .expect("Pool was just inserted or already exists"); - - // Update last accessed time - pool_with_timestamp.last_accessed = Instant::now(); - - Ok(pool_with_timestamp.pool.clone()) + Ok(()) } - /// Attempting to write from this transaction might result in a - /// database locked error. Use this transaction for read-only operations. - pub async fn create_readonly_transaction( - &self, - vault: &VaultId, - ) -> Result> { - self.get_connection_pool(vault) - .await? - .begin() - .await - .context("Cannot create transaction") - } + async fn get_vault_pools(&self, vault: &VaultId) -> Result { + Self::validate_vault_id(vault)?; - pub async fn create_write_transaction(&self, vault: &VaultId) -> Result> { - let mut transaction = self.create_readonly_transaction(vault).await?; + // Get or create the VaultPool entry. The global lock is held only + // long enough for a HashMap lookup/insert — never across + // create_vault_database. + let vault_pool = { + let mut pools = self.connection_pools.lock().await; + pools + .entry(vault.clone()) + .or_insert_with(|| { + Arc::new(VaultPool { + cell: Arc::new(OnceCell::new()), + last_accessed_ms: AtomicU64::new(self.now_ms()), + }) + }) + .clone() + }; - // sqlx doesn't support immediate transactions for sqlite: https://github.com/launchbadge/sqlx/issues/481 - sqlx::query!("END; BEGIN IMMEDIATE;") - .execute(&mut *transaction) + // OnceCell::get_or_try_init guarantees exactly-once + // initialization: concurrent callers for the same vault wait + // here; callers for other vaults are not blocked. + let config = self.config.clone(); + let vault_clone = vault.clone(); + let pools = vault_pool + .cell + .get_or_try_init(|| async { Self::create_vault_database(&config, &vault_clone).await }) .await?; - Ok(transaction) + vault_pool + .last_accessed_ms + .store(self.now_ms(), Ordering::Relaxed); + Ok(pools.clone()) } - /// Return the latest state of all documents in the vault + /// Return the reader pool for read-only queries. + async fn get_connection_pool(&self, vault: &VaultId) -> Result> { + Ok(self.get_vault_pools(vault).await?.reader) + } + + pub async fn create_write_transaction(&self, vault: &VaultId) -> Result { + let write_lock = { + let mut locks = self.write_locks.lock().await; + locks + .entry(vault.clone()) + .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(()))) + .clone() + }; + let write_guard = write_lock.lock_owned().await; + let pools = self.get_vault_pools(vault).await?; + WriteTransaction::new(&pools.writer, write_guard).await + } + + /// Return the latest state of all documents in the vault, optionally + /// bounded above by `up_to_vault_update_id` so that the result is a + /// stable snapshot at exactly that cursor (commits past the cursor + /// will be delivered separately via the broadcast channel). pub async fn get_latest_documents( &self, vault: &VaultId, - transaction: Option<&mut Transaction<'_>>, + up_to_vault_update_id: Option, + connection: Option<&mut SqliteConnection>, ) -> Result> { + // `i64::MAX` makes the upper bound a no-op for callers that don't + // care about an exact snapshot (they pass `None`). + let upper = up_to_vault_update_id.unwrap_or(i64::MAX); let query = sqlx::query!( r#" select vault_update_id, + creation_vault_update_id, document_id as "document_id: Hyphenated", relative_path, updated_date as "updated_date: chrono::DateTime", @@ -194,12 +459,14 @@ impl Database { device_id, length(content) as "content_size: u64" from latest_document_versions + where vault_update_id <= ? order by vault_update_id "#, + upper, ); - if let Some(transaction) = transaction { - query.fetch_all(&mut **transaction).await + if let Some(conn) = connection { + query.fetch_all(&mut *conn).await } else { query .fetch_all(&self.get_connection_pool(vault).await?) @@ -216,42 +483,72 @@ impl Database { is_deleted: row.is_deleted, user_id: row.user_id, device_id: row.device_id, - content_size: row - .content_size - .expect("Content size can't be null but sqlx can't infer it"), + content_size: row.content_size.unwrap_or(0), + is_new_file: row.creation_vault_update_id == row.vault_update_id, }) .collect() }) } /// Return the latest state of all documents (including deleted) in the - /// vault which have changed since the given update id + /// vault which have changed since the given update id, bounded above + /// by `up_to_vault_update_id` so the catch-up result is a stable + /// snapshot at exactly that cursor. Commits past the cursor will be + /// delivered separately via the broadcast channel. pub async fn get_latest_documents_since( &self, vault: &VaultId, vault_update_id: VaultUpdateId, - transaction: Option<&mut Transaction<'_>>, + up_to_vault_update_id: Option, + connection: Option<&mut SqliteConnection>, ) -> Result> { + // `i64::MAX` makes the upper bound a no-op for callers that don't + // care about an exact snapshot (they pass `None`). + let upper = up_to_vault_update_id.unwrap_or(i64::MAX); + // Compute "latest version as of `upper`" per document — NOT + // global latest. The `latest_document_versions` view is keyed + // on global max, so a write that commits between the catch-up's + // cursor capture (under broadcast send-lock) and this query + // (which runs after drop-lock) would expose a `vault_update_id + // > cursor` row that the cursor filter then drops, removing + // the doc from the catch-up entirely. The post-cursor live + // broadcast then carries `is_new_file = false` (per real-time + // semantics it's an update of a previously-existing version), + // and the receiving client — which has no record of the doc — + // ignores it as stale, stranding the doc forever. Computing + // the snapshot from the documents table directly with the + // upper bound applied at the GROUP BY layer keeps the + // catch-up self-contained at exactly the cursor. let query = sqlx::query!( r#" select - vault_update_id, - document_id as "document_id: Hyphenated", - relative_path, - updated_date as "updated_date: chrono::DateTime", - is_deleted, - user_id, - device_id, - length(content) as "content_size: u64" - from latest_document_versions - where vault_update_id > ? - order by vault_update_id + d.vault_update_id, + d.creation_vault_update_id, + d.document_id as "document_id: Hyphenated", + d.relative_path, + d.updated_date as "updated_date: chrono::DateTime", + d.is_deleted, + d.user_id, + d.device_id, + length(d.content) as "content_size: u64" + from documents d + inner join ( + select document_id, max(vault_update_id) as max_vid + from documents + where vault_update_id <= ? + group by document_id + ) latest_at_cursor + on d.document_id = latest_at_cursor.document_id + and d.vault_update_id = latest_at_cursor.max_vid + where d.vault_update_id > ? + order by d.vault_update_id "#, - vault_update_id + upper, + vault_update_id, ); - if let Some(transaction) = transaction { - query.fetch_all(&mut **transaction).await + if let Some(conn) = connection { + query.fetch_all(&mut *conn).await } else { query .fetch_all(&self.get_connection_pool(vault).await?) @@ -270,9 +567,18 @@ impl Database { is_deleted: row.is_deleted, user_id: row.user_id, device_id: row.device_id, - content_size: row - .content_size - .expect("Content size can't be null but sqlx can't infer it"), + content_size: row.content_size.unwrap_or(0), + // For catch-up streams, "new file" means "new to this + // recipient" — the doc was created past the recipient's + // watermark. The catch-up only carries the doc's + // *latest* version (not its full history), so using + // `creation == latest` instead would mis-flag every + // doc that was created and then updated before the + // client reconnected, and the client's + // `processRemoteChange` would drop it as "stale + // RemoteChange for untracked, non-new document", + // silently leaking docs to clients catching up. + is_new_file: row.creation_vault_update_id > vault_update_id, }) .collect() }) @@ -281,7 +587,7 @@ impl Database { pub async fn get_max_update_id_in_vault( &self, vault: &VaultId, - transaction: Option<&mut Transaction<'_>>, + connection: Option<&mut SqliteConnection>, ) -> Result { let query = sqlx::query!( r#" @@ -290,8 +596,8 @@ impl Database { "#, ); - if let Some(transaction) = transaction { - query.fetch_one(&mut **transaction).await + if let Some(conn) = connection { + query.fetch_one(&mut *conn).await } else { query .fetch_one(&self.get_connection_pool(vault).await?) @@ -301,17 +607,18 @@ impl Database { .context("Cannot fetch max update id in vault") } - pub async fn get_latest_document_by_path( + pub async fn get_latest_non_deleted_document_by_path( &self, vault: &VaultId, relative_path: &str, - transaction: Option<&mut Transaction<'_>>, + connection: Option<&mut SqliteConnection>, ) -> Result> { let query = sqlx::query_as!( StoredDocumentVersion, r#" select vault_update_id, + creation_vault_update_id, document_id as "document_id: Hyphenated", relative_path, updated_date as "updated_date: chrono::DateTime", @@ -330,8 +637,8 @@ impl Database { relative_path ); - if let Some(transaction) = transaction { - query.fetch_optional(&mut **transaction).await + if let Some(conn) = connection { + query.fetch_optional(&mut *conn).await } else { query .fetch_optional(&self.get_connection_pool(vault).await?) @@ -340,11 +647,79 @@ impl Database { .context("Cannot fetch latest document version") } + /// Find a doc whose CREATE was authored by this device with + /// matching content, and whose creation the requesting client + /// hasn't observed yet (`creation_vault_update_id > last_seen`). + /// Used by `create_document` to recover from a "lost create" + /// race: this device's create response was discarded mid-flight, + /// so the retry comes in as a brand-new create — possibly at a + /// renamed path. Binding the retry to the existing doc avoids + /// duplicating the content under a deconflicted path. + /// + /// Matches against the doc's CREATION version (not the latest) + /// because a same-path concurrent create from another agent may + /// have merged into our doc since: the latest version's content + /// is the merge result, not what we originally sent. Joining on + /// `creation_vault_update_id` recovers the original bytes. + /// + /// The `device_id` + `creation > last_seen` combination scopes + /// the dedup to "we genuinely lost track of our own create"; + /// another agent's same-content doc won't match because of + /// `device_id`, and a doc this client already saw won't match + /// because of the watermark check. + pub async fn find_unseen_lost_create_by_device_and_content( + &self, + vault: &VaultId, + device_id: &str, + last_seen_vault_update_id: VaultUpdateId, + content: &[u8], + connection: Option<&mut SqliteConnection>, + ) -> Result> { + let query = sqlx::query_as!( + StoredDocumentVersion, + r#" + select + lv.vault_update_id, + lv.creation_vault_update_id, + lv.document_id as "document_id: Hyphenated", + lv.relative_path, + lv.updated_date as "updated_date: chrono::DateTime", + lv.content, + lv.is_deleted, + lv.user_id, + lv.device_id, + lv.has_been_merged + from latest_document_versions lv + inner join documents creation + on creation.document_id = lv.document_id + and creation.vault_update_id = lv.creation_vault_update_id + where creation.device_id = ? + and creation.content = ? + and lv.is_deleted = false + and lv.creation_vault_update_id > ? + order by lv.creation_vault_update_id desc + limit 1 + "#, + device_id, + content, + last_seen_vault_update_id, + ); + + if let Some(conn) = connection { + query.fetch_optional(&mut *conn).await + } else { + query + .fetch_optional(&self.get_connection_pool(vault).await?) + .await + } + .context("Cannot fetch lost-create candidate") + } + pub async fn get_latest_document( &self, vault: &VaultId, document_id: &DocumentId, - transaction: Option<&mut Transaction<'_>>, + connection: Option<&mut SqliteConnection>, ) -> Result> { let document_id = document_id.as_hyphenated(); let query = sqlx::query_as!( @@ -352,6 +727,7 @@ impl Database { r#" select vault_update_id, + creation_vault_update_id, document_id as "document_id: Hyphenated", relative_path, updated_date as "updated_date: chrono::DateTime", @@ -366,8 +742,8 @@ impl Database { document_id ); - if let Some(transaction) = transaction { - query.fetch_optional(&mut **transaction).await + if let Some(conn) = connection { + query.fetch_optional(&mut *conn).await } else { query .fetch_optional(&self.get_connection_pool(vault).await?) @@ -380,13 +756,14 @@ impl Database { &self, vault: &VaultId, vault_update_id: VaultUpdateId, - transaction: Option<&mut Transaction<'_>>, + connection: Option<&mut SqliteConnection>, ) -> Result> { let query = sqlx::query_as!( StoredDocumentVersion, r#" select vault_update_id, + creation_vault_update_id, document_id as "document_id: Hyphenated", relative_path, updated_date as "updated_date: chrono::DateTime", @@ -400,8 +777,8 @@ impl Database { vault_update_id ); - if let Some(transaction) = transaction { - query.fetch_optional(&mut **transaction).await + if let Some(conn) = connection { + query.fetch_optional(&mut *conn).await } else { query .fetch_optional(&self.get_connection_pool(vault).await?) @@ -410,105 +787,307 @@ impl Database { .context("Cannot fetch document version") } - // inserting the document must be the last step of the transaction if there's one + // inserting the document must be the last step of the transaction pub async fn insert_document_version( &self, vault_id: &VaultId, version: &StoredDocumentVersion, - transaction: Option>, + mut transaction: WriteTransaction, ) -> Result<()> { let document_id = version.document_id.as_hyphenated(); let query = sqlx::query!( r#" insert into documents ( vault_update_id, + creation_vault_update_id, document_id, relative_path, updated_date, content, is_deleted, user_id, - device_id + device_id, + has_been_merged ) - values (?, ?, ?, ?, ?, ?, ?, ?) + values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "#, version.vault_update_id, + version.creation_vault_update_id, document_id, version.relative_path, version.updated_date, version.content, version.is_deleted, version.user_id, - version.device_id + version.device_id, + version.has_been_merged ); - if let Some(mut transaction) = transaction { - query - .execute(&mut *transaction) - .await - .context("Cannot insert document version")?; + // Acquire the broadcast send lock before the insert so that + // broadcasts are serialized in vault_update_id order even after + // the write transaction (and its per-vault lock) is released. + let _send_guard = self.broadcasts.acquire_send_lock(vault_id).await; - transaction - .commit() - .await - .context("Failed to commit transaction")?; + query + .execute(&mut *transaction) + .await + .context("Cannot insert document version")?; + + transaction + .commit() + .await + .context("Failed to commit transaction")?; + + // For non-delete writes the originating device already has + // authoritative state from its HTTP response, so we tag the + // broadcast with `origin_device_id` and the send task in + // `websocket.rs` filters it out for that device. Deletes are + // delivered to *every* connected client including the author — + // the originator only removes the document from its sync queue + // once it receives this receipt. + let envelope = WebSocketServerMessage::VaultUpdate(WebSocketVaultUpdate { + document: version.clone().into(), + }); + let with_origin = if version.is_deleted { + WebSocketServerMessageWithOrigin::new(envelope) } else { - query - .execute(&self.get_connection_pool(vault_id).await?) - .await - .context("Cannot insert document version")?; - } - + WebSocketServerMessageWithOrigin::with_origin(version.device_id.clone(), envelope) + }; self.broadcasts - .send_document_update( - vault_id.clone(), - WebSocketServerMessageWithOrigin::with_origin( - version.device_id.clone(), - WebSocketServerMessage::VaultUpdate(WebSocketVaultUpdate { - documents: vec![version.clone().into()], - is_initial_sync: false, - }), - ), - ) - .await; + .send_document_update(vault_id.clone(), with_origin); Ok(()) } + /// Return all versions (without content) of a specific document, ordered by `vault_update_id` + pub async fn get_document_versions( + &self, + vault: &VaultId, + document_id: &DocumentId, + connection: Option<&mut SqliteConnection>, + ) -> Result> { + let document_id = document_id.as_hyphenated(); + let query = sqlx::query!( + r#" + select + vault_update_id, + creation_vault_update_id, + document_id as "document_id: Hyphenated", + relative_path, + updated_date as "updated_date: chrono::DateTime", + is_deleted, + user_id, + device_id, + length(content) as "content_size: u64" + from documents + where document_id = ? + order by vault_update_id + "#, + document_id, + ); + + if let Some(conn) = connection { + query.fetch_all(&mut *conn).await + } else { + query + .fetch_all(&self.get_connection_pool(vault).await?) + .await + } + .with_context(|| format!("Cannot fetch document versions for document `{document_id}`")) + .map(|rows| { + rows.into_iter() + .map(|row| DocumentVersionWithoutContent { + vault_update_id: row.vault_update_id, + document_id: row.document_id.into(), + relative_path: row.relative_path, + updated_date: row.updated_date, + is_deleted: row.is_deleted, + user_id: row.user_id, + device_id: row.device_id, + content_size: row.content_size.unwrap_or(0), + is_new_file: row.creation_vault_update_id == row.vault_update_id, + }) + .collect() + }) + } + + /// Return all versions across all documents, paginated, ordered by `vault_update_id` DESC + pub async fn get_vault_history( + &self, + vault: &VaultId, + limit: i64, + before_update_id: Option, + connection: Option<&mut SqliteConnection>, + ) -> Result> { + let map_row = |row: models::VaultHistoryRow| DocumentVersionWithoutContent { + vault_update_id: row.vault_update_id, + document_id: row.document_id, + relative_path: row.relative_path, + updated_date: row.updated_date, + is_deleted: row.is_deleted, + user_id: row.user_id, + device_id: row.device_id, + content_size: row.content_size.unwrap_or(0), + is_new_file: row.creation_vault_update_id == row.vault_update_id, + }; + + if let Some(before) = before_update_id { + let query = sqlx::query_as!( + models::VaultHistoryRow, + r#" + select + vault_update_id, + creation_vault_update_id, + document_id as "document_id: Hyphenated", + relative_path, + updated_date as "updated_date: chrono::DateTime", + is_deleted, + user_id, + device_id, + length(content) as "content_size: u64" + from documents + where vault_update_id < ? + order by vault_update_id desc + limit ? + "#, + before, + limit, + ); + + let rows = if let Some(conn) = connection { + query.fetch_all(&mut *conn).await + } else { + query + .fetch_all(&self.get_connection_pool(vault).await?) + .await + } + .context("Cannot fetch vault history")?; + + Ok(rows.into_iter().map(map_row).collect()) + } else { + let query = sqlx::query_as!( + models::VaultHistoryRow, + r#" + select + vault_update_id, + creation_vault_update_id, + document_id as "document_id: Hyphenated", + relative_path, + updated_date as "updated_date: chrono::DateTime", + is_deleted, + user_id, + device_id, + length(content) as "content_size: u64" + from documents + order by vault_update_id desc + limit ? + "#, + limit, + ); + + let rows = if let Some(conn) = connection { + query.fetch_all(&mut *conn).await + } else { + query + .fetch_all(&self.get_connection_pool(vault).await?) + .await + } + .context("Cannot fetch vault history")?; + + Ok(rows.into_iter().map(map_row).collect()) + } + } + /// Cleanup idle connection pools that haven't been accessed in more than 5 minutes async fn cleanup_idle_pools(&self) { - let mut pools = self.connection_pools.lock().await; - let now = Instant::now(); - let idle_timeout = Duration::from_secs(5 * 60); // 5 minutes + // Collect idle vaults and remove them from the map while holding + // the lock briefly. Close pools OUTSIDE the lock so that + // pool.close().await doesn't block other get_connection_pool calls. + let idle_pools: Vec<(VaultId, Arc)> = { + let mut pools = self.connection_pools.lock().await; + let now_ms = self.now_ms(); + let idle_threshold_ms = IDLE_POOL_TIMEOUT.as_millis() as u64; - // Collect vaults to remove - let vaults_to_remove: Vec = pools - .iter() - .filter(|(_, pool_with_timestamp)| { - now.duration_since(pool_with_timestamp.last_accessed) > idle_timeout + let vaults_to_remove: Vec = pools + .iter() + .filter(|(_, vp)| { + let last = vp.last_accessed_ms.load(Ordering::Relaxed); + now_ms.saturating_sub(last) > idle_threshold_ms + }) + .map(|(vault_id, _)| vault_id.clone()) + .collect(); + + vaults_to_remove + .into_iter() + .filter_map(|id| pools.remove(&id).map(|vp| (id, vp))) + .collect() + }; + + // Close pools concurrently so cleanup doesn't serialise across vaults + let closures: Vec<_> = idle_pools + .into_iter() + .filter_map(|(vault_id, vault_pool)| { + vault_pool + .cell + .get() + .cloned() + .map(|pools| (vault_id, pools)) }) - .map(|(vault_id, _)| vault_id.clone()) .collect(); - // Close and remove idle pools - for vault_id in &vaults_to_remove { - if let Some(pool_with_timestamp) = pools.remove(vault_id) { - info!("Closing idle database connection pool for vault `{vault_id}`"); - pool_with_timestamp.pool.close().await; - } + let handles: Vec<_> = closures + .into_iter() + .map(|(vault_id, pools)| { + tokio::spawn(async move { + // Checkpoint the WAL before closing to reclaim disk space. + // Run on the blocking pool so disk I/O doesn't starve the runtime + let writer_clone = pools.writer.clone(); + let ckpt_result = tokio::task::spawn_blocking(move || { + futures::executor::block_on( + sqlx::query("PRAGMA wal_checkpoint(TRUNCATE)").execute(&writer_clone), + ) + }) + .await; + + match ckpt_result { + Ok(Err(e)) => { + log::warn!("WAL checkpoint failed for vault `{vault_id}`: {e}"); + } + Err(e) => { + log::warn!("WAL checkpoint task panicked for vault `{vault_id}`: {e}"); + } + _ => {} + } + + info!("Closing idle database connection pools for vault `{vault_id}`"); + pools.reader.close().await; + pools.writer.close().await; + }) + }) + .collect(); + + for handle in handles { + let _ = handle.await; } } /// Start a background task that periodically cleans up idle connection pools - fn start_idle_pool_cleanup(&self) { + fn start_idle_pool_cleanup(&self, mut shutdown: tokio::sync::watch::Receiver<()>) { let database = self.clone(); tokio::spawn(async move { let mut interval = tokio::time::interval(Duration::from_secs(60)); // Check every minute interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); loop { - interval.tick().await; - database.cleanup_idle_pools().await; + tokio::select! { + _ = interval.tick() => { + database.cleanup_idle_pools().await; + } + _ = shutdown.changed() => { + info!("Idle pool cleanup task shutting down"); + break; + } + } } }); } diff --git a/sync-server/src/app_state/database/migrations/20260314000000_add_idempotency_key.sql b/sync-server/src/app_state/database/migrations/20260314000000_add_idempotency_key.sql new file mode 100644 index 00000000..f3ee8dd3 --- /dev/null +++ b/sync-server/src/app_state/database/migrations/20260314000000_add_idempotency_key.sql @@ -0,0 +1,2 @@ +CREATE INDEX IF NOT EXISTS idx_documents_document_id +ON documents (document_id, vault_update_id); diff --git a/sync-server/src/app_state/database/migrations/20260421000000_add_creation_vault_update_id.sql b/sync-server/src/app_state/database/migrations/20260421000000_add_creation_vault_update_id.sql new file mode 100644 index 00000000..40dc85fb --- /dev/null +++ b/sync-server/src/app_state/database/migrations/20260421000000_add_creation_vault_update_id.sql @@ -0,0 +1,20 @@ +ALTER TABLE documents ADD COLUMN creation_vault_update_id INTEGER NOT NULL DEFAULT 0; + +UPDATE documents +SET creation_vault_update_id = ( + SELECT MIN(d2.vault_update_id) + FROM documents d2 + WHERE d2.document_id = documents.document_id +); + +DROP VIEW latest_document_versions; + +CREATE VIEW IF NOT EXISTS latest_document_versions AS --recreate view as it now includes one more field +SELECT d.* +FROM documents d +INNER JOIN ( + SELECT MAX(vault_update_id) AS max_version_id + FROM documents + GROUP BY document_id +) max_versions +ON d.vault_update_id = max_versions.max_version_id; diff --git a/sync-server/src/app_state/database/models.rs b/sync-server/src/app_state/database/models.rs index a216125a..89867067 100644 --- a/sync-server/src/app_state/database/models.rs +++ b/sync-server/src/app_state/database/models.rs @@ -13,6 +13,7 @@ pub type DeviceId = String; #[derive(Debug, Clone)] pub struct StoredDocumentVersion { pub vault_update_id: VaultUpdateId, + pub creation_vault_update_id: VaultUpdateId, pub document_id: DocumentId, pub relative_path: String, pub updated_date: DateTime, @@ -33,7 +34,7 @@ impl PartialEq for StoredDocumentVersion { #[derive(TS, Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct DocumentVersionWithoutContent { - #[ts(as = "i32")] + #[ts(type = "number")] pub vault_update_id: VaultUpdateId, pub document_id: DocumentId, @@ -43,12 +44,16 @@ pub struct DocumentVersionWithoutContent { pub user_id: UserId, pub device_id: DeviceId, - #[ts(as = "i32")] + #[ts(type = "number")] pub content_size: u64, + + /// True iff this is the first version of the document + pub is_new_file: bool, } impl From for DocumentVersionWithoutContent { fn from(value: StoredDocumentVersion) -> Self { + let is_new_file = value.creation_vault_update_id == value.vault_update_id; Self { vault_update_id: value.vault_update_id, document_id: value.document_id, @@ -58,6 +63,7 @@ impl From for DocumentVersionWithoutContent { user_id: value.user_id, device_id: value.device_id, content_size: value.content.len() as u64, + is_new_file, } } } @@ -65,7 +71,7 @@ impl From for DocumentVersionWithoutContent { #[derive(TS, Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct DocumentVersion { - #[ts(as = "i32")] + #[ts(type = "number")] pub vault_update_id: VaultUpdateId, pub document_id: DocumentId, @@ -77,6 +83,25 @@ pub struct DocumentVersion { pub device_id: DeviceId, } +/// Row struct for vault history queries (used by `sqlx::query_as!`) +#[derive(Debug)] +pub struct VaultHistoryRow { + pub vault_update_id: VaultUpdateId, + pub creation_vault_update_id: VaultUpdateId, + pub document_id: DocumentId, + pub relative_path: String, + pub updated_date: DateTime, + pub is_deleted: bool, + pub user_id: String, + pub device_id: String, + pub content_size: Option, +} + +pub struct VaultStats { + pub created_at: Option>, + pub document_count: u32, +} + impl From for DocumentVersion { fn from(value: StoredDocumentVersion) -> Self { Self { From 4ba439b874ef7addd488ae9100c54fcb3e5d413c Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Fri, 8 May 2026 21:35:41 +0100 Subject: [PATCH 04/17] split: server REST endpoints + rate limiting server.rs router rewrite, auth.rs, device_id_header.rs, requests.rs, responses.rs, plus per-endpoint changes: create/update/delete_document, fetch_document_version{,_content,s}, fetch_latest_documents, index.rs. Adds: fetch_vault_history, list_vaults, rate_limit (new files). --- sync-server/src/server.rs | 141 ++++++++---- sync-server/src/server/auth.rs | 20 +- sync-server/src/server/create_document.rs | 155 ++++++++++--- sync-server/src/server/delete_document.rs | 40 ++-- sync-server/src/server/device_id_header.rs | 29 ++- .../src/server/fetch_document_version.rs | 4 +- .../server/fetch_document_version_content.rs | 4 +- .../src/server/fetch_document_versions.rs | 42 ++++ .../src/server/fetch_latest_documents.rs | 4 +- sync-server/src/server/fetch_vault_history.rs | 70 ++++++ sync-server/src/server/index.rs | 80 ++++++- sync-server/src/server/list_vaults.rs | 82 +++++++ sync-server/src/server/rate_limit.rs | 102 +++++++++ sync-server/src/server/requests.rs | 27 +-- sync-server/src/server/responses.rs | 32 ++- sync-server/src/server/update_document.rs | 208 +++++++++++------- 16 files changed, 838 insertions(+), 202 deletions(-) create mode 100644 sync-server/src/server/fetch_document_versions.rs create mode 100644 sync-server/src/server/fetch_vault_history.rs create mode 100644 sync-server/src/server/list_vaults.rs create mode 100644 sync-server/src/server/rate_limit.rs diff --git a/sync-server/src/server.rs b/sync-server/src/server.rs index 01b09cf6..934e9428 100644 --- a/sync-server/src/server.rs +++ b/sync-server/src/server.rs @@ -4,27 +4,30 @@ mod delete_document; mod device_id_header; mod fetch_document_version; mod fetch_document_version_content; +mod fetch_document_versions; mod fetch_latest_document_version; mod fetch_latest_documents; +mod fetch_vault_history; mod index; +mod list_vaults; mod ping; +mod rate_limit; mod requests; mod responses; mod update_document; mod websocket; -use anyhow::{Context as _, Result, anyhow}; +use anyhow::{Context as _, Result}; use auth::auth_middleware; use axum::{ Router, extract::{DefaultBodyLimit, Request}, http::{self, HeaderValue, Method}, middleware, - response::IntoResponse, routing::{IntoMakeService, delete, get, post, put}, }; use device_id_header::DEVICE_ID_HEADER_NAME; -use log::info; +use log::{info, warn}; use tokio::signal; use tower_http::{ LatencyUnit, @@ -41,7 +44,7 @@ use tracing::{Level, info_span}; use crate::{ app_state::AppState, config::{Config, server_config::ServerConfig}, - errors::{client_error, not_found_error}, + consts::GRACEFUL_SHUTDOWN_TIMEOUT, }; pub async fn create_server(config: Config) -> Result<()> { @@ -51,26 +54,33 @@ pub async fn create_server(config: Config) -> Result<()> { let server_config = app_state.config.server.clone(); - let app = Router::new() + let mut app = Router::new() .nest("/", get_authed_routes(app_state.clone())) .route("/", get(index::index)) + .route("/assets/*path", get(index::spa_assets)) + .route("/vaults", get(list_vaults::list_vaults)) .route("/vaults/:vault_id/ping", get(ping::ping)) .route("/vaults/:vault_id/ws", get(websocket::websocket_handler)) + .fallback(index::spa_fallback); + + let cors_layer = build_cors_layer(&server_config).context("Invalid CORS configuration")?; + + if let Some(rate_limit) = server_config.rate_limit_per_user_per_second { + info!("Rate limiting enabled: {rate_limit} requests/second per user"); + let limiter = rate_limit::RateLimiter::new(rate_limit); + app = app.layer(middleware::from_fn_with_state( + limiter, + rate_limit::rate_limit_middleware, + )); + } + + let app = app .layer(DefaultBodyLimit::disable()) .layer(RequestBodyLimitLayer::new( app_state.config.server.max_body_size_mb * 1024 * 1024, )) .layer(TimeoutLayer::new(server_config.response_timeout)) - .layer( - CorsLayer::new() - .allow_origin("*".parse::().expect("Failed to parse origin")) - .allow_headers([ - http::header::CONTENT_TYPE, - http::header::AUTHORIZATION, - DEVICE_ID_HEADER_NAME.clone(), - ]) - .allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE]), - ) + .layer(cors_layer) .layer( TraceLayer::new_for_http() .make_span_with(|request: &Request<_>| { @@ -90,12 +100,39 @@ pub async fn create_server(config: Config) -> Result<()> { .on_eos(DefaultOnEos::new()) .on_failure(DefaultOnFailure::new().level(Level::ERROR)), ) - .with_state(app_state) - .fallback(handle_404) - .fallback(handle_405) + .with_state(app_state.clone()) .into_make_service(); - start_server(app, &server_config).await + start_server(app, &server_config, app_state).await +} + +fn build_cors_layer(server_config: &ServerConfig) -> Result { + let origins = &server_config.allowed_origins; + + let cors = if origins.len() == 1 && origins[0] == "*" { + info!("CORS: allowing all origins"); + let header: HeaderValue = "*" + .parse() + .context("Failed to parse wildcard CORS origin")?; + CorsLayer::new().allow_origin(header) + } else { + let parsed: Vec = origins + .iter() + .map(|o| { + o.parse::() + .with_context(|| format!("Failed to parse CORS origin: `{o}`")) + }) + .collect::>>()?; + CorsLayer::new().allow_origin(parsed) + }; + + Ok(cors + .allow_headers([ + http::header::CONTENT_TYPE, + http::header::AUTHORIZATION, + DEVICE_ID_HEADER_NAME.clone(), + ]) + .allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE])) } fn get_authed_routes(app_state: AppState) -> Router { @@ -120,6 +157,10 @@ fn get_authed_routes(app_state: AppState) -> Router { "/vaults/:vault_id/documents/:document_id/text", put(update_document::update_text), ) + .route( + "/vaults/:vault_id/documents/:document_id/versions", + get(fetch_document_versions::fetch_document_versions), + ) .route( "/vaults/:vault_id/documents/:document_id/versions/:vault_update_id", get(fetch_document_version::fetch_document_version), @@ -132,10 +173,18 @@ fn get_authed_routes(app_state: AppState) -> Router { "/vaults/:vault_id/documents/:document_id", delete(delete_document::delete_document), ) + .route( + "/vaults/:vault_id/history", + get(fetch_vault_history::fetch_vault_history), + ) .layer(middleware::from_fn_with_state(app_state, auth_middleware)) } -async fn start_server(app: IntoMakeService, config: &ServerConfig) -> Result<()> { +async fn start_server( + app: IntoMakeService, + config: &ServerConfig, + app_state: AppState, +) -> Result<()> { let address = format!("{}:{}", config.host, config.port); let listener = tokio::net::TcpListener::bind(address.clone()) .await @@ -148,26 +197,46 @@ async fn start_server(app: IntoMakeService, config: &ServerConfig) .context("Failed to get local address")? ); - axum::serve(listener, app) - .with_graceful_shutdown(shutdown_signal()) - .tcp_nodelay(true) - .await - .context("Failed to start server") + let mut shutdown_rx = app_state.subscribe_shutdown(); + + let server = axum::serve(listener, app) + .with_graceful_shutdown(async move { + shutdown_signal().await; + app_state.shutdown(); + }) + .tcp_nodelay(true); + + tokio::select! { + result = server => result.context("Failed to start server"), + () = async { + let _ = shutdown_rx.changed().await; + info!( + "Shutdown signal received, waiting up to {}s for in-flight requests to complete...", + GRACEFUL_SHUTDOWN_TIMEOUT.as_secs() + ); + tokio::time::sleep(GRACEFUL_SHUTDOWN_TIMEOUT).await; + warn!("Graceful shutdown timed out, forcing exit"); + } => Ok(()), + } } async fn shutdown_signal() { let ctrl_c = async { - signal::ctrl_c() - .await - .expect("failed to install Ctrl+C handler"); + if let Err(e) = signal::ctrl_c().await { + log::error!("Failed to install Ctrl+C handler: {e}"); + } }; #[cfg(unix)] let terminate = async { - signal::unix::signal(signal::unix::SignalKind::terminate()) - .expect("failed to install signal handler") - .recv() - .await; + match signal::unix::signal(signal::unix::SignalKind::terminate()) { + Ok(mut signal) => { + signal.recv().await; + } + Err(e) => { + log::error!("Failed to install SIGTERM handler: {e}"); + } + } }; #[cfg(not(unix))] @@ -178,11 +247,3 @@ async fn shutdown_signal() { () = terminate => {}, } } - -async fn handle_404() -> impl IntoResponse { - not_found_error(anyhow!("Page not found")) -} - -async fn handle_405() -> impl IntoResponse { - client_error(anyhow!("Method not allowed")) -} diff --git a/sync-server/src/server/auth.rs b/sync-server/src/server/auth.rs index e56f4acc..7fa45abd 100644 --- a/sync-server/src/server/auth.rs +++ b/sync-server/src/server/auth.rs @@ -9,7 +9,7 @@ use axum_extra::{ TypedHeader, headers::{Authorization, authorization::Bearer}, }; -use log::info; +use log::{debug, info}; use crate::{ app_state::{AppState, database::models::VaultId}, @@ -21,10 +21,12 @@ use crate::{ pub async fn auth_middleware( State(state): State, Path(path_params): Path>, - TypedHeader(auth_header): TypedHeader>, + auth_header: Option>>, mut req: Request, next: Next, ) -> Result { + let auth_header = auth_header + .ok_or_else(|| unauthenticated_error(anyhow::anyhow!("Missing Authorization header")))?; let token = auth_header.token().trim(); let vault_id = normalize_string( path_params @@ -39,20 +41,24 @@ pub async fn auth_middleware( Ok(next.run(req).await) } -pub fn auth(state: &AppState, token: &str, vault_id: &VaultId) -> Result { - let user = state +pub fn authenticate(state: &AppState, token: &str) -> Result { + state .config .users .get_user(token) .cloned() - .ok_or_else(|| unauthenticated_error(anyhow::anyhow!("Invalid token")))?; + .ok_or_else(|| unauthenticated_error(anyhow::anyhow!("Invalid token"))) +} + +pub fn auth(state: &AppState, token: &str, vault_id: &VaultId) -> Result { + let user = authenticate(state, token)?; if match user.vault_access { VaultAccess::AllowAccessToAll => true, VaultAccess::AllowList(AllowListedVaults { ref allowed }) => allowed.contains(vault_id), } { - info!( - "User `{}` is authenticated and is authorised to access to vault `{vault_id}`", + debug!( + "User `{}` is authenticated and is authorised to access vault `{vault_id}`", user.name ); diff --git a/sync-server/src/server/create_document.rs b/sync-server/src/server/create_document.rs index 859c0db4..d772e16a 100644 --- a/sync-server/src/server/create_document.rs +++ b/sync-server/src/server/create_document.rs @@ -11,12 +11,14 @@ use super::{device_id_header::DeviceIdHeader, requests::CreateDocumentVersion}; use crate::{ app_state::{ AppState, - database::models::{DocumentVersionWithoutContent, StoredDocumentVersion, VaultId}, + database::models::{StoredDocumentVersion, VaultId}, }, config::user_config::User, - errors::{SyncServerError, client_error, server_error}, + errors::{SyncServerError, client_error, server_error, write_transaction_error}, + server::{responses::DocumentUpdateResponse, update_document}, utils::{ - find_first_available_path::find_first_available_path, normalize::normalize, + find_first_available_path::find_first_available_path, is_binary::is_binary, + is_file_type_mergable::is_file_type_mergable, normalize::normalize, sanitize_path::sanitize_path, }, }; @@ -30,48 +32,137 @@ pub struct CreateDocumentPathParams { /// Create a new document in case a document with the same doesn't exist /// already. If a document with the same path exists, a new version is created /// with their content merged. +/// +/// Text content must be UTF-8 encoded. Clients are responsible for +/// transcoding other encodings (e.g. UTF-16) to UTF-8 before sending. #[axum::debug_handler] +#[allow(clippy::too_many_lines)] pub async fn create_document( Path(CreateDocumentPathParams { vault_id }): Path, Extension(user): Extension, TypedHeader(device_id): TypedHeader, State(state): State, TypedMultipart(request): TypedMultipart, -) -> Result, SyncServerError> { +) -> Result, SyncServerError> { debug!("Creating document in vault `{vault_id}`"); let mut transaction = state .database .create_write_transaction(&vault_id) .await - .map_err(server_error)?; + .map_err(write_transaction_error)?; - let document_id = match request.document_id { - Some(document_id) => { - let existing_version = state - .database - .get_latest_document(&vault_id, &document_id, Some(&mut transaction)) - .await - .map_err(server_error)?; + let sanitized_relative_path = sanitize_path(&request.relative_path).map_err(client_error)?; + let new_content = request.content.contents.to_vec(); - if existing_version.is_some() { - return Err(client_error(anyhow::anyhow!( - "Document with the same ID `{document_id}` already exists" - ))); - } - - document_id - } - None => uuid::Uuid::new_v4(), - }; - - let last_update_id = state + let latest_version = state .database - .get_max_update_id_in_vault(&vault_id, Some(&mut transaction)) + .get_latest_non_deleted_document_by_path( + &vault_id, + &sanitized_relative_path, + Some(&mut *transaction), + ) + .await + .map_err(server_error)?; + + if let Some(latest_version) = latest_version { + // Only merge with an existing document the client couldn't have + // known about: its creation is newer than the client's last seen + // vault update to avoid creating cycles by merging two documents into one. + // This could happen if both clients know of document A at path P1, + // but client 2 moves it to P2 while client 1 creates a new document at P2, + // then client 1 would merge its new document with the moved version of A at P2 + // that client 2 resulting in two files (P1 and P2) with the same doc id (A). + if latest_version.creation_vault_update_id > request.last_seen_vault_update_id + && latest_version.creation_vault_update_id == latest_version.vault_update_id + // can't allow merging with a moved document as that could create a cycle + { + let is_mergeable_text = is_file_type_mergable( + &sanitized_relative_path, + &state.config.server.mergeable_file_extensions, + ) && !is_binary(&latest_version.content) + && !is_binary(&new_content); + + if is_mergeable_text || new_content == latest_version.content { + return update_document::update_document( + &sanitized_relative_path, + Vec::new(), + vault_id, + latest_version.document_id, + Some(&request.relative_path), + new_content, + user, + device_id, + state, + transaction, + ) + .await; + } + + // For non-mergeable (binary) files with different content, don't + // merge, create a separate document at a deconflicted path so + // neither client's data is silently overwritten. + } + } + + // Lost-create + local rename recovery. If this device has a doc + // the requesting client hasn't seen yet (its create succeeded + // server-side but the response was discarded — e.g. a sync + // reset mid-flight) and the new request carries the same content + // at a different path (the user renamed the file before the + // retry), bind the retry to that existing doc instead of + // creating a duplicate. The dedup is scoped tightly: + // - same `device_id` (only this client's own lost create), + // - `creation_vault_update_id > last_seen` (client never saw + // this doc, so it can't be deliberately creating another + // copy with matching content), + // - `creation == latest` (the doc has only its create version, + // nobody else has touched it; safe to relocate), + // - exact content match. + // Outside that window we fall through to the normal deconflict + // path, so legitimate "this device created a duplicate of an + // already-acknowledged file" flows still produce a new doc. + if let Some(lost_create) = state + .database + .find_unseen_lost_create_by_device_and_content( + &vault_id, + &device_id.0, + request.last_seen_vault_update_id, + &new_content, + Some(&mut *transaction), + ) + .await + .map_err(server_error)? + { + info!( + "Lost-create recovery: binding retry at `{sanitized_relative_path}` to existing doc {} (was at `{}`) in vault `{vault_id}` for device `{}`", + lost_create.document_id, + lost_create.relative_path, + device_id.0 + ); + return update_document::update_document( + &sanitized_relative_path, + Vec::new(), + vault_id, + lost_create.document_id, + Some(&request.relative_path), + new_content, + user, + device_id, + state, + transaction, + ) + .await; + } + + let document_id = uuid::Uuid::new_v4(); + + let last_update_id = state + .database + .get_max_update_id_in_vault(&vault_id, Some(&mut *transaction)) .await .map_err(server_error)?; - let sanitized_relative_path = sanitize_path(&request.relative_path); let deduped_path = find_first_available_path( &vault_id, &sanitized_relative_path, @@ -87,11 +178,13 @@ pub async fn create_document( ); } + let new_vault_update_id = last_update_id + 1; let new_version = StoredDocumentVersion { - vault_update_id: last_update_id + 1, + vault_update_id: new_vault_update_id, + creation_vault_update_id: new_vault_update_id, document_id, relative_path: deduped_path, - content: request.content.contents.to_vec(), + content: new_content, updated_date: chrono::Utc::now(), is_deleted: false, user_id: user.name, @@ -101,9 +194,11 @@ pub async fn create_document( state .database - .insert_document_version(&vault_id, &new_version, Some(transaction)) + .insert_document_version(&vault_id, &new_version, transaction) .await .map_err(server_error)?; - Ok(Json(new_version.into())) + Ok(Json(DocumentUpdateResponse::FastForwardUpdate( + new_version.into(), + ))) } diff --git a/sync-server/src/server/delete_document.rs b/sync-server/src/server/delete_document.rs index e126d6b5..2ee6eac3 100644 --- a/sync-server/src/server/delete_document.rs +++ b/sync-server/src/server/delete_document.rs @@ -1,4 +1,4 @@ -use anyhow::Context; +use anyhow::{Context, anyhow}; use axum::{ Extension, Json, extract::{Path, State}, @@ -7,7 +7,7 @@ use axum_extra::TypedHeader; use log::{debug, info}; use serde::Deserialize; -use super::{device_id_header::DeviceIdHeader, requests::DeleteDocumentVersion}; +use super::device_id_header::DeviceIdHeader; use crate::{ app_state::{ AppState, @@ -16,8 +16,8 @@ use crate::{ }, }, config::user_config::User, - errors::{SyncServerError, server_error}, - utils::{normalize::normalize, sanitize_path::sanitize_path}, + errors::{SyncServerError, not_found_error, server_error, write_transaction_error}, + utils::normalize::normalize, }; #[derive(Deserialize)] @@ -37,7 +37,6 @@ pub async fn delete_document( Extension(user): Extension, TypedHeader(device_id): TypedHeader, State(state): State, - Json(request): Json, ) -> Result, SyncServerError> { debug!("Deleting document `{document_id}` in vault `{vault_id}`"); @@ -45,7 +44,7 @@ pub async fn delete_document( .database .create_write_transaction(&vault_id) .await - .map_err(server_error)?; + .map_err(write_transaction_error)?; let last_update_id = state .database @@ -59,9 +58,18 @@ pub async fn delete_document( .await .map_err(server_error)?; - if let Some(latest_version) = &latest_version - && latest_version.is_deleted - { + let Some(latest_version) = latest_version else { + transaction + .rollback() + .await + .context("Failed to roll back transaction") + .map_err(server_error)?; + return Err(not_found_error(anyhow!( + "Document `{document_id}` not found in vault `{vault_id}`" + ))); + }; + + if latest_version.is_deleted { transaction .rollback() .await @@ -69,15 +77,19 @@ pub async fn delete_document( .map_err(server_error)?; info!("Document `{document_id}` has already been deleted",); - return Ok(Json(latest_version.clone().into())); + return Ok(Json(latest_version.into())); } - let latest_content = latest_version.map_or_else(Vec::new, |version| version.content); // in case the document has never existed before deleting it + let new_vault_update_id = last_update_id + 1; + let latest_relative_path = latest_version.relative_path; + let latest_content = latest_version.content; + let creation_vault_update_id = latest_version.creation_vault_update_id; let new_version = StoredDocumentVersion { - vault_update_id: last_update_id + 1, + vault_update_id: new_vault_update_id, + creation_vault_update_id, document_id, - relative_path: sanitize_path(&request.relative_path), + relative_path: latest_relative_path, content: latest_content, // copy the content from the latest version updated_date: chrono::Utc::now(), is_deleted: true, @@ -88,7 +100,7 @@ pub async fn delete_document( state .database - .insert_document_version(&vault_id, &new_version, Some(transaction)) + .insert_document_version(&vault_id, &new_version, transaction) .await .map_err(server_error)?; diff --git a/sync-server/src/server/device_id_header.rs b/sync-server/src/server/device_id_header.rs index af9d6413..13bd17a8 100644 --- a/sync-server/src/server/device_id_header.rs +++ b/sync-server/src/server/device_id_header.rs @@ -16,20 +16,31 @@ impl Header for DeviceIdHeader { { let value = values.next().ok_or_else(headers::Error::invalid)?; - Ok(DeviceIdHeader( - value - .to_str() - .map_err(|_| headers::Error::invalid())? - .to_owned(), - )) + let s = value.to_str().map_err(|_| headers::Error::invalid())?; + + if s.is_empty() || s.len() > 256 { + return Err(headers::Error::invalid()); + } + + // Only allow safe characters to prevent log injection and similar attacks. + // Covers UUIDs, user-agent strings like "vault-link/1.0 (12345; linux)", + // and human-readable device names. + if !s + .chars() + .all(|c| c.is_ascii_alphanumeric() || "-_./ ();:@+,".contains(c)) + { + return Err(headers::Error::invalid()); + } + + Ok(DeviceIdHeader(s.to_owned())) } fn encode(&self, values: &mut E) where E: Extend, { - let value = HeaderValue::from_static(Box::leak(self.0.clone().into_boxed_str())); - - values.extend(std::iter::once(value)); + if let Ok(value) = HeaderValue::from_str(&self.0) { + values.extend(std::iter::once(value)); + } } } diff --git a/sync-server/src/server/fetch_document_version.rs b/sync-server/src/server/fetch_document_version.rs index c30f1d76..159cad3a 100644 --- a/sync-server/src/server/fetch_document_version.rs +++ b/sync-server/src/server/fetch_document_version.rs @@ -11,7 +11,7 @@ use crate::{ AppState, database::models::{DocumentId, DocumentVersion, VaultId, VaultUpdateId}, }, - errors::{SyncServerError, not_found_error, server_error}, + errors::{SyncServerError, client_error, not_found_error, server_error}, utils::normalize::normalize, }; @@ -52,7 +52,7 @@ pub async fn fetch_document_version( )?; if result.document_id != document_id { - return Err(not_found_error(anyhow!( + return Err(client_error(anyhow!( "Document with document id `{document_id}` does not have a version with id \ `{vault_update_id}`", ))); diff --git a/sync-server/src/server/fetch_document_version_content.rs b/sync-server/src/server/fetch_document_version_content.rs index 9fdd0ad8..a163b036 100644 --- a/sync-server/src/server/fetch_document_version_content.rs +++ b/sync-server/src/server/fetch_document_version_content.rs @@ -11,7 +11,7 @@ use crate::{ AppState, database::models::{DocumentId, VaultId, VaultUpdateId}, }, - errors::{SyncServerError, not_found_error, server_error}, + errors::{SyncServerError, client_error, not_found_error, server_error}, utils::normalize::normalize, }; @@ -52,7 +52,7 @@ pub async fn fetch_document_version_content( )?; if result.document_id != document_id { - return Err(not_found_error(anyhow!( + return Err(client_error(anyhow!( "Document with document id `{document_id}` does not have a version with id \ `{vault_update_id}`", ))); diff --git a/sync-server/src/server/fetch_document_versions.rs b/sync-server/src/server/fetch_document_versions.rs new file mode 100644 index 00000000..46d0e073 --- /dev/null +++ b/sync-server/src/server/fetch_document_versions.rs @@ -0,0 +1,42 @@ +use axum::{ + Json, + extract::{Path, State}, +}; +use log::debug; +use serde::Deserialize; + +use crate::{ + app_state::{ + AppState, + database::models::{DocumentId, DocumentVersionWithoutContent, VaultId}, + }, + errors::{SyncServerError, server_error}, + utils::normalize::normalize, +}; + +#[derive(Deserialize)] +pub struct FetchDocumentVersionsPathParams { + #[serde(deserialize_with = "normalize")] + vault_id: VaultId, + + document_id: DocumentId, +} + +#[axum::debug_handler] +pub async fn fetch_document_versions( + Path(FetchDocumentVersionsPathParams { + vault_id, + document_id, + }): Path, + State(state): State, +) -> Result>, SyncServerError> { + debug!("Fetching all versions for document `{document_id}` in vault `{vault_id}`"); + + let versions = state + .database + .get_document_versions(&vault_id, &document_id, None) + .await + .map_err(server_error)?; + + Ok(Json(versions)) +} diff --git a/sync-server/src/server/fetch_latest_documents.rs b/sync-server/src/server/fetch_latest_documents.rs index 209374ce..f1ca702d 100644 --- a/sync-server/src/server/fetch_latest_documents.rs +++ b/sync-server/src/server/fetch_latest_documents.rs @@ -37,13 +37,13 @@ pub async fn fetch_latest_documents( let documents = if let Some(since_update_id) = since_update_id { state .database - .get_latest_documents_since(&vault_id, since_update_id, None) + .get_latest_documents_since(&vault_id, since_update_id, None, None) .await .map_err(server_error) } else { state .database - .get_latest_documents(&vault_id, None) + .get_latest_documents(&vault_id, None, None) .await .map_err(server_error) }?; diff --git a/sync-server/src/server/fetch_vault_history.rs b/sync-server/src/server/fetch_vault_history.rs new file mode 100644 index 00000000..42cceaa6 --- /dev/null +++ b/sync-server/src/server/fetch_vault_history.rs @@ -0,0 +1,70 @@ +use axum::{ + Json, + extract::{Path, Query, State}, +}; +use log::debug; +use serde::Deserialize; + +use super::responses::VaultHistoryResponse; +use crate::{ + app_state::{ + AppState, + database::models::{VaultId, VaultUpdateId}, + }, + errors::{SyncServerError, client_error, server_error}, + utils::normalize::normalize, +}; + +const DEFAULT_LIMIT: i64 = 50; +const MAX_LIMIT: i64 = 500; + +#[derive(Deserialize)] +pub struct FetchVaultHistoryPathParams { + #[serde(deserialize_with = "normalize")] + vault_id: VaultId, +} + +#[derive(Deserialize)] +pub struct QueryParams { + limit: Option, + before_update_id: Option, +} + +#[axum::debug_handler] +pub async fn fetch_vault_history( + Path(FetchVaultHistoryPathParams { vault_id }): Path, + Query(QueryParams { + limit, + before_update_id, + }): Query, + State(state): State, +) -> Result, SyncServerError> { + if let Some(id) = before_update_id + && id <= 0 + { + return Err(client_error(anyhow::anyhow!( + "before_update_id must be a positive integer" + ))); + } + + let limit = limit.unwrap_or(DEFAULT_LIMIT).clamp(1, MAX_LIMIT); + + debug!( + "Fetching vault history for vault `{vault_id}` (limit={limit}, before={before_update_id:?})" + ); + + // Fetch one extra row to determine if there are more results + let mut versions = state + .database + .get_vault_history(&vault_id, limit + 1, before_update_id, None) + .await + .map_err(server_error)?; + + #[allow(clippy::cast_sign_loss)] // limit is clamped to [1, 500] above + let has_more = versions.len() > limit as usize; + if has_more { + versions.pop(); + } + + Ok(Json(VaultHistoryResponse { versions, has_more })) +} diff --git a/sync-server/src/server/index.rs b/sync-server/src/server/index.rs index 64b053f7..ca8f38ff 100644 --- a/sync-server/src/server/index.rs +++ b/sync-server/src/server/index.rs @@ -1,7 +1,77 @@ -use axum::response::{Html, IntoResponse}; +use axum::{ + body::Body, + extract::{Path, State}, + http::{StatusCode, header}, + response::{Html, IntoResponse, Response}, +}; +use log::warn; +use rust_embed::Embed; -pub async fn index() -> impl IntoResponse { - const HTML_CONTENT: &str = include_str!("./assets/index.html"); - let html_content = HTML_CONTENT; - Html(html_content) +use crate::app_state::AppState; + +#[derive(Embed)] +#[folder = "../frontend/history-ui/dist/"] +struct HistoryUiAssets; + +pub async fn index(State(_state): State) -> impl IntoResponse { + if let Some(content) = HistoryUiAssets::get("index.html") { + Html( + std::str::from_utf8(content.data.as_ref()) + .inspect_err(|e| warn!("Embedded index.html is not valid UTF-8: {e}")) + .unwrap_or("

VaultLink

") + .to_owned(), + ) + .into_response() + } else { + warn!("No embedded index.html found — history UI may not have been built"); + Html("

VaultLink server

".to_owned()).into_response() + } +} + +pub async fn spa_assets(Path(path): Path) -> impl IntoResponse { + // The route is /assets/*path so path is relative to assets/. + // The embedded files include the assets/ prefix from the dist directory. + let full_path = format!("assets/{path}"); + if let Some(content) = HistoryUiAssets::get(&full_path) { + let mime = mime_guess::from_path(&full_path).first_or_octet_stream(); + return Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, mime.as_ref()) + .body(Body::from(content.data.to_vec())) + .unwrap_or_else(|_| { + Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::empty()) + .unwrap_or_else(|_| Response::new(Body::empty())) + }); + } + + // Asset paths must match an embedded file — no SPA fallback. + // Serving index.html here would return 200 with text/html for missing + // .css/.js files, causing the browser to silently ignore the content. + Response::builder() + .status(StatusCode::NOT_FOUND) + .body(Body::from("Not found")) + .unwrap_or_else(|_| Response::new(Body::from("Not found"))) +} + +/// SPA fallback for production: serves index.html for client-side routes +/// (e.g. `/documents/123`). +pub async fn spa_fallback() -> impl IntoResponse { + match HistoryUiAssets::get("index.html") { + Some(content) => Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, "text/html") + .body(Body::from(content.data.to_vec())) + .unwrap_or_else(|_| { + Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::empty()) + .unwrap_or_else(|_| Response::new(Body::empty())) + }), + None => Response::builder() + .status(StatusCode::NOT_FOUND) + .body(Body::from("Not found")) + .unwrap_or_else(|_| Response::new(Body::from("Not found"))), + } } diff --git a/sync-server/src/server/list_vaults.rs b/sync-server/src/server/list_vaults.rs new file mode 100644 index 00000000..7ef23405 --- /dev/null +++ b/sync-server/src/server/list_vaults.rs @@ -0,0 +1,82 @@ +use axum::{ + Json, + extract::{Query, State}, +}; +use axum_extra::{ + TypedHeader, + headers::{Authorization, authorization::Bearer}, +}; +use log::debug; +use serde::Deserialize; + +use super::{ + auth::authenticate, + responses::{ListVaultsResponse, VaultInfo}, +}; +use crate::{ + app_state::AppState, + config::user_config::{AllowListedVaults, VaultAccess}, + errors::{SyncServerError, server_error, unauthenticated_error}, +}; + +const DEFAULT_LIMIT: usize = 50; +const MAX_LIMIT: usize = 200; + +#[derive(Deserialize)] +pub struct QueryParams { + limit: Option, + after: Option, +} + +#[axum::debug_handler] +pub async fn list_vaults( + auth_header: Option>>, + Query(QueryParams { limit, after }): Query, + State(state): State, +) -> Result, SyncServerError> { + let auth_header = auth_header + .ok_or_else(|| unauthenticated_error(anyhow::anyhow!("Missing Authorization header")))?; + + let user = authenticate(&state, auth_header.token().trim())?; + + debug!("User `{}` listing accessible vaults", user.name); + + let existing_vaults = state.database.list_vaults().await.map_err(server_error)?; + + let mut accessible: Vec = match user.vault_access { + VaultAccess::AllowAccessToAll => existing_vaults, + VaultAccess::AllowList(AllowListedVaults { ref allowed }) => existing_vaults + .into_iter() + .filter(|v| allowed.contains(v)) + .collect(), + }; + + // Cursor-based pagination: skip vaults up to and including `after` + if let Some(ref cursor) = after { + accessible.retain(|v| v.as_str() > cursor.as_str()); + } + + let limit = limit.unwrap_or(DEFAULT_LIMIT).clamp(1, MAX_LIMIT); + let has_more = accessible.len() > limit; + accessible.truncate(limit); + + let mut vaults = Vec::with_capacity(accessible.len()); + for name in accessible { + let stats = state + .database + .get_vault_stats(&name) + .await + .map_err(server_error)?; + vaults.push(VaultInfo { + name, + document_count: stats.document_count, + created_at: stats.created_at, + }); + } + + Ok(Json(ListVaultsResponse { + vaults, + has_more, + user_name: user.name, + })) +} diff --git a/sync-server/src/server/rate_limit.rs b/sync-server/src/server/rate_limit.rs new file mode 100644 index 00000000..7792a814 --- /dev/null +++ b/sync-server/src/server/rate_limit.rs @@ -0,0 +1,102 @@ +use std::{ + collections::HashMap, + sync::{Arc, Mutex}, + time::Instant, +}; + +use axum::{extract::Request, http::StatusCode, middleware::Next, response::Response}; +use axum_extra::{ + TypedHeader, + headers::{Authorization, authorization::Bearer}, +}; + +/// Per-user token-bucket rate limiter. Each bearer token gets its own bucket +/// that refills to `max_per_second` tokens every second. +#[derive(Clone, Debug)] +pub struct RateLimiter { + max_per_second: u64, + buckets: Arc>>>, +} + +#[derive(Debug)] +struct TokenBucket { + state: Mutex, + max_tokens: u64, +} + +#[derive(Debug)] +struct BucketState { + tokens: u64, + last_refill: Instant, +} + +impl RateLimiter { + /// Create a new per-user rate limiter. + /// + /// # Panics + /// + /// Panics if `max_per_second` is 0. + pub fn new(max_per_second: u64) -> Self { + assert!( + max_per_second > 0, + "max_per_second must be > 0 (set rate_limit_per_user_per_second to null in config to disable)" + ); + + Self { + max_per_second, + buckets: Arc::new(Mutex::new(HashMap::new())), + } + } + + fn get_or_create_bucket(&self, token: &str) -> Arc { + self.buckets + .lock() + .expect("rate limiter lock poisoned") + .entry(token.to_owned()) + .or_insert_with(|| { + Arc::new(TokenBucket { + state: Mutex::new(BucketState { + tokens: self.max_per_second, + last_refill: Instant::now(), + }), + max_tokens: self.max_per_second, + }) + }) + .clone() + } +} + +impl TokenBucket { + fn try_acquire(&self) -> bool { + let mut state = self.state.lock().expect("token bucket lock poisoned"); + let now = Instant::now(); + if now.duration_since(state.last_refill).as_secs() >= 1 { + state.tokens = self.max_tokens; + state.last_refill = now; + } + if state.tokens > 0 { + state.tokens -= 1; + true + } else { + false + } + } +} + +pub async fn rate_limit_middleware( + axum::extract::State(limiter): axum::extract::State, + auth_header: Option>>, + req: Request, + next: Next, +) -> Result { + let Some(TypedHeader(auth)) = auth_header else { + return Ok(next.run(req).await); + }; + + let bucket = limiter.get_or_create_bucket(auth.token()); + if bucket.try_acquire() { + Ok(next.run(req).await) + } else { + Err(StatusCode::TOO_MANY_REQUESTS) + } +} diff --git a/sync-server/src/server/requests.rs b/sync-server/src/server/requests.rs index 119ad467..232e514d 100644 --- a/sync-server/src/server/requests.rs +++ b/sync-server/src/server/requests.rs @@ -4,18 +4,16 @@ use reconcile_text::NumberOrText; use serde::{self, Deserialize}; use ts_rs::TS; -use crate::app_state::database::models::{DocumentId, VaultUpdateId}; +use crate::app_state::database::models::VaultUpdateId; #[derive(TS, Debug, TryFromMultipart)] #[ts(export)] pub struct CreateDocumentVersion { - /// The client can decide the document id (if it wishes to) in order - /// to help with syncing. If the client does not provide a document id, - /// the server will generate one. If the client provides a document id - /// it must not already exist in the database. - pub document_id: Option, pub relative_path: String, + #[ts(type = "number")] + pub last_seen_vault_update_id: VaultUpdateId, + #[ts(as = "Vec")] #[form_data(limit = "unlimited")] pub content: FieldData, @@ -24,7 +22,9 @@ pub struct CreateDocumentVersion { #[derive(Debug, TryFromMultipart)] pub struct UpdateBinaryDocumentVersion { pub parent_version_id: VaultUpdateId, - pub relative_path: String, + // None on a content-only edit; Some on a user rename. When None, + // the server keeps the document at its current path. + pub relative_path: Option, #[form_data(limit = "unlimited")] pub content: FieldData, @@ -34,18 +34,13 @@ pub struct UpdateBinaryDocumentVersion { #[serde(rename_all = "camelCase")] #[ts(export)] pub struct UpdateTextDocumentVersion { - #[ts(as = "i32")] + #[ts(type = "number")] pub parent_version_id: VaultUpdateId, - pub relative_path: String, + // None on a content-only edit; Some on a user rename. When None, + // the server keeps the document at its current path. + pub relative_path: Option, #[ts(type = "Array")] pub content: Vec, } - -#[derive(TS, Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -#[ts(export)] -pub struct DeleteDocumentVersion { - pub relative_path: String, -} diff --git a/sync-server/src/server/responses.rs b/sync-server/src/server/responses.rs index a8b3fcd7..f5b30782 100644 --- a/sync-server/src/server/responses.rs +++ b/sync-server/src/server/responses.rs @@ -1,3 +1,4 @@ +use chrono::{DateTime, Utc}; use serde::{self, Serialize}; use ts_rs::TS; @@ -36,7 +37,36 @@ pub struct FetchLatestDocumentsResponse { pub last_update_id: VaultUpdateId, } -/// Response to an update document request. +/// Response to a vault history request (paginated). +#[derive(TS, Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +#[ts(export)] +pub struct VaultHistoryResponse { + pub versions: Vec, + pub has_more: bool, +} + +/// Summary of a single vault returned by the list-vaults endpoint. +#[derive(TS, Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +#[ts(export)] +pub struct VaultInfo { + pub name: String, + pub document_count: u32, + pub created_at: Option>, +} + +/// Response to listing vaults accessible to the authenticated user. +#[derive(TS, Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +#[ts(export)] +pub struct ListVaultsResponse { + pub vaults: Vec, + pub has_more: bool, + pub user_name: String, +} + +/// Response to a create/update document request. #[derive(TS, Debug, Clone, Serialize)] #[serde(tag = "type")] #[ts(export)] diff --git a/sync-server/src/server/update_document.rs b/sync-server/src/server/update_document.rs index 00fbd008..0145288c 100644 --- a/sync-server/src/server/update_document.rs +++ b/sync-server/src/server/update_document.rs @@ -16,10 +16,15 @@ use super::{ use crate::{ app_state::{ AppState, - database::models::{DocumentId, StoredDocumentVersion, VaultId, VaultUpdateId}, + database::{ + WriteTransaction, + models::{DocumentId, StoredDocumentVersion, VaultId, VaultUpdateId}, + }, }, config::user_config::User, - errors::{SyncServerError, client_error, not_found_error, server_error}, + errors::{ + SyncServerError, client_error, not_found_error, server_error, write_transaction_error, + }, server::requests::UpdateBinaryDocumentVersion, utils::{ find_first_available_path::find_first_available_path, is_binary::is_binary, @@ -46,18 +51,27 @@ pub async fn update_binary( State(state): State, TypedMultipart(request): TypedMultipart, ) -> Result, SyncServerError> { - let parent_document = get_parent_document(&state, &vault_id, request.parent_version_id).await?; + let parent_document = + get_parent_document(&state, &vault_id, &document_id, request.parent_version_id).await?; let content = request.content.contents.to_vec(); + let transaction = state + .database + .create_write_transaction(&vault_id) + .await + .map_err(write_transaction_error)?; + update_document( - parent_document, + &parent_document.relative_path, + parent_document.content, vault_id, document_id, + request.relative_path.as_deref(), + content, user, device_id, state, - &request.relative_path, - content, + transaction, ) .await } @@ -74,28 +88,36 @@ pub async fn update_text( State(state): State, Json(request): Json, ) -> Result, SyncServerError> { - let parent_document = get_parent_document(&state, &vault_id, request.parent_version_id).await?; + let parent_document = + get_parent_document(&state, &vault_id, &document_id, request.parent_version_id).await?; - let edited_text = EditedText::from_diff( - str::from_utf8(&parent_document.content) - .expect("parent must be valid UTF-8 because it's a text document"), - request.content, - &*BuiltinTokenizer::Word, - ) - .context("Failed to apply given diff to parent document") - .map_err(client_error)?; + let parent_text = str::from_utf8(&parent_document.content) + .context("Parent version contains binary content; use putBinary instead of putText") + .map_err(client_error)?; + + let edited_text = EditedText::from_diff(parent_text, request.content, &*BuiltinTokenizer::Word) + .context("Failed to apply given diff to parent document") + .map_err(client_error)?; let content = edited_text.apply().text().into_bytes(); + let transaction = state + .database + .create_write_transaction(&vault_id) + .await + .map_err(write_transaction_error)?; + update_document( - parent_document, + &parent_document.relative_path, + parent_document.content, vault_id, document_id, + request.relative_path.as_deref(), + content, user, device_id, state, - &request.relative_path, - content, + transaction, ) .await } @@ -103,9 +125,10 @@ pub async fn update_text( async fn get_parent_document( state: &AppState, vault_id: &VaultId, + document_id: &DocumentId, parent_version_id: VaultUpdateId, ) -> Result { - state + let parent = state .database .get_document_version(vault_id, parent_version_id, None) .await @@ -117,29 +140,36 @@ async fn get_parent_document( ))) }, Ok, - ) + )?; + + if &parent.document_id != document_id { + return Err(client_error(anyhow!( + "Parent version `{parent_version_id}` does not belong to document `{document_id}`" + ))); + } + + Ok(parent) } #[allow(clippy::too_many_lines, clippy::too_many_arguments)] -async fn update_document( - parent_document: StoredDocumentVersion, +pub async fn update_document( + parent_relative_path: &str, + parent_content: Vec, vault_id: VaultId, document_id: DocumentId, + relative_path: Option<&str>, + content: Vec, user: User, device_id: DeviceIdHeader, state: AppState, - relative_path: &str, - content: Vec, + mut transaction: WriteTransaction, ) -> Result, SyncServerError> { debug!("Updating document `{document_id}` in vault `{vault_id}`"); - let sanitized_relative_path = sanitize_path(relative_path); - - let mut transaction = state - .database - .create_write_transaction(&vault_id) - .await - .map_err(server_error)?; + let sanitized_relative_path = relative_path + .map(sanitize_path) + .transpose() + .map_err(client_error)?; let last_update_id = state .database @@ -175,9 +205,12 @@ async fn update_document( } // Return the latest version if the content and path are the same as the latest - // version - if content == latest_version.content && sanitized_relative_path == latest_version.relative_path - { + // version. A missing relative_path means "keep current path", so the path + // is implicitly unchanged. + let path_unchanged = sanitized_relative_path + .as_deref() + .is_none_or(|p| p == latest_version.relative_path); + if content == latest_version.content && path_unchanged { info!( "Document content is the same as the latest version for `{document_id}`, skipping update" ); @@ -192,62 +225,89 @@ async fn update_document( ))); } + // For mergability, use whichever path the new version will live at — the + // requested rename target if the client sent one, otherwise the existing + // server-side path. + let mergable_check_path = sanitized_relative_path + .as_deref() + .unwrap_or(&latest_version.relative_path); let are_all_participants_mergable = is_file_type_mergable( - &sanitized_relative_path, + mergable_check_path, &state.config.server.mergeable_file_extensions, - ) && !is_binary(&parent_document.content) + ) && !is_binary(&parent_content) && !is_binary(&latest_version.content) && !is_binary(&content); - let merged_content = if are_all_participants_mergable { + let (merged_content, is_different_from_request_content) = if are_all_participants_mergable { info!("Merging changes for document `{document_id}` in vault `{vault_id}`"); - reconcile( - str::from_utf8(&parent_document.content) - .expect("parent must be valid UTF-8 because it's not binary"), - &str::from_utf8(&latest_version.content) - .expect("latest_version must be valid UTF-8 because it's not binary") - .into(), - &str::from_utf8(&content) - .expect("content must be valid UTF-8 because it's not binary") - .into(), - &*BuiltinTokenizer::Word, - ) - .apply() - .text() - .into_bytes() + let parent_text = str::from_utf8(&parent_content) + .context("Parent document content is not valid UTF-8") + .map_err(client_error)?; + let latest_text = str::from_utf8(&latest_version.content) + .context("Latest version content is not valid UTF-8") + .map_err(client_error)?; + let new_text = str::from_utf8(&content) + .context("New content is not valid UTF-8") + .map_err(client_error)?; + let parent_owned = parent_text.to_owned(); + let latest_owned = latest_text.to_owned(); + let new_owned = new_text.to_owned(); + let content_clone = content.clone(); + + let (merged, is_different) = tokio::task::spawn_blocking(move || { + let merged = reconcile( + &parent_owned, + &latest_owned.into(), + &new_owned.into(), + &*BuiltinTokenizer::Word, + ) + .apply() + .text() + .into_bytes(); + let is_different = merged != content_clone; + (merged, is_different) + }) + .await + .map_err(|e| server_error(anyhow::anyhow!("Reconcile task failed: {e}")))?; + + (merged, is_different) } else { - content.clone() + (content, false) // false means that the client doesn't need to refetch the file as we can ensure the remote and local versions are the same as LWW is the merging method for binary files }; - let is_different_from_request_content = merged_content != content; + // Rename resolution: only apply the client's rename if (a) the client + // requested one (`sanitized_relative_path` is `Some`) and (b) the + // document's path hasn't changed since this client's parent version. + // If the parent and latest paths differ, another client already renamed + // the document — keep the latest path (first rename wins). Content + // changes from both clients are still merged correctly via the 3-way + // reconcile above, independent of which rename wins. A missing + // relative_path means "keep current path" (content-only edit). + let new_relative_path = match sanitized_relative_path.as_deref() { + Some(requested) + if parent_relative_path == latest_version.relative_path + && requested != latest_version.relative_path => + { + let new_path = + find_first_available_path(&vault_id, requested, &state.database, &mut transaction) + .await + .map_err(server_error)?; - // We can only update the relative path if we're the first one to do so - let new_relative_path = if parent_document.relative_path == latest_version.relative_path - && latest_version.relative_path != sanitized_relative_path - { - let new_path = find_first_available_path( - &vault_id, - &sanitized_relative_path, - &state.database, - &mut transaction, - ) - .await - .map_err(server_error)?; + if new_path != requested { + info!( + "Document already exists at new location: `{requested}` when trying to update it in vault `{vault_id}`, deconflicting by creating at `{new_path}`" + ); + } - if new_path != sanitized_relative_path { - info!( - "Document already exists at new location: `{sanitized_relative_path}` when trying to update it in vault `{vault_id}`, deconflicting by creating at `{new_path}`" - ); + new_path } - - new_path - } else { - latest_version.relative_path.clone() + _ => latest_version.relative_path.clone(), }; let new_version = StoredDocumentVersion { document_id, vault_update_id: last_update_id + 1, + creation_vault_update_id: latest_version.creation_vault_update_id, relative_path: new_relative_path, content: merged_content, updated_date: chrono::Utc::now(), @@ -259,7 +319,7 @@ async fn update_document( state .database - .insert_document_version(&vault_id, &new_version, Some(transaction)) + .insert_document_version(&vault_id, &new_version, transaction) .await .map_err(server_error)?; From 042233c4d783e872060004b0478f2d849e3052fa Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Fri, 8 May 2026 21:35:52 +0100 Subject: [PATCH 05/17] split: server websocket + cursors src/server/websocket.rs handshake/catch-up rewrite, app_state/cursors.rs, app_state/websocket/{broadcasts,models,utils}.rs. --- sync-server/src/app_state/cursors.rs | 90 +++-- .../src/app_state/websocket/broadcasts.rs | 160 ++++++-- sync-server/src/app_state/websocket/models.rs | 21 +- sync-server/src/app_state/websocket/utils.rs | 16 +- sync-server/src/server/websocket.rs | 370 +++++++++++++----- 5 files changed, 487 insertions(+), 170 deletions(-) diff --git a/sync-server/src/app_state/cursors.rs b/sync-server/src/app_state/cursors.rs index d083e1ac..e17fb4f7 100644 --- a/sync-server/src/app_state/cursors.rs +++ b/sync-server/src/app_state/cursors.rs @@ -42,7 +42,9 @@ impl Cursors { ) { let mut vault_to_cursors = self.vault_to_cursors.lock().await; - let all_device_cursors = vault_to_cursors.entry(vault_id).or_insert_with(Vec::new); + let all_device_cursors = vault_to_cursors + .entry(vault_id.clone()) + .or_insert_with(Vec::new); all_device_cursors.retain(|c| &c.client_cursors.device_id != device_id); all_device_cursors.push(ClientCursorsWithTimeToLive::new(ClientCursors { @@ -52,7 +54,7 @@ impl Cursors { })); drop(vault_to_cursors); // Explicitly drop the lock before broadcasting to avoid deadlock - self.broadcast_cursors().await; + self.broadcast_cursors_for_vault(&vault_id).await; } pub async fn get_cursors(&self, vault_id: &VaultId) -> Vec { @@ -69,45 +71,81 @@ impl Cursors { .unwrap_or_default() } - pub fn start_background_task(self) { + pub fn start_background_task(self, mut shutdown: tokio::sync::watch::Receiver<()>) { tokio::spawn(async move { loop { - self.remove_expired_cursors().await; - tokio::time::sleep(Duration::from_secs(1)).await; + tokio::select! { + () = tokio::time::sleep(Duration::from_secs(1)) => { + self.remove_expired_cursors().await; + } + Ok(()) = shutdown.changed() => break, + } } }); } async fn remove_expired_cursors(&self) { - let mut vault_to_cursors = self.vault_to_cursors.lock().await; + let changed_vaults: Vec = { + let mut vault_to_cursors = self.vault_to_cursors.lock().await; - for (_vault_id, cursors) in vault_to_cursors.iter_mut() { - cursors.retain(|cursor| !cursor.is_expired(self.config.cursor_timeout)); + let mut changed = Vec::new(); + for (vault_id, cursors) in vault_to_cursors.iter_mut() { + let before = cursors.len(); + cursors.retain(|cursor| !cursor.is_expired(self.config.cursor_timeout)); + if cursors.len() != before { + changed.push(vault_id.clone()); + } + } + + // Remove empty vault entries to prevent unbounded growth + vault_to_cursors.retain(|_, cursors| !cursors.is_empty()); + + changed + }; + + for vault_id in &changed_vaults { + self.broadcast_cursors_for_vault(vault_id).await; } } - async fn broadcast_cursors(&self) { - let vault_to_cursors = self.vault_to_cursors.lock().await; + async fn broadcast_cursors_for_vault(&self, vault_id: &VaultId) { + let client_cursors: Vec = { + let vault_to_cursors = self.vault_to_cursors.lock().await; + vault_to_cursors + .get(vault_id) + .map(|cursors| cursors.iter().map(|c| c.client_cursors.clone()).collect()) + .unwrap_or_default() + }; - for (vault_id, cursors) in vault_to_cursors.iter() { - self.broadcasts - .send_document_update( - vault_id.clone(), - WebSocketServerMessageWithOrigin::new(WebSocketServerMessage::CursorPositions( - CursorPositionFromServer { - clients: cursors.iter().map(|c| c.client_cursors.clone()).collect(), - }, - )), - ) - .await; - } + self.broadcasts.send_document_update( + vault_id.clone(), + WebSocketServerMessageWithOrigin::new(WebSocketServerMessage::CursorPositions( + CursorPositionFromServer { + clients: client_cursors, + }, + )), + ); } - pub async fn remove_cursors_of_device(&self, vault_id: &str, device_id: &str) { - let mut vault_to_cursors = self.vault_to_cursors.lock().await; + pub async fn remove_cursors_of_device(&self, vault_id: &VaultId, device_id: &DeviceId) { + let changed = { + let mut vault_to_cursors = self.vault_to_cursors.lock().await; - if let Some(cursors) = vault_to_cursors.get_mut(vault_id) { - cursors.retain(|c| c.client_cursors.device_id != device_id); + if let Some(cursors) = vault_to_cursors.get_mut(vault_id) { + let before = cursors.len(); + cursors.retain(|c| c.client_cursors.device_id != *device_id); + let changed = cursors.len() != before; + if cursors.is_empty() { + vault_to_cursors.remove(vault_id); + } + changed + } else { + false + } + }; + + if changed { + self.broadcast_cursors_for_vault(vault_id).await; } } } diff --git a/sync-server/src/app_state/websocket/broadcasts.rs b/sync-server/src/app_state/websocket/broadcasts.rs index 60ae0219..b9e2ea39 100644 --- a/sync-server/src/app_state/websocket/broadcasts.rs +++ b/sync-server/src/app_state/websocket/broadcasts.rs @@ -1,69 +1,147 @@ -use std::{collections::HashMap, sync::Arc}; +use std::{ + collections::HashMap, + sync::{Arc, Mutex as StdMutex}, +}; -use anyhow::Context; -use log::{debug, warn}; +use log::{debug, info, warn}; use tokio::sync::{Mutex, broadcast}; -use super::models::WebSocketServerMessageWithOrigin; -use crate::{ - app_state::database::models::VaultId, config::server_config::ServerConfig, errors::server_error, -}; +use super::models::{WebSocketServerMessage, WebSocketServerMessageWithOrigin}; +use crate::{app_state::database::models::VaultId, config::server_config::ServerConfig}; #[derive(Debug, Clone)] pub struct Broadcasts { - max_clients_per_vault: usize, - tx: Arc>>>, + broadcast_channel_capacity: usize, + // `tx` uses a blocking std::sync::Mutex because the critical section is + // a HashMap lookup plus a synchronous `broadcast::Sender::send`. Making + // this non-async lets `send_document_update` run without an `.await`, + // so an axum handler that is cancelled between `transaction.commit()` + // and the broadcast can never drop the notification mid-flight. + tx: Arc>>>, + send_locks: Arc>>>>, } +type TxMap = HashMap>; + impl Broadcasts { pub fn new(server_config: &ServerConfig) -> Self { Self { - max_clients_per_vault: server_config.max_clients_per_vault, - tx: Arc::new(Mutex::new(HashMap::new())), + broadcast_channel_capacity: server_config.broadcast_channel_capacity, + tx: Arc::new(StdMutex::new(HashMap::new())), + send_locks: Arc::new(Mutex::new(HashMap::new())), } } - pub async fn get_receiver( + /// Acquire a per-vault lock that serializes broadcasts in commit order. + /// Must be acquired before the insert, held through commit and broadcast. + pub async fn acquire_send_lock(&self, vault: &VaultId) -> tokio::sync::OwnedMutexGuard<()> { + let lock = { + let mut locks = self.send_locks.lock().await; + locks + .entry(vault.clone()) + .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(()))) + .clone() + }; + lock.lock_owned().await + } + + /// Remove senders for vaults with no active receivers + fn prune_inactive_vaults(tx_map: &mut TxMap) -> Vec { + let mut pruned = Vec::new(); + tx_map.retain(|vault, sender| { + let alive = sender.receiver_count() > 0; + if !alive { + pruned.push(vault.clone()); + } + alive + }); + pruned + } + + pub fn get_receiver( &self, vault: VaultId, - ) -> broadcast::Receiver { - let tx = self.get_or_create(vault).await; + max_clients: usize, + ) -> Result, crate::errors::SyncServerError> + { + let mut tx_map = self + .tx + .lock() + .expect("broadcasts.tx mutex poisoned — a previous holder panicked"); - tx.subscribe() + let count_before_prune = tx_map + .get(&vault) + .map_or(0, tokio::sync::broadcast::Sender::receiver_count); + let pruned = Self::prune_inactive_vaults(&mut tx_map); + let pruned_self = pruned.contains(&vault); + + let sender = tx_map + .entry(vault.clone()) + .or_insert_with(|| broadcast::channel(self.broadcast_channel_capacity).0); + + // Hold the lock across the count check *and* the subscribe so the + // `max_clients` cap is atomic: two concurrent callers can't both + // observe `receiver_count() < max_clients` and both subscribe. + if sender.receiver_count() >= max_clients { + return Err(crate::errors::client_error(anyhow::anyhow!( + "Vault has reached the maximum number of clients ({max_clients})" + ))); + } + + let receiver = sender.subscribe(); + let count_after = sender.receiver_count(); + info!( + "[BCAST] get_receiver vault={vault} count_before_prune={count_before_prune} pruned_self={pruned_self} pruned_total={} count_after_subscribe={count_after}", + pruned.len() + ); + Ok(receiver) } /// Notify all clients (who are subscribed to the vault) about an update. - /// We only log failures and don't propagate them. - pub async fn send_document_update( - &self, - vault: VaultId, - document: WebSocketServerMessageWithOrigin, - ) { - let tx = self.get_or_create(vault.clone()).await; + /// Synchronous: safe to invoke from a handler between `commit()` and + /// function return without worrying about task cancellation dropping + /// the broadcast mid-flight. Failures are logged, never propagated. + pub fn send_document_update(&self, vault: VaultId, document: WebSocketServerMessageWithOrigin) { + let vault_update_id = match &document.message { + WebSocketServerMessage::VaultUpdate(u) => Some(u.document.vault_update_id), + WebSocketServerMessage::CursorPositions(_) => None, + }; + let is_deleted = match &document.message { + WebSocketServerMessage::VaultUpdate(u) => Some(u.document.is_deleted), + WebSocketServerMessage::CursorPositions(_) => None, + }; + let mut tx_map = self + .tx + .lock() + .expect("broadcasts.tx mutex poisoned — a previous holder panicked"); + let count_before_prune = tx_map + .get(&vault) + .map_or(0, tokio::sync::broadcast::Sender::receiver_count); + let pruned = Self::prune_inactive_vaults(&mut tx_map); + let pruned_self = pruned.contains(&vault); - if tx.receiver_count() == 0 { + let sender = tx_map + .entry(vault.clone()) + .or_insert_with(|| broadcast::channel(self.broadcast_channel_capacity).0); + + let count_before_send = sender.receiver_count(); + + if count_before_send == 0 { + info!( + "[BCAST] send_document_update vault={vault} vuid={vault_update_id:?} is_deleted={is_deleted:?} count_before_prune={count_before_prune} pruned_self={pruned_self} count_before_send=0 SKIPPED" + ); debug!("Skipping broadcast, no clients connected for vault `{vault}`"); return; } - let result = tx - .send(document) - .context("Cannot broadcast server message to websocket listeners") - .map_err(server_error); - - if result.is_err() { - warn!("Failed to send message: {result:?}"); + let send_result = sender.send(document); + match &send_result { + Ok(n) => info!( + "[BCAST] send_document_update vault={vault} vuid={vault_update_id:?} is_deleted={is_deleted:?} count_before_prune={count_before_prune} pruned_self={pruned_self} count_before_send={count_before_send} SENT delivered_to={n}" + ), + Err(e) => warn!( + "[BCAST] send_document_update vault={vault} vuid={vault_update_id:?} is_deleted={is_deleted:?} count_before_prune={count_before_prune} pruned_self={pruned_self} count_before_send={count_before_send} FAILED err={e}" + ), } } - - async fn get_or_create( - &self, - vault: VaultId, - ) -> broadcast::Sender { - let mut tx = self.tx.lock().await; - - tx.entry(vault) - .or_insert_with(|| broadcast::channel(self.max_clients_per_vault).0.clone()) - .clone() - } } diff --git a/sync-server/src/app_state/websocket/models.rs b/sync-server/src/app_state/websocket/models.rs index e037fb7e..eb6c956a 100644 --- a/sync-server/src/app_state/websocket/models.rs +++ b/sync-server/src/app_state/websocket/models.rs @@ -11,7 +11,7 @@ pub struct WebSocketHandshake { pub token: String, pub device_id: DeviceId, - #[ts(as = "Option")] + #[ts(type = "number | null")] pub last_seen_vault_update_id: Option, } @@ -22,13 +22,14 @@ pub struct CursorPositionFromClient { } #[derive(TS, Serialize, Deserialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] pub struct DocumentWithCursors { // It's None in case the document is dirty. // We still want to sync the cursor to mark // that it exists and can be client-side // interpolated. However, the actual // position is meaningless. - #[ts(as = "Option")] + #[ts(type = "number | null")] pub vault_update_id: Option, pub document_id: DocumentId, @@ -57,11 +58,19 @@ pub struct CursorPositionFromServer { pub clients: Vec, } +// One committed version. Non-delete updates are broadcast to every +// connected client *except* the device that authored them — that +// device already has the new state via its HTTP response. Deletes are +// broadcast to every client including the author: the author keeps +// the document in its sync queue until this receipt arrives so a late +// remote update can't sneak in between the HTTP response and the +// queue cleanup. The server also emits these one-at-a-time to catch +// up a freshly-connected client on versions committed while it was +// offline, in ascending `vault_update_id` order. #[derive(TS, Serialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct WebSocketVaultUpdate { - pub documents: Vec, - pub is_initial_sync: bool, + pub document: DocumentVersionWithoutContent, } #[derive(TS, Deserialize, Clone, Debug)] @@ -80,6 +89,10 @@ pub enum WebSocketServerMessage { CursorPositions(CursorPositionFromServer), } +/// Broadcast envelope carrying the message plus the device that produced +/// it. The per-recipient send task compares `origin_device_id` against +/// its own device id to fill in `originates_from_self` before the message +/// is serialized on the wire. #[derive(Clone, Debug)] pub struct WebSocketServerMessageWithOrigin { pub origin_device_id: Option, diff --git a/sync-server/src/app_state/websocket/utils.rs b/sync-server/src/app_state/websocket/utils.rs index 1e0dd243..d78360de 100644 --- a/sync-server/src/app_state/websocket/utils.rs +++ b/sync-server/src/app_state/websocket/utils.rs @@ -9,7 +9,7 @@ use crate::{ database::models::{DocumentVersionWithoutContent, VaultId, VaultUpdateId}, }, config::user_config::User, - errors::{SyncServerError, server_error, unauthenticated_error}, + errors::{SyncServerError, client_error, server_error, unauthenticated_error}, server::auth::auth, }; @@ -26,7 +26,7 @@ pub fn get_authenticated_handshake( if let Some(Message::Text(message)) = message { let message: WebSocketClientMessage = serde_json::from_str(&message) .context("Failed to parse message") - .map_err(server_error)?; + .map_err(client_error)?; match message { WebSocketClientMessage::Handshake(handshake) => { @@ -44,21 +44,29 @@ pub fn get_authenticated_handshake( } } +/// Stream the documents the client missed while offline, bounded above +/// by `up_to_vault_update_id` so the catch-up is a stable snapshot at +/// exactly that cursor. The WebSocket handshake atomically subscribes +/// to the broadcast channel and snapshots this cursor under the per- +/// vault send lock; commits past the cursor are then delivered solely +/// through the broadcast channel (filtered by the same cursor on the +/// receive side), so every committed update is delivered exactly once. pub async fn get_unseen_documents( state: &AppState, vault_id: &VaultId, last_seen_vault_update_id: Option, + up_to_vault_update_id: VaultUpdateId, ) -> Result, SyncServerError> { if let Some(update_id) = last_seen_vault_update_id { state .database - .get_latest_documents_since(vault_id, update_id, None) + .get_latest_documents_since(vault_id, update_id, Some(up_to_vault_update_id), None) .await .map_err(server_error) } else { state .database - .get_latest_documents(vault_id, None) + .get_latest_documents(vault_id, Some(up_to_vault_update_id), None) .await .map_err(server_error) } diff --git a/sync-server/src/server/websocket.rs b/sync-server/src/server/websocket.rs index bb10b49f..6e1af0ba 100644 --- a/sync-server/src/server/websocket.rs +++ b/sync-server/src/server/websocket.rs @@ -1,15 +1,3 @@ -use anyhow::Context; -use axum::{ - extract::{ - Path, State, - ws::{Message, WebSocket, WebSocketUpgrade}, - }, - response::Response, -}; -use futures::stream::StreamExt; -use log::{debug, info}; -use serde::Deserialize; - use crate::{ app_state::{ AppState, @@ -24,9 +12,35 @@ use crate::{ }, }, }, + consts::{ + HANDSHAKE_TIMEOUT, MAX_CURSOR_DOCUMENTS, MAX_CURSORS_PER_DOCUMENT, MAX_RELATIVE_PATH_LEN, + }, errors::{SyncServerError, client_error, server_error}, utils::normalize::normalize, }; +use anyhow::Context; +use axum::{ + extract::{ + Path, State, + ws::{Message, WebSocket, WebSocketUpgrade}, + }, + response::Response, +}; +use futures::sink::SinkExt; +use futures::stream::StreamExt; +use log::{debug, info, warn}; +use serde::Deserialize; + +/// Tracks a pending (not yet authenticated) WebSocket connection. +/// Decrements the counter when dropped, ensuring cleanup even if +/// the upgrade never completes or auth fails. +struct PendingWsGuard(std::sync::Arc); + +impl Drop for PendingWsGuard { + fn drop(&mut self) { + self.0.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + } +} #[derive(Deserialize)] pub struct WebSocketPathParams { @@ -39,13 +53,31 @@ pub async fn websocket_handler( Path(WebSocketPathParams { vault_id }): Path, State(state): State, ) -> Result { - Ok(ws.on_upgrade(move |socket| websocket_wrapped(state, socket, vault_id))) + let current = state + .pending_ws_connections + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if current >= state.config.server.max_pending_websocket_connections { + state + .pending_ws_connections + .fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + return Err(client_error(anyhow::anyhow!( + "Too many pending WebSocket connections" + ))); + } + + let guard = PendingWsGuard(state.pending_ws_connections.clone()); + Ok(ws.on_upgrade(move |socket| websocket_wrapped(state, socket, vault_id, guard))) } -async fn websocket_wrapped(state: AppState, stream: WebSocket, vault_id: VaultId) { +async fn websocket_wrapped( + state: AppState, + stream: WebSocket, + vault_id: VaultId, + pending_guard: PendingWsGuard, +) { info!("WebSocket connection opened on vault `{vault_id}`"); - let result = websocket(state, stream, vault_id.clone()).await; + let result = websocket(state, stream, vault_id.clone(), pending_guard).await; if let Err(err) = result { debug!("WebSocket connection error on vault `{vault_id}`: {err}"); @@ -57,39 +89,112 @@ async fn websocket( state: AppState, stream: WebSocket, vault_id: VaultId, + pending_guard: PendingWsGuard, ) -> Result<(), SyncServerError> { let (mut sender, mut websocket_receiver) = stream.split(); - let authed_handshake = get_authenticated_handshake( - &state, - &vault_id, - websocket_receiver - .next() - .await - .transpose() - .unwrap_or_default(), - )?; + let handshake_msg = tokio::time::timeout(HANDSHAKE_TIMEOUT, websocket_receiver.next()) + .await + .map_err(|_| client_error(anyhow::anyhow!("WebSocket handshake timed out")))? + .transpose() + .map_err(|e| client_error(anyhow::anyhow!("WebSocket error during handshake: {e}")))?; + + let authed_handshake = get_authenticated_handshake(&state, &vault_id, handshake_msg)?; info!( "WebSocket handshake successful for vault `{vault_id}` for `{}`", authed_handshake.handshake.device_id ); - let mut broadcast_receiver = state.broadcasts.get_receiver(vault_id.clone()).await; + // Auth complete — no longer a pending connection. + drop(pending_guard); - send_update_over_websocket( - &WebSocketServerMessage::VaultUpdate(WebSocketVaultUpdate { - documents: get_unseen_documents( - &state, - &vault_id, - authed_handshake.handshake.last_seen_vault_update_id, - ) - .await?, - is_initial_sync: true, - }), - &mut sender, + let max_clients = state.config.server.max_clients_per_vault; + + // Atomic subscribe + cursor snapshot, serialized against in-flight + // broadcasts: + // + // 1. Acquire the per-vault broadcast send lock. While we hold it, + // no `send_document_update` can run, so no broadcast can fire + // between our subscribe and our cursor snapshot. + // 2. Subscribe to the broadcast channel (now we'll see every + // broadcast that fires after we drop the send guard). + // 3. Snapshot `cursor = max committed vault_update_id`. Because + // `insert_document_version` holds the same send lock from + // *before* the commit through *after* the broadcast, every doc + // visible at this cursor has either (a) already had its + // broadcast delivered to all then-existing subscribers — and we + // weren't one of them, so we'll catch it via the snapshot — or + // (b) had its broadcast contend on the lock we're holding, and + // will be delivered to us as soon as we drop the guard, with + // `vault_update_id > cursor`. + // 4. Drop the send guard so writers can resume broadcasting. + // 5. Stream the catch-up bounded by the cursor — i.e. only docs + // with `vault_update_id <= cursor` — exactly once. + // 6. The send task forwards broadcasts but filters to + // `vault_update_id > cursor`, so a doc that's both in the + // catch-up and in a contended-then-released broadcast is + // delivered exactly once (via the catch-up). + let send_guard = state.broadcasts.acquire_send_lock(&vault_id).await; + let mut broadcast_receiver = match state.broadcasts.get_receiver(vault_id.clone(), max_clients) + { + Ok(receiver) => receiver, + Err(err) => { + drop(send_guard); + warn!( + "Vault `{vault_id}` has reached the maximum number of clients ({max_clients}), rejecting connection from `{}`", + authed_handshake.handshake.device_id + ); + if let Err(e) = sender + .send(Message::Close(Some(axum::extract::ws::CloseFrame { + code: 4000, + reason: format!( + "Vault has reached the maximum number of clients ({max_clients})" + ) + .into(), + }))) + .await + { + warn!("Failed to send WebSocket close frame: {e}"); + } + return Err(err); + } + }; + let cursor = state + .database + .get_max_update_id_in_vault(&vault_id, None) + .await + .map_err(server_error)?; + drop(send_guard); + + // Catch-up on versions committed while this client was offline, + // streamed one-at-a-time in ascending `vault_update_id` order, up + // to the snapshot cursor. + let unseen_documents = get_unseen_documents( + &state, + &vault_id, + authed_handshake.handshake.last_seen_vault_update_id, + cursor, ) .await?; + let unseen_summary: Vec<(i64, bool, String)> = unseen_documents + .iter() + .map(|d| (d.vault_update_id, d.is_deleted, d.relative_path.clone())) + .collect(); + info!( + "[CATCHUP] vault={vault_id} device={} last_seen={:?} cursor={cursor} unseen_count={} unseen={:?}", + authed_handshake.handshake.device_id, + authed_handshake.handshake.last_seen_vault_update_id, + unseen_summary.len(), + unseen_summary + ); + for document in unseen_documents { + send_update_over_websocket( + &WebSocketServerMessage::VaultUpdate(WebSocketVaultUpdate { document }), + &mut sender, + ) + .await?; + } send_update_over_websocket( &WebSocketServerMessage::CursorPositions(CursorPositionFromServer { @@ -101,24 +206,57 @@ async fn websocket( let device_id = authed_handshake.handshake.device_id.clone(); let mut send_task = tokio::spawn(async move { - while let Ok(update) = broadcast_receiver.recv().await { - if Some(&device_id) == update.origin_device_id.as_ref() { - continue; - } + loop { + match broadcast_receiver.recv().await { + Ok(update) => { + // Drop messages this device authored because the HTTP + // response already carried authoritative state back. + // Delete broadcasts are sent without an origin so the + // author also receives them — that's the receipt the + // client needs to drop the doc from its sync queue. + if Some(&device_id) == update.origin_device_id.as_ref() { + continue; + } - let message = match update.message { - WebSocketServerMessage::CursorPositions(CursorPositionFromServer { clients }) => { - WebSocketServerMessage::CursorPositions(CursorPositionFromServer { - clients: clients - .into_iter() - .filter(|client| client.device_id != device_id) - .collect(), - }) + // Filter out vault updates already covered by the + // catch-up snapshot. The handshake atomically + // subscribed and snapshotted `cursor` under the + // broadcast send lock, so any broadcast with + // `vault_update_id <= cursor` is one that contended + // on the lock during our subscribe — its row is + // already in the catch-up stream and re-delivering + // it via this channel would duplicate the message. + // Cursor messages aren't versioned and are always + // forwarded. + if let WebSocketServerMessage::VaultUpdate(WebSocketVaultUpdate { document }) = + &update.message + && document.vault_update_id <= cursor + { + continue; + } + + let message = match update.message { + WebSocketServerMessage::CursorPositions(CursorPositionFromServer { + clients, + }) => WebSocketServerMessage::CursorPositions(CursorPositionFromServer { + clients: clients + .into_iter() + .filter(|client| client.device_id != device_id) + .collect(), + }), + WebSocketServerMessage::VaultUpdate(_) => update.message, + }; + + send_update_over_websocket(&message, &mut sender).await?; } - WebSocketServerMessage::VaultUpdate(_) => update.message, - }; - - send_update_over_websocket(&message, &mut sender).await?; + Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => { + warn!( + "WebSocket receiver lagged, dropped {n} messages — disconnecting client to force full resync" + ); + break; + } + Err(tokio::sync::broadcast::error::RecvError::Closed) => break, + } } Ok::<(), SyncServerError>(()) @@ -128,26 +266,59 @@ async fn websocket( let vault_id_clone = vault_id.clone(); let cursor_manager = state.cursors.clone(); let mut receive_task = tokio::spawn(async move { - while let Some(Ok(Message::Text(message))) = websocket_receiver.next().await { - let message: WebSocketClientMessage = serde_json::from_str(&message) - .context("Failed to parse WebSocket message from client") - .map_err(server_error)?; + while let Some(msg) = websocket_receiver.next().await { + match msg { + Ok(Message::Text(message)) => { + let message: WebSocketClientMessage = serde_json::from_str(&message) + .context("Failed to parse WebSocket message from client") + .map_err(client_error)?; - match message { - WebSocketClientMessage::Handshake(_) => { - return Err(client_error(anyhow::anyhow!( - "Unexpected handshake message" - ))); + match message { + WebSocketClientMessage::Handshake(_) => { + return Err(client_error(anyhow::anyhow!( + "Unexpected handshake message" + ))); + } + WebSocketClientMessage::CursorPositions(cursors) => { + let docs = cursors.documents_with_cursors; + if docs.len() > MAX_CURSOR_DOCUMENTS { + warn!( + "Cursor update rejected: {} documents exceeds limit of {MAX_CURSOR_DOCUMENTS}", + docs.len() + ); + continue; + } + + let valid = docs.iter().all(|doc| { + doc.cursors.len() <= MAX_CURSORS_PER_DOCUMENT + && doc.relative_path.len() <= MAX_RELATIVE_PATH_LEN + }); + if !valid { + warn!( + "Cursor update rejected: a document exceeds cursor or path length limits" + ); + continue; + } + + cursor_manager + .update_cursors( + vault_id_clone.clone(), + authed_handshake.user.name.clone(), + &device_id, + docs, + ) + .await; + } + } } - WebSocketClientMessage::CursorPositions(cursors) => { - cursor_manager - .update_cursors( - vault_id_clone.clone(), - authed_handshake.user.name.clone(), - &device_id, - cursors.documents_with_cursors, - ) - .await; + Ok(Message::Close(_)) => break, + Ok(Message::Binary(_)) => { + warn!("Received unexpected binary WebSocket message, ignoring"); + } + Ok(_) => {} // Ping/Pong frames handled by axum + Err(e) => { + debug!("WebSocket receive error: {e}"); + break; } } } @@ -155,38 +326,47 @@ async fn websocket( Ok::<(), SyncServerError>(()) }); - tokio::select! { - _ = &mut send_task => receive_task.abort(), - _ = &mut receive_task => send_task.abort(), + let result: Result<(), SyncServerError> = tokio::select! { + send_result = &mut send_task => { + receive_task.abort(); + let _ = receive_task.await; + match send_result { + Err(e) => Err(server_error( + anyhow::Error::from(e).context("WebSocket send task failed"), + )), + Ok(inner) => inner, + } + }, + receive_result = &mut receive_task => { + send_task.abort(); + let _ = send_task.await; + match receive_result { + Err(e) => Err(server_error( + anyhow::Error::from(e).context("WebSocket receive task failed"), + )), + Ok(inner) => inner, + } + }, }; - let result: Result<(), SyncServerError> = (async { - send_task - .await - .context("WebSocket send task failed") - .map_err(client_error) - .and_then(|err| err)?; - - receive_task - .await - .context("WebSocket receive task failed") - .map_err(client_error) - .and_then(|err| err)?; - - Ok(()) - }) - .await; - state .cursors .remove_cursors_of_device(&vault_id, &authed_handshake.handshake.device_id) .await; - if result.is_err() { - info!( - "WebSocket disconnected on vault `{vault_id}` for `{}`", - authed_handshake.handshake.device_id - ); + match &result { + Ok(()) => { + info!( + "WebSocket disconnected on vault `{vault_id}` for `{}`", + authed_handshake.handshake.device_id + ); + } + Err(err) => { + warn!( + "WebSocket error on vault `{vault_id}` for `{}`: {err}", + authed_handshake.handshake.device_id + ); + } } result From f7beb31d8f210379974388bf4e59b3b70e9e670b Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Fri, 8 May 2026 21:36:13 +0100 Subject: [PATCH 06/17] split: regenerated TS API type bindings Auto-generated TS types regenerated from Rust ts-rs derives, mirrored into frontend/sync-client/src/services/types/ and frontend/history-ui/src/lib/types/. Adds ListVaultsResponse, VaultHistoryResponse, VaultInfo and updates several existing types; removes DeleteDocumentVersion and UpdateDocumentVersion. --- .../history-ui/src/lib/types/ClientCursors.ts | 8 ++++++ .../src/lib/types/CreateDocumentVersion.ts} | 8 +++--- .../src/lib/types/CursorPositionFromClient.ts | 6 +++++ .../src/lib/types/CursorPositionFromServer.ts | 4 +++ .../src/lib/types/CursorSpan.ts} | 4 +-- .../src/lib/types/DocumentUpdateResponse.ts | 10 ++++++++ .../src/lib/types/DocumentVersion.ts | 12 +++++++++ .../types/DocumentVersionWithoutContent.ts | 16 ++++++++++++ .../src/lib/types/DocumentWithCursors.ts | 9 +++++++ .../lib/types/FetchLatestDocumentsResponse.ts | 13 ++++++++++ .../src/lib/types/ListVaultsResponse.ts | 11 ++++++++ .../history-ui/src/lib/types/PingResponse.ts | 25 +++++++++++++++++++ .../src/lib/types/SerializedError.ts | 7 ++++++ .../lib/types/UpdateTextDocumentVersion.ts | 7 ++++++ .../src/lib/types/VaultHistoryResponse.ts | 10 ++++++++ .../history-ui/src/lib/types/VaultInfo.ts | 10 ++++++++ .../src/lib/types/WebSocketClientMessage.ts | 7 ++++++ .../src/lib/types/WebSocketHandshake.ts | 7 ++++++ .../src/lib/types/WebSocketServerMessage.ts | 7 ++++++ .../src/lib/types/WebSocketVaultUpdate.ts | 4 +++ .../services/types/CreateDocumentVersion.ts | 8 +----- .../services/types/DocumentUpdateResponse.ts | 2 +- .../types/DocumentVersionWithoutContent.ts | 4 +++ .../src/services/types/DocumentWithCursors.ts | 6 ++--- .../types/FetchLatestDocumentsResponse.ts | 4 +-- .../src/services/types/ListVaultsResponse.ts | 11 ++++++++ .../src/services/types/PingResponse.ts | 20 +++++++-------- .../types/UpdateTextDocumentVersion.ts | 2 +- .../services/types/VaultHistoryResponse.ts | 10 ++++++++ .../src/services/types/VaultInfo.ts | 10 ++++++++ .../services/types/WebSocketVaultUpdate.ts | 3 +-- 31 files changed, 232 insertions(+), 33 deletions(-) create mode 100644 frontend/history-ui/src/lib/types/ClientCursors.ts rename frontend/{sync-client/src/services/types/UpdateDocumentVersion.ts => history-ui/src/lib/types/CreateDocumentVersion.ts} (55%) create mode 100644 frontend/history-ui/src/lib/types/CursorPositionFromClient.ts create mode 100644 frontend/history-ui/src/lib/types/CursorPositionFromServer.ts rename frontend/{sync-client/src/services/types/DeleteDocumentVersion.ts => history-ui/src/lib/types/CursorSpan.ts} (61%) create mode 100644 frontend/history-ui/src/lib/types/DocumentUpdateResponse.ts create mode 100644 frontend/history-ui/src/lib/types/DocumentVersion.ts create mode 100644 frontend/history-ui/src/lib/types/DocumentVersionWithoutContent.ts create mode 100644 frontend/history-ui/src/lib/types/DocumentWithCursors.ts create mode 100644 frontend/history-ui/src/lib/types/FetchLatestDocumentsResponse.ts create mode 100644 frontend/history-ui/src/lib/types/ListVaultsResponse.ts create mode 100644 frontend/history-ui/src/lib/types/PingResponse.ts create mode 100644 frontend/history-ui/src/lib/types/SerializedError.ts create mode 100644 frontend/history-ui/src/lib/types/UpdateTextDocumentVersion.ts create mode 100644 frontend/history-ui/src/lib/types/VaultHistoryResponse.ts create mode 100644 frontend/history-ui/src/lib/types/VaultInfo.ts create mode 100644 frontend/history-ui/src/lib/types/WebSocketClientMessage.ts create mode 100644 frontend/history-ui/src/lib/types/WebSocketHandshake.ts create mode 100644 frontend/history-ui/src/lib/types/WebSocketServerMessage.ts create mode 100644 frontend/history-ui/src/lib/types/WebSocketVaultUpdate.ts create mode 100644 frontend/sync-client/src/services/types/ListVaultsResponse.ts create mode 100644 frontend/sync-client/src/services/types/VaultHistoryResponse.ts create mode 100644 frontend/sync-client/src/services/types/VaultInfo.ts diff --git a/frontend/history-ui/src/lib/types/ClientCursors.ts b/frontend/history-ui/src/lib/types/ClientCursors.ts new file mode 100644 index 00000000..14298431 --- /dev/null +++ b/frontend/history-ui/src/lib/types/ClientCursors.ts @@ -0,0 +1,8 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { DocumentWithCursors } from "./DocumentWithCursors"; + +export type ClientCursors = { + userName: string; + deviceId: string; + documentsWithCursors: Array; +}; diff --git a/frontend/sync-client/src/services/types/UpdateDocumentVersion.ts b/frontend/history-ui/src/lib/types/CreateDocumentVersion.ts similarity index 55% rename from frontend/sync-client/src/services/types/UpdateDocumentVersion.ts rename to frontend/history-ui/src/lib/types/CreateDocumentVersion.ts index 4e57a297..389d8e88 100644 --- a/frontend/sync-client/src/services/types/UpdateDocumentVersion.ts +++ b/frontend/history-ui/src/lib/types/CreateDocumentVersion.ts @@ -1,7 +1,7 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export interface UpdateDocumentVersion { - parent_version_id: bigint; +export type CreateDocumentVersion = { relative_path: string; - content: number[]; -} + last_seen_vault_update_id: number; + content: Array; +}; diff --git a/frontend/history-ui/src/lib/types/CursorPositionFromClient.ts b/frontend/history-ui/src/lib/types/CursorPositionFromClient.ts new file mode 100644 index 00000000..5846843e --- /dev/null +++ b/frontend/history-ui/src/lib/types/CursorPositionFromClient.ts @@ -0,0 +1,6 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { DocumentWithCursors } from "./DocumentWithCursors"; + +export type CursorPositionFromClient = { + documentsWithCursors: Array; +}; diff --git a/frontend/history-ui/src/lib/types/CursorPositionFromServer.ts b/frontend/history-ui/src/lib/types/CursorPositionFromServer.ts new file mode 100644 index 00000000..3a72c706 --- /dev/null +++ b/frontend/history-ui/src/lib/types/CursorPositionFromServer.ts @@ -0,0 +1,4 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ClientCursors } from "./ClientCursors"; + +export type CursorPositionFromServer = { clients: Array }; diff --git a/frontend/sync-client/src/services/types/DeleteDocumentVersion.ts b/frontend/history-ui/src/lib/types/CursorSpan.ts similarity index 61% rename from frontend/sync-client/src/services/types/DeleteDocumentVersion.ts rename to frontend/history-ui/src/lib/types/CursorSpan.ts index 99ecc9e7..916019ce 100644 --- a/frontend/sync-client/src/services/types/DeleteDocumentVersion.ts +++ b/frontend/history-ui/src/lib/types/CursorSpan.ts @@ -1,5 +1,3 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export interface DeleteDocumentVersion { - relativePath: string; -} +export type CursorSpan = { start: number; end: number }; diff --git a/frontend/history-ui/src/lib/types/DocumentUpdateResponse.ts b/frontend/history-ui/src/lib/types/DocumentUpdateResponse.ts new file mode 100644 index 00000000..dd7eadda --- /dev/null +++ b/frontend/history-ui/src/lib/types/DocumentUpdateResponse.ts @@ -0,0 +1,10 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { DocumentVersion } from "./DocumentVersion"; +import type { DocumentVersionWithoutContent } from "./DocumentVersionWithoutContent"; + +/** + * Response to a create/update document request. + */ +export type DocumentUpdateResponse = + | ({ type: "FastForwardUpdate" } & DocumentVersionWithoutContent) + | ({ type: "MergingUpdate" } & DocumentVersion); diff --git a/frontend/history-ui/src/lib/types/DocumentVersion.ts b/frontend/history-ui/src/lib/types/DocumentVersion.ts new file mode 100644 index 00000000..50a6c591 --- /dev/null +++ b/frontend/history-ui/src/lib/types/DocumentVersion.ts @@ -0,0 +1,12 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type DocumentVersion = { + vaultUpdateId: number; + documentId: string; + relativePath: string; + updatedDate: string; + contentBase64: string; + isDeleted: boolean; + userId: string; + deviceId: string; +}; diff --git a/frontend/history-ui/src/lib/types/DocumentVersionWithoutContent.ts b/frontend/history-ui/src/lib/types/DocumentVersionWithoutContent.ts new file mode 100644 index 00000000..e3ed828a --- /dev/null +++ b/frontend/history-ui/src/lib/types/DocumentVersionWithoutContent.ts @@ -0,0 +1,16 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type DocumentVersionWithoutContent = { + vaultUpdateId: number; + documentId: string; + relativePath: string; + updatedDate: string; + isDeleted: boolean; + userId: string; + deviceId: string; + contentSize: number; + /** + * True iff this is the first version of the document + */ + isNewFile: boolean; +}; diff --git a/frontend/history-ui/src/lib/types/DocumentWithCursors.ts b/frontend/history-ui/src/lib/types/DocumentWithCursors.ts new file mode 100644 index 00000000..ca6a2155 --- /dev/null +++ b/frontend/history-ui/src/lib/types/DocumentWithCursors.ts @@ -0,0 +1,9 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { CursorSpan } from "./CursorSpan"; + +export type DocumentWithCursors = { + vaultUpdateId: number | null; + documentId: string; + relativePath: string; + cursors: Array; +}; diff --git a/frontend/history-ui/src/lib/types/FetchLatestDocumentsResponse.ts b/frontend/history-ui/src/lib/types/FetchLatestDocumentsResponse.ts new file mode 100644 index 00000000..141c2565 --- /dev/null +++ b/frontend/history-ui/src/lib/types/FetchLatestDocumentsResponse.ts @@ -0,0 +1,13 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { DocumentVersionWithoutContent } from "./DocumentVersionWithoutContent"; + +/** + * Response to a fetch latest documents request. + */ +export type FetchLatestDocumentsResponse = { + latestDocuments: Array; + /** + * The update ID of the latest document in the response. + */ + lastUpdateId: bigint; +}; diff --git a/frontend/history-ui/src/lib/types/ListVaultsResponse.ts b/frontend/history-ui/src/lib/types/ListVaultsResponse.ts new file mode 100644 index 00000000..604ad958 --- /dev/null +++ b/frontend/history-ui/src/lib/types/ListVaultsResponse.ts @@ -0,0 +1,11 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { VaultInfo } from "./VaultInfo"; + +/** + * Response to listing vaults accessible to the authenticated user. + */ +export type ListVaultsResponse = { + vaults: Array; + hasMore: boolean; + userName: string; +}; diff --git a/frontend/history-ui/src/lib/types/PingResponse.ts b/frontend/history-ui/src/lib/types/PingResponse.ts new file mode 100644 index 00000000..7e5ac4f8 --- /dev/null +++ b/frontend/history-ui/src/lib/types/PingResponse.ts @@ -0,0 +1,25 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Response to a ping request. + */ +export type PingResponse = { + /** + * Semantic version of the server. + */ + serverVersion: string; + /** + * Whether the client is authenticated based on the sent Authorization + * header. + */ + isAuthenticated: boolean; + /** + * List of file extensions that are allowed to be merged. + */ + mergeableFileExtensions: Array; + /** + * API version ensuring backwards & forwards compatibility between the client + * and server. + */ + supportedApiVersion: number; +}; diff --git a/frontend/history-ui/src/lib/types/SerializedError.ts b/frontend/history-ui/src/lib/types/SerializedError.ts new file mode 100644 index 00000000..354305f6 --- /dev/null +++ b/frontend/history-ui/src/lib/types/SerializedError.ts @@ -0,0 +1,7 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type SerializedError = { + errorType: string; + message: string; + causes: Array; +}; diff --git a/frontend/history-ui/src/lib/types/UpdateTextDocumentVersion.ts b/frontend/history-ui/src/lib/types/UpdateTextDocumentVersion.ts new file mode 100644 index 00000000..5a1978eb --- /dev/null +++ b/frontend/history-ui/src/lib/types/UpdateTextDocumentVersion.ts @@ -0,0 +1,7 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type UpdateTextDocumentVersion = { + parentVersionId: number; + relativePath: string | null; + content: Array; +}; diff --git a/frontend/history-ui/src/lib/types/VaultHistoryResponse.ts b/frontend/history-ui/src/lib/types/VaultHistoryResponse.ts new file mode 100644 index 00000000..e69366f0 --- /dev/null +++ b/frontend/history-ui/src/lib/types/VaultHistoryResponse.ts @@ -0,0 +1,10 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { DocumentVersionWithoutContent } from "./DocumentVersionWithoutContent"; + +/** + * Response to a vault history request (paginated). + */ +export type VaultHistoryResponse = { + versions: Array; + hasMore: boolean; +}; diff --git a/frontend/history-ui/src/lib/types/VaultInfo.ts b/frontend/history-ui/src/lib/types/VaultInfo.ts new file mode 100644 index 00000000..3f630ae9 --- /dev/null +++ b/frontend/history-ui/src/lib/types/VaultInfo.ts @@ -0,0 +1,10 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Summary of a single vault returned by the list-vaults endpoint. + */ +export type VaultInfo = { + name: string; + documentCount: number; + createdAt: string | null; +}; diff --git a/frontend/history-ui/src/lib/types/WebSocketClientMessage.ts b/frontend/history-ui/src/lib/types/WebSocketClientMessage.ts new file mode 100644 index 00000000..9608f3af --- /dev/null +++ b/frontend/history-ui/src/lib/types/WebSocketClientMessage.ts @@ -0,0 +1,7 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { CursorPositionFromClient } from "./CursorPositionFromClient"; +import type { WebSocketHandshake } from "./WebSocketHandshake"; + +export type WebSocketClientMessage = + | ({ type: "handshake" } & WebSocketHandshake) + | ({ type: "cursorPositions" } & CursorPositionFromClient); diff --git a/frontend/history-ui/src/lib/types/WebSocketHandshake.ts b/frontend/history-ui/src/lib/types/WebSocketHandshake.ts new file mode 100644 index 00000000..8e51a121 --- /dev/null +++ b/frontend/history-ui/src/lib/types/WebSocketHandshake.ts @@ -0,0 +1,7 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type WebSocketHandshake = { + token: string; + deviceId: string; + lastSeenVaultUpdateId: number | null; +}; diff --git a/frontend/history-ui/src/lib/types/WebSocketServerMessage.ts b/frontend/history-ui/src/lib/types/WebSocketServerMessage.ts new file mode 100644 index 00000000..fd250b7b --- /dev/null +++ b/frontend/history-ui/src/lib/types/WebSocketServerMessage.ts @@ -0,0 +1,7 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { CursorPositionFromServer } from "./CursorPositionFromServer"; +import type { WebSocketVaultUpdate } from "./WebSocketVaultUpdate"; + +export type WebSocketServerMessage = + | ({ type: "vaultUpdate" } & WebSocketVaultUpdate) + | ({ type: "cursorPositions" } & CursorPositionFromServer); diff --git a/frontend/history-ui/src/lib/types/WebSocketVaultUpdate.ts b/frontend/history-ui/src/lib/types/WebSocketVaultUpdate.ts new file mode 100644 index 00000000..94d70c0a --- /dev/null +++ b/frontend/history-ui/src/lib/types/WebSocketVaultUpdate.ts @@ -0,0 +1,4 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { DocumentVersionWithoutContent } from "./DocumentVersionWithoutContent"; + +export type WebSocketVaultUpdate = { document: DocumentVersionWithoutContent }; diff --git a/frontend/sync-client/src/services/types/CreateDocumentVersion.ts b/frontend/sync-client/src/services/types/CreateDocumentVersion.ts index ed921f18..2d83cd99 100644 --- a/frontend/sync-client/src/services/types/CreateDocumentVersion.ts +++ b/frontend/sync-client/src/services/types/CreateDocumentVersion.ts @@ -1,13 +1,7 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. export interface CreateDocumentVersion { - /** - * The client can decide the document id (if it wishes to) in order - * to help with syncing. If the client does not provide a document id, - * the server will generate one. If the client provides a document id - * it must not already exist in the database. - */ - document_id: string | null; relative_path: string; + last_seen_vault_update_id: number; content: number[]; } diff --git a/frontend/sync-client/src/services/types/DocumentUpdateResponse.ts b/frontend/sync-client/src/services/types/DocumentUpdateResponse.ts index 7fd06c7a..dd7eadda 100644 --- a/frontend/sync-client/src/services/types/DocumentUpdateResponse.ts +++ b/frontend/sync-client/src/services/types/DocumentUpdateResponse.ts @@ -3,7 +3,7 @@ import type { DocumentVersion } from "./DocumentVersion"; import type { DocumentVersionWithoutContent } from "./DocumentVersionWithoutContent"; /** - * Response to an update document request. + * Response to a create/update document request. */ export type DocumentUpdateResponse = | ({ type: "FastForwardUpdate" } & DocumentVersionWithoutContent) diff --git a/frontend/sync-client/src/services/types/DocumentVersionWithoutContent.ts b/frontend/sync-client/src/services/types/DocumentVersionWithoutContent.ts index 4b24e7c5..662b41e5 100644 --- a/frontend/sync-client/src/services/types/DocumentVersionWithoutContent.ts +++ b/frontend/sync-client/src/services/types/DocumentVersionWithoutContent.ts @@ -9,4 +9,8 @@ export interface DocumentVersionWithoutContent { userId: string; deviceId: string; contentSize: number; + /** + * True iff this is the first version of the document + */ + isNewFile: boolean; } diff --git a/frontend/sync-client/src/services/types/DocumentWithCursors.ts b/frontend/sync-client/src/services/types/DocumentWithCursors.ts index dcfe6e2d..8ed59067 100644 --- a/frontend/sync-client/src/services/types/DocumentWithCursors.ts +++ b/frontend/sync-client/src/services/types/DocumentWithCursors.ts @@ -2,8 +2,8 @@ import type { CursorSpan } from "./CursorSpan"; export interface DocumentWithCursors { - vault_update_id: number | null; - document_id: string; - relative_path: string; + vaultUpdateId: number | null; + documentId: string; + relativePath: string; cursors: CursorSpan[]; } diff --git a/frontend/sync-client/src/services/types/FetchLatestDocumentsResponse.ts b/frontend/sync-client/src/services/types/FetchLatestDocumentsResponse.ts index 160c9279..315d701a 100644 --- a/frontend/sync-client/src/services/types/FetchLatestDocumentsResponse.ts +++ b/frontend/sync-client/src/services/types/FetchLatestDocumentsResponse.ts @@ -7,7 +7,7 @@ import type { DocumentVersionWithoutContent } from "./DocumentVersionWithoutCont export interface FetchLatestDocumentsResponse { latestDocuments: DocumentVersionWithoutContent[]; /** - * The update ID of the latest document in the response. - */ + * The update ID of the latest document in the response. + */ lastUpdateId: bigint; } diff --git a/frontend/sync-client/src/services/types/ListVaultsResponse.ts b/frontend/sync-client/src/services/types/ListVaultsResponse.ts new file mode 100644 index 00000000..babad2d5 --- /dev/null +++ b/frontend/sync-client/src/services/types/ListVaultsResponse.ts @@ -0,0 +1,11 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { VaultInfo } from "./VaultInfo"; + +/** + * Response to listing vaults accessible to the authenticated user. + */ +export interface ListVaultsResponse { + vaults: VaultInfo[]; + hasMore: boolean; + userName: string; +} diff --git a/frontend/sync-client/src/services/types/PingResponse.ts b/frontend/sync-client/src/services/types/PingResponse.ts index 6db66354..f96520e9 100644 --- a/frontend/sync-client/src/services/types/PingResponse.ts +++ b/frontend/sync-client/src/services/types/PingResponse.ts @@ -5,21 +5,21 @@ */ export interface PingResponse { /** - * Semantic version of the server. - */ + * Semantic version of the server. + */ serverVersion: string; /** - * Whether the client is authenticated based on the sent Authorization - * header. - */ + * Whether the client is authenticated based on the sent Authorization + * header. + */ isAuthenticated: boolean; /** - * List of file extensions that are allowed to be merged. - */ + * List of file extensions that are allowed to be merged. + */ mergeableFileExtensions: string[]; /** - * API version ensuring backwards & forwards compatibility between the client - * and server. - */ + * API version ensuring backwards & forwards compatibility between the client + * and server. + */ supportedApiVersion: number; } diff --git a/frontend/sync-client/src/services/types/UpdateTextDocumentVersion.ts b/frontend/sync-client/src/services/types/UpdateTextDocumentVersion.ts index 46f36bd0..988e3b2f 100644 --- a/frontend/sync-client/src/services/types/UpdateTextDocumentVersion.ts +++ b/frontend/sync-client/src/services/types/UpdateTextDocumentVersion.ts @@ -2,6 +2,6 @@ export interface UpdateTextDocumentVersion { parentVersionId: number; - relativePath: string; + relativePath: string | null; content: (number | string)[]; } diff --git a/frontend/sync-client/src/services/types/VaultHistoryResponse.ts b/frontend/sync-client/src/services/types/VaultHistoryResponse.ts new file mode 100644 index 00000000..35531010 --- /dev/null +++ b/frontend/sync-client/src/services/types/VaultHistoryResponse.ts @@ -0,0 +1,10 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { DocumentVersionWithoutContent } from "./DocumentVersionWithoutContent"; + +/** + * Response to a vault history request (paginated). + */ +export interface VaultHistoryResponse { + versions: DocumentVersionWithoutContent[]; + hasMore: boolean; +} diff --git a/frontend/sync-client/src/services/types/VaultInfo.ts b/frontend/sync-client/src/services/types/VaultInfo.ts new file mode 100644 index 00000000..20d6811c --- /dev/null +++ b/frontend/sync-client/src/services/types/VaultInfo.ts @@ -0,0 +1,10 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Summary of a single vault returned by the list-vaults endpoint. + */ +export interface VaultInfo { + name: string; + documentCount: number; + createdAt: string | null; +} diff --git a/frontend/sync-client/src/services/types/WebSocketVaultUpdate.ts b/frontend/sync-client/src/services/types/WebSocketVaultUpdate.ts index f1ea0f80..b4a942c8 100644 --- a/frontend/sync-client/src/services/types/WebSocketVaultUpdate.ts +++ b/frontend/sync-client/src/services/types/WebSocketVaultUpdate.ts @@ -2,6 +2,5 @@ import type { DocumentVersionWithoutContent } from "./DocumentVersionWithoutContent"; export interface WebSocketVaultUpdate { - documents: DocumentVersionWithoutContent[]; - isInitialSync: boolean; + document: DocumentVersionWithoutContent; } From 9d99a4ac237ca3a081ecbcda63741c98049cb5d4 Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Fri, 8 May 2026 21:36:29 +0100 Subject: [PATCH 07/17] split: sync-client utils and errors reorganization Move error classes from services/ and file-operations/ into a new errors/ directory (authentication-error, server-version-mismatch-error, sync-reset-error, file-not-found-error), plus add file-already-exists-error and http-client-error. Update consts.ts and utils/* (await-all, create-client-id, hash, rate-limit, find-matching-file). Replace data-structures (locks, min-covered, event-listeners, fix-sized-cache) and add debugging utilities (in-memory-file-system, log-to-console, slow-web-socket-factory). Removes utils/create-promise.ts. --- frontend/sync-client/src/consts.ts | 6 +- .../authentication-error.ts | 0 .../src/errors/file-already-exists-error.ts | 9 + .../file-not-found-error.ts | 0 .../src/errors/http-client-error.ts | 9 + .../server-version-mismatch-error.ts | 0 .../{services => errors}/sync-reset-error.ts | 0 frontend/sync-client/src/utils/await-all.ts | 2 +- .../sync-client/src/utils/create-client-id.ts | 8 +- .../sync-client/src/utils/create-promise.ts | 25 --- .../utils/data-structures/event-listeners.ts | 74 +++++---- .../utils/data-structures/fix-sized-cache.ts | 2 +- .../src/utils/data-structures/locks.test.ts | 83 ++++++++-- .../src/utils/data-structures/locks.ts | 156 ++++++++++-------- .../utils/data-structures/min-covered.test.ts | 40 ++--- .../src/utils/data-structures/min-covered.ts | 15 +- .../utils/debugging/in-memory-file-system.ts | 69 ++++++++ .../src/utils/debugging/log-to-console.ts | 44 ++++- .../debugging/slow-web-socket-factory.ts | 2 +- .../src/utils/find-matching-file.ts | 13 +- frontend/sync-client/src/utils/hash.ts | 22 +-- frontend/sync-client/src/utils/rate-limit.ts | 20 +-- 22 files changed, 384 insertions(+), 215 deletions(-) rename frontend/sync-client/src/{services => errors}/authentication-error.ts (100%) create mode 100644 frontend/sync-client/src/errors/file-already-exists-error.ts rename frontend/sync-client/src/{file-operations => errors}/file-not-found-error.ts (100%) create mode 100644 frontend/sync-client/src/errors/http-client-error.ts rename frontend/sync-client/src/{services => errors}/server-version-mismatch-error.ts (100%) rename frontend/sync-client/src/{services => errors}/sync-reset-error.ts (100%) delete mode 100644 frontend/sync-client/src/utils/create-promise.ts create mode 100644 frontend/sync-client/src/utils/debugging/in-memory-file-system.ts diff --git a/frontend/sync-client/src/consts.ts b/frontend/sync-client/src/consts.ts index da70ba47..86319fd7 100644 --- a/frontend/sync-client/src/consts.ts +++ b/frontend/sync-client/src/consts.ts @@ -1,6 +1,6 @@ export const TIMEOUT_FOR_MERGING_HISTORY_ENTRIES_IN_SECONDS = 60; -export const DIFF_CACHE_SIZE_MB = 2; export const MAX_LOG_MESSAGE_COUNT = 100000; export const MAX_HISTORY_ENTRY_COUNT = 5000; -export const SUPPORTED_API_VERSION = 2; -export const WEBSOCKET_DISCONNECT_TIMEOUT_IN_S = 10; +export const SUPPORTED_API_VERSION = 3; +export const WEBSOCKET_DISCONNECT_TIMEOUT_IN_SECONDS = 10; +export const WEBSOCKET_CONNECTION_TIMEOUT_IN_SECONDS = 10; diff --git a/frontend/sync-client/src/services/authentication-error.ts b/frontend/sync-client/src/errors/authentication-error.ts similarity index 100% rename from frontend/sync-client/src/services/authentication-error.ts rename to frontend/sync-client/src/errors/authentication-error.ts diff --git a/frontend/sync-client/src/errors/file-already-exists-error.ts b/frontend/sync-client/src/errors/file-already-exists-error.ts new file mode 100644 index 00000000..35f51a66 --- /dev/null +++ b/frontend/sync-client/src/errors/file-already-exists-error.ts @@ -0,0 +1,9 @@ +export class FileAlreadyExistsError extends Error { + public constructor( + message: string, + public readonly filePath: string + ) { + super(message); + this.name = "FileAlreadyExistsError"; + } +} diff --git a/frontend/sync-client/src/file-operations/file-not-found-error.ts b/frontend/sync-client/src/errors/file-not-found-error.ts similarity index 100% rename from frontend/sync-client/src/file-operations/file-not-found-error.ts rename to frontend/sync-client/src/errors/file-not-found-error.ts diff --git a/frontend/sync-client/src/errors/http-client-error.ts b/frontend/sync-client/src/errors/http-client-error.ts new file mode 100644 index 00000000..2475cf35 --- /dev/null +++ b/frontend/sync-client/src/errors/http-client-error.ts @@ -0,0 +1,9 @@ +export class HttpClientError extends Error { + public constructor( + public readonly statusCode: number, + message: string + ) { + super(message); + this.name = "HttpClientError"; + } +} diff --git a/frontend/sync-client/src/services/server-version-mismatch-error.ts b/frontend/sync-client/src/errors/server-version-mismatch-error.ts similarity index 100% rename from frontend/sync-client/src/services/server-version-mismatch-error.ts rename to frontend/sync-client/src/errors/server-version-mismatch-error.ts diff --git a/frontend/sync-client/src/services/sync-reset-error.ts b/frontend/sync-client/src/errors/sync-reset-error.ts similarity index 100% rename from frontend/sync-client/src/services/sync-reset-error.ts rename to frontend/sync-client/src/errors/sync-reset-error.ts diff --git a/frontend/sync-client/src/utils/await-all.ts b/frontend/sync-client/src/utils/await-all.ts index 9406a6b8..43e06ce6 100644 --- a/frontend/sync-client/src/utils/await-all.ts +++ b/frontend/sync-client/src/utils/await-all.ts @@ -9,7 +9,7 @@ type ResolvedTuple = { export const awaitAll = async ( promises: PromiseTuple ): Promise> => { - // eslint-disable-next-line no-restricted-properties + // eslint-disable-next-line no-restricted-properties, @typescript-eslint/await-thenable const result = await Promise.allSettled(promises); for (const res of result) { if (res.status === "rejected") { diff --git a/frontend/sync-client/src/utils/create-client-id.ts b/frontend/sync-client/src/utils/create-client-id.ts index cfa132da..03dc2ae9 100644 --- a/frontend/sync-client/src/utils/create-client-id.ts +++ b/frontend/sync-client/src/utils/create-client-id.ts @@ -1,5 +1,3 @@ -import { v4 as uuidv4 } from "uuid"; - export function createClientId(): string { // @ts-expect-error, injected by webpack const packageVersion = __CURRENT_VERSION__; // eslint-disable-line @@ -8,8 +6,8 @@ export function createClientId(): string { typeof navigator !== "undefined" ? navigator.platform // eslint-disable-line @typescript-eslint/no-deprecated : typeof process !== "undefined" - ? process.platform - : "unknown"; + ? process.platform + : "unknown"; - return `vault-link/${packageVersion} (${uuidv4()}; ${platform})`; + return `vault-link/${packageVersion} (${Math.round(Math.random() * 1e10)}; ${platform})`; } diff --git a/frontend/sync-client/src/utils/create-promise.ts b/frontend/sync-client/src/utils/create-promise.ts deleted file mode 100644 index a49196ee..00000000 --- a/frontend/sync-client/src/utils/create-promise.ts +++ /dev/null @@ -1,25 +0,0 @@ -type ResolveFunction = undefined extends T - ? (value?: T) => unknown - : (value: T) => unknown; - -/** - * A type-safe utility function to create a Promise with resolve and reject functions. - * @returns A tuple containing a Promise, a resolve function, and a reject function. - */ -export function createPromise(): [ - Promise, - ResolveFunction, - (error: unknown) => unknown -] { - let resolve: undefined | ResolveFunction = undefined; - let reject: undefined | ((error: unknown) => unknown) = undefined; - - const creationPromise = new Promise( - (resolve_, reject_) => - // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion - ((resolve = resolve_ as ResolveFunction), (reject = reject_)) - ); - - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - return [creationPromise, resolve!, reject!]; -} diff --git a/frontend/sync-client/src/utils/data-structures/event-listeners.ts b/frontend/sync-client/src/utils/data-structures/event-listeners.ts index e08ca65e..420e4e63 100644 --- a/frontend/sync-client/src/utils/data-structures/event-listeners.ts +++ b/frontend/sync-client/src/utils/data-structures/event-listeners.ts @@ -13,56 +13,64 @@ export class EventListeners any> { } /** - * Adds a new listener to the collection. - * - * @param listener The listener callback to add - * @returns An unsubscribe function that removes this listener when called - */ + * Adds a new listener to the collection. + * + * @param listener The listener callback to add + * @returns An unsubscribe function that removes this listener when called + */ public add(listener: TListener): () => void { this.listeners.push(listener); return () => this.remove(listener); } /** - * Removes a listener from the collection. - * - * @param listener The listener callback to remove - * @returns true if the listener was found and removed, false otherwise - */ + * Removes a listener from the collection. + * + * @param listener The listener callback to remove + * @returns true if the listener was found and removed, false otherwise + */ public remove(listener: TListener): boolean { return removeFromArray(this.listeners, listener); } /** - * Triggers all listeners synchronously with the provided arguments. - * Any returned promises are ignored. Use triggerAsync() to await them. - * - * @param args The arguments to pass to each listener - */ + * Triggers all listeners synchronously with the provided arguments. + * Any returned promises are ignored. Use triggerAsync() to await them. + * + * @param args The arguments to pass to each listener + */ public trigger(...args: Parameters): void { - this.listeners.forEach((listener) => { + const snapshot = this.listeners.slice(); + for (const listener of snapshot) { + // allow removing listeners during the trigger loop + if (!this.listeners.includes(listener)) { + continue; + } listener(...args); - }); + } } /** - * Triggers all listeners and awaits any promises they return. - * Synchronous listeners are called immediately, and any async listeners - * are awaited in parallel. - * - * @param args The arguments to pass to each listener - */ + * Triggers all listeners and awaits any promises they return. + * Synchronous listeners are called immediately, and any async listeners + * are awaited in parallel. + * + * @param args The arguments to pass to each listener + */ public async triggerAsync(...args: Parameters): Promise { - await awaitAll( - this.listeners - .map((listener) => { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return listener(...args); - }) - .filter((result): result is Promise => { - return result instanceof Promise; - }) - ); + const snapshot = this.listeners.slice(); + const promises: Promise[] = []; + for (const listener of snapshot) { + if (!this.listeners.includes(listener)) { + continue; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const result = listener(...args); + if (result instanceof Promise) { + promises.push(result); + } + } + await awaitAll(promises); } public clear(): void { diff --git a/frontend/sync-client/src/utils/data-structures/fix-sized-cache.ts b/frontend/sync-client/src/utils/data-structures/fix-sized-cache.ts index 51ad41c1..44a71dc8 100644 --- a/frontend/sync-client/src/utils/data-structures/fix-sized-cache.ts +++ b/frontend/sync-client/src/utils/data-structures/fix-sized-cache.ts @@ -1,6 +1,6 @@ // Implements an in-memory fixed-size cache for document contents, -import type { VaultUpdateId } from "../../persistence/database"; +import type { VaultUpdateId } from "../../sync-operations/types"; // Doubly-linked list node for O(1) LRU operations class LRUNode { diff --git a/frontend/sync-client/src/utils/data-structures/locks.test.ts b/frontend/sync-client/src/utils/data-structures/locks.test.ts index 9beb867a..c98bda0b 100644 --- a/frontend/sync-client/src/utils/data-structures/locks.test.ts +++ b/frontend/sync-client/src/utils/data-structures/locks.test.ts @@ -1,22 +1,24 @@ import { describe, it, beforeEach } from "node:test"; import assert from "node:assert"; import { Logger } from "../../tracing/logger"; -import type { RelativePath } from "../../persistence/database"; +import type { RelativePath } from "../../sync-operations/types"; import { Locks } from "./locks"; import { awaitAll } from "../await-all"; import { sleep } from "../sleep"; -import { SyncResetError } from "../../services/sync-reset-error"; +import { SyncResetError } from "../../errors/sync-reset-error"; describe("withLock", () => { const testPath: RelativePath = "test/document/path"; const testPath2: RelativePath = "test/document/path2"; + const testPath3: RelativePath = "test/document/path3"; + const logger = new Logger(); // eslint-disable-next-line @typescript-eslint/init-declarations let locks: Locks; beforeEach(() => { - locks = new Locks(logger); + locks = new Locks("locks-test", logger); }); it("should execute function with single key lock", async () => { @@ -56,22 +58,32 @@ describe("withLock", () => { it("should sort multiple keys to prevent deadlocks", async () => { const executionOrder: string[] = []; - // Start two concurrent operations with keys in different orders - const promise1 = locks.withLock([testPath2, testPath], async () => { - executionOrder.push("operation1-start"); - await sleep(50); - executionOrder.push("operation1-end"); - return "result1"; - }); + await locks.waitForLock(testPath); - const promise2 = locks.withLock([testPath, testPath2], async () => { - executionOrder.push("operation2-start"); - await sleep(50); - executionOrder.push("operation2-end"); - return "result2"; - }); + const promise = awaitAll([ + locks.withLock([testPath2, testPath3, testPath], async () => { + executionOrder.push("operation1-start"); + executionOrder.push("operation1-end"); + return "result1"; + }), - const [result1, result2] = await awaitAll([promise1, promise2]); + locks.withLock([testPath3, testPath, testPath2], async () => { + executionOrder.push("operation2-start"); + executionOrder.push("operation2-end"); + return "result2"; + }) + ]); + + locks.unlock(testPath); + + const [result1, result2] = await Promise.race([ + promise, + new Promise((_, reject) => { + setTimeout(() => { + reject(new Error("Deadlock detected")); + }, 1000); + }) + ]); assert.strictEqual(result1, "result1"); assert.strictEqual(result2, "result2"); @@ -234,13 +246,14 @@ describe("withLock", () => { describe("reset", () => { const testPath: RelativePath = "test/document/path"; + const testPath2: RelativePath = "test/document/path2"; const logger = new Logger(); // eslint-disable-next-line @typescript-eslint/init-declarations let locks: Locks; beforeEach(() => { - locks = new Locks(logger); + locks = new Locks("locks-test", logger); }); it("should reject pending waiters with SyncResetError while running operation completes", async () => { @@ -289,4 +302,38 @@ describe("reset", () => { const result = await locks.withLock(testPath, () => "success"); assert.strictEqual(result, "success"); }); + + it("should release partially acquired locks when reset interrupts multi-key acquisition", async () => { + // Hold testPath2 so multi-key acquisition will block on it + await locks.waitForLock(testPath2); + + // Start multi-key lock that will acquire testPath first, then block on testPath2 + const multiKeyPromise = locks.withLock( + [testPath, testPath2], + async () => "multi" + ); + void multiKeyPromise.catch(() => {}); // eslint-disable-line @typescript-eslint/no-empty-function + + // Wait for the multi-key operation to acquire testPath and start waiting on testPath2 + await sleep(10); + + // Reset should reject the waiting operation + locks.reset(); + + await assert.rejects(multiKeyPromise, (err: Error) => { + assert.ok(err instanceof SyncResetError); + return true; + }); + + // The key that was already acquired (testPath) should now be released + // This would hang/timeout if the lock was leaked + const result = await Promise.race([ + locks.withLock(testPath, () => "success"), + sleep(100).then(() => { + throw new Error("Lock was not released - deadlock detected"); + }) + ]); + + assert.strictEqual(result, "success"); + }); }); diff --git a/frontend/sync-client/src/utils/data-structures/locks.ts b/frontend/sync-client/src/utils/data-structures/locks.ts index e55c76b0..99c33075 100644 --- a/frontend/sync-client/src/utils/data-structures/locks.ts +++ b/frontend/sync-client/src/utils/data-structures/locks.ts @@ -1,6 +1,5 @@ -import { SyncResetError } from "../../services/sync-reset-error"; +import { SyncResetError } from "../../errors/sync-reset-error"; import type { Logger } from "../../tracing/logger"; -import { awaitAll } from "../await-all"; /** * Manages exclusive locks on items to prevent concurrent modifications. @@ -8,47 +7,53 @@ import { awaitAll } from "../await-all"; * * @template T The type of the key used for locking */ +/** Waiter entry with callbacks */ +interface WaiterEntry { + resolve: () => unknown; + reject: (err: unknown) => unknown; +} + export class Locks { /** Currently locked keys */ private readonly locked = new Set(); - /** Queue of resolve functions waiting for each key */ - private readonly waiters = new Map< - T, - [() => unknown, (err: unknown) => unknown][] - >(); + /** Queue of waiters for each key */ + private readonly waiters = new Map(); - public constructor(private readonly logger?: Logger) {} + public constructor( + private readonly name: string, + private readonly logger?: Logger + ) {} /** - * Executes a function while holding exclusive locks on one or more keys. - * - * This method ensures that the provided function runs with exclusive access to the - * specified key(s). Multiple keys are sorted to prevent deadlocks when different - * operations request the same keys in different orders. - * - * @template R The return type of the function to execute - * @param keyOrKeys A single key or array of keys to lock during function execution - * @param fn The function to execute while holding the lock(s). Can be sync or async. - * @returns A Promise that resolves to the return value of the executed function - * - * @example - * ```typescript - * // Lock a single key - * const result = await locks.withLock('file1', () => { - * // Critical section - only one operation can access 'file1' at a time - * return processFile('file1'); - * }); - * - * // Lock multiple keys (prevents deadlocks through consistent ordering) - * await locks.withLock(['file1', 'file2'], async () => { - * // Critical section - exclusive access to both files - * await moveFile('file1', 'file2'); - * }); - * ``` - * - * @throws Any error thrown by the provided function will be propagated after locks are released - */ + * Executes a function while holding exclusive locks on one or more keys. + * + * This method ensures that the provided function runs with exclusive access to the + * specified key(s). Multiple keys are sorted to prevent deadlocks when different + * operations request the same keys in different orders. + * + * @template R The return type of the function to execute + * @param keyOrKeys A single key or array of keys to lock during function execution + * @param fn The function to execute while holding the lock(s). Can be sync or async. + * @returns A Promise that resolves to the return value of the executed function + * + * @example + * ```typescript + * // Lock a single key + * const result = await locks.withLock('file1', () => { + * // Critical section - only one operation can access 'file1' at a time + * return processFile('file1'); + * }); + * + * // Lock multiple keys (prevents deadlocks through consistent ordering) + * await locks.withLock(['file1', 'file2'], async () => { + * // Critical section - exclusive access to both files + * await moveFile('file1', 'file2'); + * }); + * ``` + * + * @throws Any error thrown by the provided function will be propagated after locks are released + */ public async withLock( keyOrKeys: T | T[], fn: () => R | Promise @@ -59,12 +64,17 @@ export class Locks { const uniqueKeys = Array.from(new Set(keys)); uniqueKeys.sort((a, b) => String(a).localeCompare(String(b))); // Ensure consistent order to prevent deadlocks - await awaitAll(uniqueKeys.map(async (key) => this.waitForLock(key))); - + const lockedKeys = []; try { + for (const key of uniqueKeys) { + // Must acquire locks in-order (not concurrently) to prevent deadlocks + await this.waitForLock(key); + lockedKeys.push(key); + } + return await fn(); } finally { - uniqueKeys.forEach((key) => { + lockedKeys.forEach((key) => { this.unlock(key); }); } @@ -74,7 +84,7 @@ export class Locks { // Resolve all waiting promises before clearing to prevent deadlock // Any operation waiting for a lock will be granted access immediately for (const waiting of this.waiters.values()) { - for (const [_, reject] of waiting) { + for (const { reject } of waiting) { reject(new SyncResetError()); } } @@ -82,13 +92,17 @@ export class Locks { this.waiters.clear(); } + public isLocked(key: T): boolean { + return this.locked.has(key); + } + /** - * Attempts to acquire a lock immediately without waiting. - * Must call `unlock()` if successful. - * - * @param key The key to lock - * @returns `true` if lock acquired, `false` if already locked - */ + * Attempts to acquire a lock immediately without waiting. + * Must call `unlock()` if successful. + * + * @param key The key to lock + * @returns `true` if lock acquired, `false` if already locked + */ public tryLock(key: T): boolean { if (this.locked.has(key)) { return false; @@ -100,18 +114,18 @@ export class Locks { } /** - * Waits to acquire a lock, blocking until available. - * Operations are queued in FIFO order. Must call `unlock()` when done. - * - * @param key The key to wait for and lock - * @returns Promise that resolves when lock is acquired - */ + * Waits to acquire a lock, blocking until available. + * Operations are queued in FIFO order. Must call `unlock()` when done. + * + * @param key The key to wait for and lock + * @returns Promise that resolves when lock is acquired + */ public async waitForLock(key: T): Promise { if (this.tryLock(key)) { return Promise.resolve(); } - this.logger?.debug(`Waiting for lock on ${key}`); + this.logger?.debug(`Waiting for lock '${this.name}' on '${key}'`); return new Promise((resolve, reject) => { // DefaultDict behavior @@ -121,28 +135,36 @@ export class Locks { this.waiters.set(key, waiting); } - waiting.push([resolve, reject]); + waiting.push({ + resolve, + reject + }); }); } /** - * Releases a lock and grants access to the next waiting operation in FIFO order. - * Removes the key from locked set if no waiters. - * - * @param key The key to unlock - * @throws {Error} If key is not currently locked - */ + * Releases a lock and grants access to the next waiting operation in FIFO order. + * Removes the key from locked set if no waiters. + * + * @param key The key to unlock + * @throws {Error} If key is not currently locked + */ public unlock(key: T): void { if (!this.locked.has(key)) { + this.logger?.debug( + `Attempted to unlock '${this.name}' on '${key}' which is not locked` + ); return; } - // Remove first waiter to ensure FIFO order - const [resolveNextWaiting, _] = this.waiters.get(key)?.shift() ?? []; + this.logger?.debug(`Releasing lock '${this.name}' on '${key}'`); - if (resolveNextWaiting) { - this.logger?.debug(`Granted lock on ${key}`); - resolveNextWaiting(); + // Remove first waiter to ensure FIFO order + const nextWaiter = this.waiters.get(key)?.shift(); + + if (nextWaiter) { + this.logger?.debug(`Granted lock '${this.name}' on '${key}'`); + nextWaiter.resolve(); } else { this.locked.delete(key); } @@ -152,8 +174,8 @@ export class Locks { export class Lock { private readonly locks: Locks; - public constructor(logger?: Logger) { - this.locks = new Locks(logger); + public constructor(name: string, logger?: Logger) { + this.locks = new Locks(name, logger); } public async withLock(fn: () => R | Promise): Promise { diff --git a/frontend/sync-client/src/utils/data-structures/min-covered.test.ts b/frontend/sync-client/src/utils/data-structures/min-covered.test.ts index 7b7271d7..752227c0 100644 --- a/frontend/sync-client/src/utils/data-structures/min-covered.test.ts +++ b/frontend/sync-client/src/utils/data-structures/min-covered.test.ts @@ -1,15 +1,15 @@ import { describe, it } from "node:test"; import assert from "node:assert"; -import { CoveredValues } from "./min-covered"; +import { MinCovered } from "./min-covered"; -describe("CoveredValues", () => { +describe("MinCovered", () => { it("should initialize with the given min value", () => { - const covered = new CoveredValues(5); + const covered = new MinCovered(5); assert.strictEqual(covered.min, 5); }); it("should add values greater than min", () => { - const covered = new CoveredValues(0); + const covered = new MinCovered(0); covered.add(3); assert.strictEqual(covered.min, 0); covered.add(1); @@ -21,7 +21,7 @@ describe("CoveredValues", () => { }); it("should ignore duplicate values", () => { - const covered = new CoveredValues(0); + const covered = new MinCovered(0); covered.add(3); covered.add(3); covered.add(3); @@ -32,7 +32,7 @@ describe("CoveredValues", () => { }); it("should handle multiple consecutive values", () => { - const covered = new CoveredValues(132); + const covered = new MinCovered(132); for (let i = 250; i > 132; i--) { assert.strictEqual(covered.min, 132); covered.add(i); @@ -41,36 +41,32 @@ describe("CoveredValues", () => { }); it("should handle adding values lower than current min", () => { - const covered = new CoveredValues(5); + const covered = new MinCovered(5); covered.add(3); assert.strictEqual(covered.min, 5); covered.add(6); assert.strictEqual(covered.min, 6); }); - it("should auto-advance when setting min value", () => { - const covered = new CoveredValues(5); + it("should auto-advance when adding the value that fills the next gap", () => { + const covered = new MinCovered(5); covered.add(7); covered.add(8); covered.add(9); assert.strictEqual(covered.min, 5); - // Setting min to 6 should auto-advance through 7, 8, 9 - covered.min = 6; + // Adding 6 fills the gap and auto-advances through 7, 8, 9 + covered.add(6); assert.strictEqual(covered.min, 9); covered.add(10); assert.strictEqual(covered.min, 10); }); - it("should handle setting min value with no consecutive values", () => { - const covered = new CoveredValues(5); - covered.add(10); - covered.add(15); - assert.strictEqual(covered.min, 5); - // Setting min to 8 should not auto-advance (no consecutive values) - covered.min = 8; - assert.strictEqual(covered.min, 8); - // Add 9 to trigger auto-advance to 10 - covered.add(9); - assert.strictEqual(covered.min, 10); + it("should rewind when reset is called explicitly", () => { + const covered = new MinCovered(5); + covered.add(7); + covered.reset(3); + assert.strictEqual(covered.min, 3); + covered.add(4); + assert.strictEqual(covered.min, 4); }); }); diff --git a/frontend/sync-client/src/utils/data-structures/min-covered.ts b/frontend/sync-client/src/utils/data-structures/min-covered.ts index 8b38822f..ed0b9d2e 100644 --- a/frontend/sync-client/src/utils/data-structures/min-covered.ts +++ b/frontend/sync-client/src/utils/data-structures/min-covered.ts @@ -7,13 +7,13 @@ * * @example * ```typescript - * const covered = new CoveredValues(0); + * const covered = new MinCovered(0); * covered.add(2); // seenValues = [2], min = 0 * covered.add(1); // seenValues = [], min = 2 * covered.min; // returns 2 * ``` */ -export class CoveredValues { +export class MinCovered { private seenValues: number[] = []; public constructor(private minValue: number) {} @@ -22,12 +22,6 @@ export class CoveredValues { return this.minValue; } - public set min(value: number) { - this.minValue = Math.max(value, this.minValue); - this.seenValues = this.seenValues.filter((v) => v > this.minValue); - this.advanceMinWhilePossible(); - } - public add(value: number | undefined): void { if (value === undefined || value < this.minValue) { return; @@ -49,6 +43,11 @@ export class CoveredValues { this.advanceMinWhilePossible(); } + public reset(minValue?: number): void { + this.minValue = minValue ?? 0; + this.seenValues = []; + } + private advanceMinWhilePossible(): void { while ( this.seenValues.length > 0 && diff --git a/frontend/sync-client/src/utils/debugging/in-memory-file-system.ts b/frontend/sync-client/src/utils/debugging/in-memory-file-system.ts new file mode 100644 index 00000000..0d26b175 --- /dev/null +++ b/frontend/sync-client/src/utils/debugging/in-memory-file-system.ts @@ -0,0 +1,69 @@ +import type { RelativePath } from "../../sync-operations/types"; +import type { TextWithCursors } from "reconcile-text"; +import type { FileSystemOperations } from "../../file-operations/filesystem-operations"; + +export class InMemoryFileSystem implements FileSystemOperations { + protected readonly files = new Map(); + + public async listFilesRecursively( + _root: RelativePath | undefined = undefined // we don't use multi-level paths during tests + ): Promise { + return Array.from(this.files.keys()); + } + + public async read(path: RelativePath): Promise { + const file = this.files.get(path); + if (!file) { + throw new Error(`File ${path} does not exist`); + } + return file; + } + + public async write(path: RelativePath, content: Uint8Array): Promise { + this.files.set(path, content); + } + + public async atomicUpdateText( + path: RelativePath, + updater: (current: TextWithCursors) => TextWithCursors + ): Promise { + const file = this.files.get(path); + if (!file) { + throw new Error(`File ${path} does not exist`); + } + const currentContent = new TextDecoder().decode(file); + const newContent = updater({ text: currentContent, cursors: [] }).text; + this.files.set(path, new TextEncoder().encode(newContent)); + return newContent; + } + + public async getFileSize(path: RelativePath): Promise { + return (await this.read(path)).length; + } + + public async exists(path: RelativePath): Promise { + return this.files.has(path); + } + + public async createDirectory(_path: RelativePath): Promise { + // This doesn't mean anything in our virtual FS representation + } + + public async delete(path: RelativePath): Promise { + this.files.delete(path); + } + + public async rename( + oldPath: RelativePath, + newPath: RelativePath + ): Promise { + const file = this.files.get(oldPath); + if (!file) { + throw new Error(`File ${oldPath} does not exist`); + } + this.files.set(newPath, file); + if (oldPath !== newPath) { + this.files.delete(oldPath); + } + } +} diff --git a/frontend/sync-client/src/utils/debugging/log-to-console.ts b/frontend/sync-client/src/utils/debugging/log-to-console.ts index c47f18f6..def71400 100644 --- a/frontend/sync-client/src/utils/debugging/log-to-console.ts +++ b/frontend/sync-client/src/utils/debugging/log-to-console.ts @@ -1,10 +1,44 @@ -import type { SyncClient } from "../../sync-client"; -import type { LogLine } from "../../tracing/logger"; +/* eslint-disable no-console */ +import type { Logger, LogLine } from "../../tracing/logger"; import { LogLevel } from "../../tracing/logger"; -export function logToConsole(client: SyncClient): void { - client.logger.onLogEmitted.add((logLine: LogLine) => { - const formatted = `${logLine.timestamp.toISOString()} ${logLine.level} ${logLine.message}`; +const COLORS = { + reset: "\x1b[0m", + red: "\x1b[31m", + yellow: "\x1b[33m", + blue: "\x1b[34m", + gray: "\x1b[90m" +}; + +export function logToConsole( + logger: Logger, + { useColors = true }: { useColors?: boolean } = {} +): void { + logger.onLogEmitted.add((logLine: LogLine) => { + const timestamp = logLine.timestamp.toISOString(); + const { message } = logLine; + + let color = ""; + let reset = ""; + if (useColors) { + ({ reset } = COLORS); + switch (logLine.level) { + case LogLevel.ERROR: + color = COLORS.red; + break; + case LogLevel.WARNING: + color = COLORS.yellow; + break; + case LogLevel.INFO: + color = COLORS.blue; + break; + case LogLevel.DEBUG: + color = COLORS.gray; + break; + } + } + + const formatted = `${timestamp} ${color}${logLine.level}${reset} ${message}`; switch (logLine.level) { case LogLevel.ERROR: diff --git a/frontend/sync-client/src/utils/debugging/slow-web-socket-factory.ts b/frontend/sync-client/src/utils/debugging/slow-web-socket-factory.ts index c64bff18..b93460b5 100644 --- a/frontend/sync-client/src/utils/debugging/slow-web-socket-factory.ts +++ b/frontend/sync-client/src/utils/debugging/slow-web-socket-factory.ts @@ -11,7 +11,7 @@ export function slowWebSocketFactory( private static readonly RECEIVE_KEY = "websocket-receive"; private static readonly SEND_KEY = "websocket-send"; - private readonly locks = new Locks(logger); + private readonly locks = new Locks(FlakyWebSocket.name, logger); public set onopen(callback: ((event: Event) => void) | null) { super.onopen = async (event: Event): Promise => { diff --git a/frontend/sync-client/src/utils/find-matching-file.ts b/frontend/sync-client/src/utils/find-matching-file.ts index c3d323d3..1e0b352c 100644 --- a/frontend/sync-client/src/utils/find-matching-file.ts +++ b/frontend/sync-client/src/utils/find-matching-file.ts @@ -1,14 +1,17 @@ -import type { DocumentRecord } from "../persistence/database"; +import type { DocumentRecord } from "../sync-operations/types"; import { EMPTY_HASH } from "./hash"; // TODO: make this smarter so that offline files can be renamed & edited at the same time -export function findMatchingFile( +export async function findMatchingFile( contentHash: string, candidates: DocumentRecord[] -): DocumentRecord | undefined { - if (contentHash === EMPTY_HASH) { +): Promise { + if (contentHash === (await EMPTY_HASH)) { return undefined; } - return candidates.find(({ metadata }) => metadata?.hash === contentHash); + return candidates.find( + (record) => + record.remoteHash !== undefined && record.remoteHash === contentHash + ); } diff --git a/frontend/sync-client/src/utils/hash.ts b/frontend/sync-client/src/utils/hash.ts index 906b6fad..b9d23041 100644 --- a/frontend/sync-client/src/utils/hash.ts +++ b/frontend/sync-client/src/utils/hash.ts @@ -1,12 +1,14 @@ -// https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript -export function hash(content: Uint8Array): string { - let result = 0; - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (let i = 0; i < content.length; i++) { - result = (result << 5) - result + content[i]; - result |= 0; // Convert to 32bit integer - } - return Math.abs(result).toString(16).padStart(8, "0"); +export async function hash(content: Uint8Array): Promise { + // Re-wrap into a fresh Uint8Array so SubtleCrypto's + // BufferSource overload accepts it without an unsafe type assertion. + // The lib types require an ArrayBuffer-backed view; the source may + // be backed by SharedArrayBuffer in some runtimes. + const buffer = new ArrayBuffer(content.byteLength); + new Uint8Array(buffer).set(content); + const digest = await crypto.subtle.digest("SHA-256", buffer); + const bytes = new Uint8Array(digest); + return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); } -export const EMPTY_HASH = hash(new Uint8Array(0)); +// SHA-256 of empty content, computed once at import time +export const EMPTY_HASH: Promise = hash(new Uint8Array()); diff --git a/frontend/sync-client/src/utils/rate-limit.ts b/frontend/sync-client/src/utils/rate-limit.ts index 52cbbce7..acb86393 100644 --- a/frontend/sync-client/src/utils/rate-limit.ts +++ b/frontend/sync-client/src/utils/rate-limit.ts @@ -1,4 +1,4 @@ -import { createPromise } from "./create-promise"; +import { awaitAll } from "./await-all"; import { sleep } from "./sleep"; /** @@ -45,18 +45,16 @@ export function rateLimit< newArgs = undefined; } - const [promise, resolve] = createPromise(); - running = promise; - sleep( + // `running` must signal both "minimum interval has elapsed" *and* + // "fn() has finished" — otherwise an `fn` that takes longer than + // the interval would let a queued waiter fire a concurrent `fn` + const interval = typeof minIntervalMs === "function" ? minIntervalMs() - : minIntervalMs - ) - .then(resolve) - .catch(() => { - // sleep cannot fail - }); - return fn(...args); + : minIntervalMs; + const fnPromise = fn(...args); + running = awaitAll([fnPromise.catch(() => undefined), sleep(interval)]); + return fnPromise; }; return decoratedFn; From 45b86cffe43ce173cfb0e4da40dd82f5e5b6ff27 Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Fri, 8 May 2026 21:36:41 +0100 Subject: [PATCH 08/17] split: sync-client services layer Add build-vault-url helper. Rewrite fetch-controller and websocket-manager (plus their tests). Update server-config and sync-service to consume the new error types and the regenerated API types from previous chunks. --- .../src/services/build-vault-url.ts | 8 + .../src/services/fetch-controller.test.ts | 2 +- .../src/services/fetch-controller.ts | 79 +++--- .../sync-client/src/services/server-config.ts | 40 ++- .../sync-client/src/services/sync-service.ts | 181 +++++++------- .../src/services/websocket-manager.test.ts | 71 +++++- .../src/services/websocket-manager.ts | 228 +++++++++++------- 7 files changed, 377 insertions(+), 232 deletions(-) create mode 100644 frontend/sync-client/src/services/build-vault-url.ts diff --git a/frontend/sync-client/src/services/build-vault-url.ts b/frontend/sync-client/src/services/build-vault-url.ts new file mode 100644 index 00000000..1f5002d7 --- /dev/null +++ b/frontend/sync-client/src/services/build-vault-url.ts @@ -0,0 +1,8 @@ +import type { Settings } from "../persistence/settings"; + +export function buildVaultUrl(settings: Settings, path: string): string { + const { vaultName, remoteUri } = settings.getSettings(); + const remoteUriWithoutTrailingSlash = remoteUri.replace(/\/+$/, ""); + const encodedVaultName = encodeURIComponent(vaultName.trim()); + return `${remoteUriWithoutTrailingSlash}/vaults/${encodedVaultName}${path}`; +} diff --git a/frontend/sync-client/src/services/fetch-controller.test.ts b/frontend/sync-client/src/services/fetch-controller.test.ts index 94fa8424..a1b791a6 100644 --- a/frontend/sync-client/src/services/fetch-controller.test.ts +++ b/frontend/sync-client/src/services/fetch-controller.test.ts @@ -3,7 +3,7 @@ import { describe, it, mock, beforeEach, afterEach } from "node:test"; import assert from "node:assert"; import { FetchController } from "./fetch-controller"; import { Logger } from "../tracing/logger"; -import { SyncResetError } from "./sync-reset-error"; +import { SyncResetError } from "../errors/sync-reset-error"; import { sleep } from "../utils/sleep"; describe("FetchController", () => { diff --git a/frontend/sync-client/src/services/fetch-controller.ts b/frontend/sync-client/src/services/fetch-controller.ts index 77b87e3a..f5bb8664 100644 --- a/frontend/sync-client/src/services/fetch-controller.ts +++ b/frontend/sync-client/src/services/fetch-controller.ts @@ -1,6 +1,5 @@ import type { Logger } from "../tracing/logger"; -import { createPromise } from "../utils/create-promise"; -import { SyncResetError } from "./sync-reset-error"; +import { SyncResetError } from "../errors/sync-reset-error"; /** * Offers a resettable fetch implementation that waits until syncing is enabled @@ -13,37 +12,43 @@ export class FetchController { // Promise resolves on the next state change: sync enabled/disabled or reset started/ended private until: Promise; - private resolveUntil: (result: symbol) => unknown; - private rejectUntil: (reason: unknown) => unknown; + private resolveUntil: (value: symbol | PromiseLike) => void; + private rejectUntil: (reason?: unknown) => void; public constructor( private _canFetch: boolean, private readonly logger: Logger ) { - [this.until, this.resolveUntil, this.rejectUntil] = - createPromise(); + ({ + promise: this.until, + resolve: this.resolveUntil, + reject: this.rejectUntil + } = Promise.withResolvers()); } /** - * Whether the fetch implementation can immediately send requests once outside of a reset. - */ + * Whether the fetch implementation can immediately send requests once outside of a reset. + */ public get canFetch(): boolean { return this._canFetch; } /** - * Allow or disallow fetching. The changes only take effect if not resetting. - * When called during a reset, its effect is deferred until the reset is finished. - * - * @param canFetch Whether fetching is enabled - */ + * Allow or disallow fetching. The changes only take effect if not resetting. + * When called during a reset, its effect is deferred until the reset is finished. + * + * @param canFetch Whether fetching is enabled + */ public set canFetch(canFetch: boolean) { this._canFetch = canFetch; if (!this.isResetting) { const previousResolve = this.resolveUntil; - [this.until, this.resolveUntil, this.rejectUntil] = - createPromise(); + ({ + promise: this.until, + resolve: this.resolveUntil, + reject: this.rejectUntil + } = Promise.withResolvers()); previousResolve(FetchController.UNTIL_RESOLUTION); } } @@ -59,9 +64,9 @@ export class FetchController { } /** - * Starts a reset, causing all ongoing and future fetches to be rejected - * with a SyncResetError until finishReset is called. - */ + * Starts a reset, causing all ongoing and future fetches to be rejected + * with a SyncResetError until finishReset is called. + */ public startReset(): void { this.isResetting = true; this.rejectUntil(new SyncResetError()); @@ -72,32 +77,36 @@ export class FetchController { } /** - * Finishes a reset, allowing fetches to proceed or wait again depending on - * the current sync settings. - */ + * Finishes a reset, allowing fetches to proceed or wait again depending on + * the current sync settings. + */ public finishReset(): void { if (!this.isResetting) { return; } this.isResetting = false; - [this.until, this.resolveUntil, this.rejectUntil] = createPromise(); + ({ + promise: this.until, + resolve: this.resolveUntil, + reject: this.rejectUntil + } = Promise.withResolvers()); } /** - * - * |------------------|---------------|-----------------------------------------------------| - * | | Sync enabled | Sync disabled | - * |------------------|-------------- |-----------------------------------------------------| - * | During reset | Rejects with SyncResetError without sending request | - * |------------------|-------------- |-----------------------------------------------------| - * | Outside of reset | Same as fetch | Blocks until sync is enabled and then same as fetch | - * |------------------|---------------|-----------------------------------------------------| - * - * @param logger for errors - * @param fetch to wrap - * @returns a wrapped fetch implementation affected by the FetchController state - */ + * + * |------------------|---------------|-----------------------------------------------------| + * | | Sync enabled | Sync disabled | + * |------------------|-------------- |-----------------------------------------------------| + * | During reset | Rejects with SyncResetError without sending request | + * |------------------|-------------- |-----------------------------------------------------| + * | Outside of reset | Same as fetch | Blocks until sync is enabled and then same as fetch | + * |------------------|---------------|-----------------------------------------------------| + * + * @param logger for errors + * @param fetch to wrap + * @returns a wrapped fetch implementation affected by the FetchController state + */ public getControlledFetchImplementation( logger: Logger, fetch: typeof globalThis.fetch = globalThis.fetch diff --git a/frontend/sync-client/src/services/server-config.ts b/frontend/sync-client/src/services/server-config.ts index 309c637c..187e1bff 100644 --- a/frontend/sync-client/src/services/server-config.ts +++ b/frontend/sync-client/src/services/server-config.ts @@ -1,6 +1,7 @@ import { SUPPORTED_API_VERSION } from "../consts"; -import { AuthenticationError } from "./authentication-error"; -import { ServerVersionMismatchError } from "./server-version-mismatch-error"; +import { AuthenticationError } from "../errors/authentication-error"; +import { ServerVersionMismatchError } from "../errors/server-version-mismatch-error"; +import type { Settings } from "../persistence/settings"; import type { SyncService } from "./sync-service"; import type { PingResponse } from "./types/PingResponse"; @@ -14,7 +15,20 @@ export class ServerConfig { private response: Promise | undefined; private config: ServerConfigData | undefined; - public constructor(private readonly syncService: SyncService) {} + public constructor( + private readonly syncService: SyncService, + settings: Settings + ) { + settings.onSettingsChanged.add((newSettings, oldSettings) => { + if ( + newSettings.token !== oldSettings.token || + newSettings.vaultName !== oldSettings.vaultName || + newSettings.remoteUri !== oldSettings.remoteUri + ) { + this.reset(); + } + }); + } private static validateConfig(config: ServerConfigData): void { if (config.supportedApiVersion !== SUPPORTED_API_VERSION) { @@ -34,11 +48,6 @@ export class ServerConfig { } } - // warm the cache - public async initialize(): Promise { - await this.getConfig(); - } - public async checkConnection(forceUpdate = false): Promise<{ isSuccessful: boolean; message: string; @@ -46,7 +55,7 @@ export class ServerConfig { try { let { response } = this; if (!response || forceUpdate) { - response = this.response = this.syncService.ping(); + response = this.startPing(); } const result: PingResponse = await response; // it must be defined, otherwise we would have thrown above @@ -73,7 +82,7 @@ export class ServerConfig { public async getConfig(): Promise { if (!this.config) { - this.response ??= this.syncService.ping(); + this.response ??= this.startPing(); this.config = await this.response; } @@ -86,4 +95,15 @@ export class ServerConfig { this.response = undefined; this.config = undefined; } + + private async startPing(): Promise { + const pending = this.syncService.ping().catch((e: unknown) => { + if (this.response === pending) { + this.response = undefined; + } + throw e; + }); + this.response = pending; + return pending; + } } diff --git a/frontend/sync-client/src/services/sync-service.ts b/frontend/sync-client/src/services/sync-service.ts index 8190a638..0a99fe84 100644 --- a/frontend/sync-client/src/services/sync-service.ts +++ b/frontend/sync-client/src/services/sync-service.ts @@ -2,25 +2,27 @@ import type { DocumentId, RelativePath, VaultUpdateId -} from "../persistence/database"; +} from "../sync-operations/types"; import type { Logger } from "../tracing/logger"; import type { Settings } from "../persistence/settings"; import type { FetchController } from "./fetch-controller"; import { sleep } from "../utils/sleep"; -import { SyncResetError } from "./sync-reset-error"; +import { SyncResetError } from "../errors/sync-reset-error"; +import { HttpClientError } from "../errors/http-client-error"; import type { SerializedError } from "./types/SerializedError"; import type { DocumentVersionWithoutContent } from "./types/DocumentVersionWithoutContent"; import type { DocumentUpdateResponse } from "./types/DocumentUpdateResponse"; import type { DocumentVersion } from "./types/DocumentVersion"; import type { FetchLatestDocumentsResponse } from "./types/FetchLatestDocumentsResponse"; import type { PingResponse } from "./types/PingResponse"; -import type { DeleteDocumentVersion } from "./types/DeleteDocumentVersion"; import type { UpdateTextDocumentVersion } from "./types/UpdateTextDocumentVersion"; +import { buildVaultUrl } from "./build-vault-url"; export class SyncService { private readonly client: typeof globalThis.fetch; private readonly pingClient: typeof globalThis.fetch; + private isStopped = false; public constructor( private readonly deviceId: string, @@ -65,28 +67,68 @@ export class SyncService { return result; } + private static async throwIfNotOk( + response: Response, + operation: string + ): Promise { + if (response.ok) { + return; + } + const message = `Failed to ${operation}: ${await SyncService.errorFromResponse(response)}`; + // 429 is the only 4xx the server uses for *transient* contention + // (`WriteBusyError` → HTTP 429). Every other 4xx means the request + // is permanently rejected and shouldn't be retried. + if (response.status === 429) { + throw new Error(message); + } + if (response.status >= 400 && response.status < 500) { + throw new HttpClientError(response.status, message); + } + throw new Error(message); + } + + /** + * Signal that the service is shutting down so any in-flight + * `retryForever` exits at its next iteration instead of looping + * indefinitely after the rest of the client has stopped. Idempotent. + */ + public stop(): void { + this.isStopped = true; + } + + /** + * Re-enable the service after a `stop()`. Used when the client pauses + * and resumes syncing within the same lifecycle (e.g. user toggles + * sync off and on). + */ + public resume(): void { + this.isStopped = false; + } + public async create({ - documentId, relativePath, + lastSeenVaultUpdateId, contentBytes }: { - documentId?: DocumentId; relativePath: RelativePath; + lastSeenVaultUpdateId: VaultUpdateId; contentBytes: Uint8Array; - }): Promise { + }): Promise { return this.retryForever(async () => { const formData = new FormData(); - if (documentId !== undefined) { - formData.append("document_id", documentId); - } + formData.append("relative_path", relativePath); + formData.append( + "last_seen_vault_update_id", + lastSeenVaultUpdateId.toString() + ); formData.append( "content", new Blob([new Uint8Array(contentBytes)]) ); this.logger.debug( - `Creating document with id ${documentId} and relative path ${relativePath}` + `Creating document with relative path ${relativePath}` ); const response = await this.client(this.getUrl("/documents"), { @@ -95,16 +137,10 @@ export class SyncService { headers: this.getDefaultHeaders() }); - if (!response.ok) { - throw new Error( - `Failed to create document: ${await SyncService.errorFromResponse( - response - )}` - ); - } + await SyncService.throwIfNotOk(response, "create document"); - const result: DocumentVersionWithoutContent = - (await response.json()) as DocumentVersionWithoutContent; // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion + const result: DocumentUpdateResponse = + (await response.json()) as DocumentUpdateResponse; // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion this.logger.debug(`Created document ${JSON.stringify(result)}`); @@ -120,17 +156,17 @@ export class SyncService { }: { parentVersionId: VaultUpdateId; documentId: DocumentId; - relativePath: RelativePath; + relativePath: RelativePath | undefined; content: (number | string)[]; }): Promise { return this.retryForever(async () => { this.logger.debug( - `Updating text document ${documentId} with parent version ${parentVersionId} and relative path ${relativePath}, content [${content.join(", ")}]` + `Updating text document ${documentId} with parent version ${parentVersionId} and relative path ${relativePath ?? ""}, content [${content.join(", ")}]` ); const request: UpdateTextDocumentVersion = { parentVersionId, - relativePath, + relativePath: relativePath ?? null, content }; @@ -143,13 +179,7 @@ export class SyncService { } ); - if (!response.ok) { - throw new Error( - `Failed to update document: ${await SyncService.errorFromResponse( - response - )}` - ); - } + await SyncService.throwIfNotOk(response, "update document"); const result: DocumentUpdateResponse = (await response.json()) as DocumentUpdateResponse; // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion @@ -172,16 +202,18 @@ export class SyncService { }: { parentVersionId: VaultUpdateId; documentId: DocumentId; - relativePath: RelativePath; + relativePath: RelativePath | undefined; contentBytes: Uint8Array; }): Promise { return this.retryForever(async () => { this.logger.debug( - `Updating binary document ${documentId} with parent version ${parentVersionId} and relative path ${relativePath}` + `Updating binary document ${documentId} with parent version ${parentVersionId} and relative path ${relativePath ?? ""}` ); const formData = new FormData(); formData.append("parent_version_id", parentVersionId.toString()); - formData.append("relative_path", relativePath); + if (relativePath !== undefined) { + formData.append("relative_path", relativePath); + } formData.append( "content", new Blob([new Uint8Array(contentBytes)]) @@ -196,13 +228,7 @@ export class SyncService { } ); - if (!response.ok) { - throw new Error( - `Failed to update document: ${await SyncService.errorFromResponse( - response - )}` - ); - } + await SyncService.throwIfNotOk(response, "update document"); const result: DocumentUpdateResponse = (await response.json()) as DocumentUpdateResponse; // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion @@ -218,44 +244,29 @@ export class SyncService { } public async delete({ - documentId, - relativePath + documentId }: { documentId: DocumentId; - relativePath: RelativePath; }): Promise { return this.retryForever(async () => { - const request: DeleteDocumentVersion = { - relativePath - }; - - this.logger.debug( - `Delete document with id ${documentId} and relative path ${relativePath}` - ); + this.logger.debug(`Delete document with id ${documentId}`); + // The server identifies the document by its URL path; no body + // is needed. Sending one was a leftover of an earlier shape. const response = await this.client( this.getUrl(`/documents/${documentId}`), { method: "DELETE", - body: JSON.stringify(request), - headers: this.getDefaultHeaders({ type: "json" }) + headers: this.getDefaultHeaders() } ); - if (!response.ok) { - throw new Error( - `Failed to delete document: ${await SyncService.errorFromResponse( - response - )}` - ); - } + await SyncService.throwIfNotOk(response, "delete document"); const result: DocumentVersionWithoutContent = (await response.json()) as DocumentVersionWithoutContent; // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion - this.logger.debug( - `Deleted document ${relativePath} with id ${documentId}` - ); + this.logger.debug(`Deleted document with id ${documentId}`); return result; }); @@ -276,13 +287,7 @@ export class SyncService { } ); - if (!response.ok) { - throw new Error( - `Failed to get document: ${await SyncService.errorFromResponse( - response - )}` - ); - } + await SyncService.throwIfNotOk(response, "get document"); const result: DocumentVersion = (await response.json()) as DocumentVersion; // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion @@ -314,13 +319,10 @@ export class SyncService { } ); - if (!response.ok) { - throw new Error( - `Failed to get document: ${await SyncService.errorFromResponse( - response - )}` - ); - } + await SyncService.throwIfNotOk( + response, + "get document version content" + ); const result = await response.bytes(); this.logger.debug( @@ -341,19 +343,13 @@ export class SyncService { const url = new URL(this.getUrl("/documents")); if (since !== undefined) { - url.searchParams.append("since", since.toString()); + url.searchParams.append("since_update_id", since.toString()); } const response = await this.client(url.toString(), { headers: this.getDefaultHeaders() }); - if (!response.ok) { - throw new Error( - `Failed to get documents: ${await SyncService.errorFromResponse( - response - )}` - ); - } + await SyncService.throwIfNotOk(response, "get documents"); const result: FetchLatestDocumentsResponse = (await response.json()) as FetchLatestDocumentsResponse; // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion @@ -390,10 +386,7 @@ export class SyncService { } private getUrl(path: string): string { - const { vaultName, remoteUri } = this.settings.getSettings(); - const remoteUriWithoutTrailingSlash = remoteUri.replace(/\/+$/, ""); - const encodedVaultName = encodeURIComponent(vaultName.trim()); - return `${remoteUriWithoutTrailingSlash}/vaults/${encodedVaultName}${path}`; + return buildVaultUrl(this.settings, path); } private getDefaultHeaders( @@ -414,13 +407,17 @@ export class SyncService { private async retryForever(fn: () => Promise): Promise { // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (true) { + this.throwIfStopped(); try { return await fn(); } catch (e) { - // We must not retry errors coming from reset - if (e instanceof SyncResetError) { + if ( + e instanceof SyncResetError || + e instanceof HttpClientError + ) { throw e; } + this.throwIfStopped(); const retryInterval = this.settings.getSettings().networkRetryIntervalMs; @@ -431,4 +428,10 @@ export class SyncService { } } } + + private throwIfStopped(): void { + if (this.isStopped) { + throw new SyncResetError(); + } + } } diff --git a/frontend/sync-client/src/services/websocket-manager.test.ts b/frontend/sync-client/src/services/websocket-manager.test.ts index fef901e7..bde18ef3 100644 --- a/frontend/sync-client/src/services/websocket-manager.test.ts +++ b/frontend/sync-client/src/services/websocket-manager.test.ts @@ -4,8 +4,7 @@ import assert from "node:assert"; import { WebSocketManager } from "./websocket-manager"; import type { Logger } from "../tracing/logger"; import type { Settings } from "../persistence/settings"; -// eslint-disable-next-line @typescript-eslint/no-require-imports -const WebSocket = require("ws") as typeof globalThis.WebSocket; +import { awaitAll } from "../utils/await-all"; class MockCloseEvent extends Event { public code: number; @@ -91,10 +90,8 @@ function createMockFn unknown>( describe("WebSocketManager", () => { let mockLogger: Logger = undefined as unknown as Logger; let mockSettings: Settings = undefined as unknown as Settings; - let deviceId = "test-device-123"; beforeEach(() => { - deviceId = "test-device-123"; const noop = (): void => { // Intentionally empty for mock }; @@ -116,7 +113,6 @@ describe("WebSocketManager", () => { it("cleans up promises after message handling", async () => { const manager = new WebSocketManager( - deviceId, mockLogger, mockSettings, MockWebSocket as unknown as typeof WebSocket @@ -146,7 +142,6 @@ describe("WebSocketManager", () => { it("cleans up cursor position promises", async () => { const manager = new WebSocketManager( - deviceId, mockLogger, mockSettings, MockWebSocket as unknown as typeof WebSocket @@ -176,7 +171,6 @@ describe("WebSocketManager", () => { it("logs handshake send errors", async () => { const manager = new WebSocketManager( - deviceId, mockLogger, mockSettings, MockWebSocket as unknown as typeof WebSocket @@ -205,7 +199,6 @@ describe("WebSocketManager", () => { it("completes stop with timeout protection", async () => { const manager = new WebSocketManager( - deviceId, mockLogger, mockSettings, MockWebSocket as unknown as typeof WebSocket @@ -220,7 +213,6 @@ describe("WebSocketManager", () => { it("clears old handlers on reconnection", async () => { const manager = new WebSocketManager( - deviceId, mockLogger, mockSettings, MockWebSocket as unknown as typeof WebSocket @@ -255,9 +247,68 @@ describe("WebSocketManager", () => { await manager.stop(); }); + it("handles concurrent stop() calls without stranding either caller", async () => { + // Real WebSocket.close() doesn't fire onclose synchronously, and the + // socket stays reachable across the close handshake. Model that + // here so the manager's `while (isWebSocketConnected)` loop is + // actually awaiting when the second stop() races in. Static OPEN + // is required because the manager compares readyState against + // `factory.OPEN`. + class AsyncCloseWebSocket extends MockWebSocket { + public static readonly OPEN = WebSocket.OPEN; + + public override close(code?: number, reason?: string): void { + if ( + this.readyState === WebSocket.CLOSED || + (this as { _closing?: boolean })._closing === true + ) { + return; + } + (this as { _closing?: boolean })._closing = true; + setTimeout(() => { + this.readyState = WebSocket.CLOSED; + this.onclose?.( + new MockCloseEvent("close", { + code: code ?? 1000, + reason: reason ?? "" + }) + ); + }, 5); + } + } + + const manager = new WebSocketManager( + mockLogger, + mockSettings, + AsyncCloseWebSocket as unknown as typeof WebSocket + ); + + manager.start(); + await new Promise((resolve) => setTimeout(resolve, 50)); + + const start = Date.now(); + // Two concurrent stops mimic destroy() racing onSettingsChange. + await awaitAll([manager.stop(), manager.stop()]); + const elapsed = Date.now() - start; + + // Both should resolve via the normal close path; if the second call + // had clobbered the first's resolver, the first would have been + // stranded until the 10s disconnect timeout. + assert.ok( + elapsed < 1000, + `concurrent stop() took ${elapsed}ms — expected fast resolution` + ); + const errorCalls = (mockLogger.error as unknown as { calls: unknown[] }) + .calls; + assert.strictEqual( + errorCalls.length, + 0, + "no timeout-recovery error should be logged" + ); + }); + it("tracks message handling promises", async () => { const manager = new WebSocketManager( - deviceId, mockLogger, mockSettings, MockWebSocket as unknown as typeof WebSocket diff --git a/frontend/sync-client/src/services/websocket-manager.ts b/frontend/sync-client/src/services/websocket-manager.ts index 09787bce..8a4fe34c 100644 --- a/frontend/sync-client/src/services/websocket-manager.ts +++ b/frontend/sync-client/src/services/websocket-manager.ts @@ -4,12 +4,15 @@ import type { WebSocketServerMessage } from "./types/WebSocketServerMessage"; import type { WebSocketClientMessage } from "./types/WebSocketClientMessage"; import type { CursorPositionFromClient } from "./types/CursorPositionFromClient"; import type { ClientCursors } from "./types/ClientCursors"; -import { createPromise } from "../utils/create-promise"; import type { WebSocketVaultUpdate } from "./types/WebSocketVaultUpdate"; -import { WEBSOCKET_DISCONNECT_TIMEOUT_IN_S } from "../consts"; +import { + WEBSOCKET_DISCONNECT_TIMEOUT_IN_SECONDS, + WEBSOCKET_CONNECTION_TIMEOUT_IN_SECONDS +} from "../consts"; import { removeFromArray } from "../utils/remove-from-array"; import { EventListeners } from "../utils/data-structures/event-listeners"; import { awaitAll } from "../utils/await-all"; +import { buildVaultUrl } from "./build-vault-url"; export class WebSocketManager { public readonly onWebSocketStatusChanged = new EventListeners< @@ -26,32 +29,22 @@ export class WebSocketManager { private isStopped = true; private resolveDisconnectingPromise: null | (() => unknown) = null; + private stopPromise: Promise | null = null; private reconnectTimeoutId: ReturnType | undefined; + private connectionTimeoutId: ReturnType | undefined; private readonly outstandingPromises: Promise[] = []; private webSocket: WebSocket | undefined; - private readonly webSocketFactoryImplementation: typeof globalThis.WebSocket; public constructor( - private readonly deviceId: string, private readonly logger: Logger, private readonly settings: Settings, - webSocketImplementation?: typeof globalThis.WebSocket - ) { - if (webSocketImplementation) { - this.webSocketFactoryImplementation = webSocketImplementation; - } else { - if ( - typeof globalThis !== "undefined" && - typeof globalThis.WebSocket === "undefined" - ) { - // eslint-disable-next-line - this.webSocketFactoryImplementation = require("ws"); // polyfill for WebSocket in Node.js - } else { - this.webSocketFactoryImplementation = WebSocket; - } - } + private readonly webSocketFactoryImplementation: typeof globalThis.WebSocket = WebSocket + ) {} + + public get hasOutstandingWork(): boolean { + return this.outstandingPromises.length > 0; } public get isWebSocketConnected(): boolean { @@ -67,49 +60,14 @@ export class WebSocketManager { } public async stop(): Promise { - const [promise, resolve] = createPromise(); - this.resolveDisconnectingPromise = resolve; - - this.isStopped = true; - - if (this.reconnectTimeoutId !== undefined) { - clearTimeout(this.reconnectTimeoutId); - this.reconnectTimeoutId = undefined; - } - - this.webSocket?.close(1000, "WebSocketManager has been stopped"); - - // eslint-disable-next-line @typescript-eslint/init-declarations - let timeoutId: ReturnType | undefined; - const timeoutPromise = new Promise((_, reject) => { - timeoutId = setTimeout(() => { - reject( - new Error( - `Timeout waiting for WebSocket to close after ${WEBSOCKET_DISCONNECT_TIMEOUT_IN_S} seconds` - ) - ); - }, WEBSOCKET_DISCONNECT_TIMEOUT_IN_S * 1000); + // Concurrent callers (e.g. destroy() and onSettingsChange) must share + // the same disconnect; otherwise the second call would overwrite + // resolveDisconnectingPromise and strand the first caller's await + // until the timeout rejects. + this.stopPromise ??= this.performStop().finally(() => { + this.stopPromise = null; }); - - try { - while (this.isWebSocketConnected) { - await Promise.race([promise, timeoutPromise]); - } - } catch (error) { - this.logger.error( - `Error while waiting for WebSocket to close: ${String(error)}` - ); - // Force cleanup even if close didn't work - this.resolveDisconnectingPromise(); - this.resolveDisconnectingPromise = null; - } finally { - // Clear timeout to prevent unhandled rejection - if (timeoutId !== undefined) { - clearTimeout(timeoutId); - } - } - - await this.waitUntilFinished(); + await this.stopPromise; } public async waitUntilFinished(): Promise { @@ -162,6 +120,59 @@ export class WebSocketManager { } } + private async performStop(): Promise { + const { promise, resolve } = Promise.withResolvers(); + this.resolveDisconnectingPromise = (): void => { + resolve(undefined); + }; + + this.isStopped = true; + + if (this.reconnectTimeoutId !== undefined) { + clearTimeout(this.reconnectTimeoutId); + this.reconnectTimeoutId = undefined; + } + + if (this.connectionTimeoutId !== undefined) { + clearTimeout(this.connectionTimeoutId); + this.connectionTimeoutId = undefined; + } + + this.webSocket?.close(1000, "WebSocketManager has been stopped"); + + // eslint-disable-next-line @typescript-eslint/init-declarations + let timeoutId: ReturnType | undefined; + const timeoutPromise = new Promise((_, reject) => { + timeoutId = setTimeout(() => { + reject( + new Error( + `Timeout waiting for WebSocket to close after ${WEBSOCKET_DISCONNECT_TIMEOUT_IN_SECONDS} seconds` + ) + ); + }, WEBSOCKET_DISCONNECT_TIMEOUT_IN_SECONDS * 1000); + }); + + try { + while (this.isWebSocketConnected) { + await Promise.race([promise, timeoutPromise]); + } + } catch (error) { + this.logger.error( + `Error while waiting for WebSocket to close: ${String(error)}` + ); + // Force cleanup even if close didn't work + this.resolveDisconnectingPromise(); + this.resolveDisconnectingPromise = null; + } finally { + // Clear timeout to prevent unhandled rejection + if (timeoutId !== undefined) { + clearTimeout(timeoutId); + } + } + + await this.waitUntilFinished(); + } + private initializeWebSocket(): void { // Clean up old WebSocket handlers to prevent race conditions if (this.webSocket) { @@ -171,26 +182,55 @@ export class WebSocketManager { this.webSocket.onclose = null; this.webSocket.onmessage = null; this.webSocket.onerror = null; - this.webSocket.close(); + this.webSocket.close( + 1000, + "Closing previous WebSocket connection" + ); } catch (e) { this.logger.error( `Failed to close previous WebSocket connection: ${e}` ); } + // Abandon any outstanding handler promises from the previous + // connection. They'll still resolve in the background, but we + // no longer want `waitUntilFinished` / `stop` to block on + // post-reconnect state — and we definitely don't want their + // results applied against a now-stale socket. + this.outstandingPromises.length = 0; } - const wsUri = new URL(this.settings.getSettings().remoteUri); - wsUri.protocol = wsUri.protocol === "https" ? "wss" : "ws"; - wsUri.pathname = `/vaults/${this.settings.getSettings().vaultName}/ws`; + // Build the WS URL through the same vault-URL helper the HTTP client + // uses so vault-name encoding, trailing-slash stripping, and any path + // prefix in `remoteUri` stay in sync between transports. + const wsUri = new URL(buildVaultUrl(this.settings, "/ws")); + wsUri.protocol = wsUri.protocol.startsWith("https") ? "wss" : "ws"; this.logger.info(`Connecting to WebSocket at ${wsUri.toString()}`); - this.webSocket = new this.webSocketFactoryImplementation(wsUri); + const ws = new this.webSocketFactoryImplementation(wsUri); + this.webSocket = ws; + + // Set connection timeout to handle cases where server is down and the WebSocket connection won't open. + // The callback closes the *captured* `ws` rather than `this.webSocket` so a delayed timeout cannot + // accidentally close a freshly-constructed replacement socket. (Closing the already-closed `ws` is a no-op.) + this.connectionTimeoutId = setTimeout(() => { + this.connectionTimeoutId = undefined; + this.logger.warn( + `WebSocket connection timeout after ${WEBSOCKET_CONNECTION_TIMEOUT_IN_SECONDS} seconds` + ); + // Force close to trigger onclose handler which will schedule reconnection + ws.close(1000, "Connection timeout"); + }, WEBSOCKET_CONNECTION_TIMEOUT_IN_SECONDS * 1000); + + ws.onopen = (): void => { + if (this.connectionTimeoutId !== undefined) { + clearTimeout(this.connectionTimeoutId); + this.connectionTimeoutId = undefined; + } - this.webSocket.onopen = (): void => { // Check if we've been stopped while connecting if (this.isStopped) { - this.webSocket?.close( + ws.close( 1000, "WebSocketManager was stopped during connection" ); @@ -200,7 +240,7 @@ export class WebSocketManager { this.onWebSocketStatusChanged.trigger(true); }; - this.webSocket.onmessage = (event): void => { + ws.onmessage = (event): void => { try { // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion const message = JSON.parse( @@ -231,7 +271,18 @@ export class WebSocketManager { } }; - this.webSocket.onclose = (event): void => { + ws.onerror = (error): void => { + this.logger.warn( + `WebSocket error occurred: ${error instanceof ErrorEvent ? error.message : "Unknown error"}` + ); + }; + + ws.onclose = (event): void => { + if (this.connectionTimeoutId !== undefined) { + clearTimeout(this.connectionTimeoutId); + this.connectionTimeoutId = undefined; + } + this.logger.warn( `WebSocket closed with code ${event.code} (${event.reason == "" ? "unknown reason" : event.reason})` ); @@ -241,10 +292,13 @@ export class WebSocketManager { this.resolveDisconnectingPromise?.(); this.resolveDisconnectingPromise = null; } else { + const delay = + this.settings.getSettings().webSocketRetryIntervalMs; + this.logger.info(`Reconnecting to WebSocket in ${delay}ms...`); this.reconnectTimeoutId = setTimeout(() => { this.reconnectTimeoutId = undefined; this.initializeWebSocket(); - }, this.settings.getSettings().webSocketRetryIntervalMs); + }, delay); } }; } @@ -252,22 +306,22 @@ export class WebSocketManager { private async handleWebSocketMessage( message: WebSocketServerMessage ): Promise { - if (message.type === "vaultUpdate") { - await this.onRemoteVaultUpdateReceived.triggerAsync(message); - - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - } else if (message.type === "cursorPositions") { - this.logger.debug( - `Received cursor positions for ${JSON.stringify(message.clients)}` - ); - - await this.onRemoteCursorsUpdateReceived.triggerAsync( - message.clients - ); - } else { - this.logger.warn( - `Received unknown message type: ${JSON.stringify(message)}` - ); + switch (message.type) { + case "vaultUpdate": + await this.onRemoteVaultUpdateReceived.triggerAsync(message); + return; + case "cursorPositions": + this.logger.debug( + `Received cursor positions for ${JSON.stringify(message.clients)}` + ); + await this.onRemoteCursorsUpdateReceived.triggerAsync( + message.clients + ); + return; + default: + this.logger.warn( + `Received unknown message type: ${JSON.stringify(message)}` + ); } } } From 0fda95ff8efcaf3bccf27414b50b969bdd7721e0 Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Fri, 8 May 2026 21:36:54 +0100 Subject: [PATCH 09/17] split: sync-client file-operations + persistence Rewrite file-operations and safe-filesystem-operations (and their tests), update filesystem-operations. Drop persistence/database.ts (in-memory record store moved into sync-event-queue). Update persistence/settings.ts. --- .../file-operations/file-operations.test.ts | 232 ++++------- .../src/file-operations/file-operations.ts | 290 +++++++------- .../file-operations/filesystem-operations.ts | 2 +- .../safe-filesystem-operations.ts | 92 +---- .../sync-client/src/persistence/database.ts | 374 ------------------ .../sync-client/src/persistence/settings.ts | 10 +- 6 files changed, 251 insertions(+), 749 deletions(-) delete mode 100644 frontend/sync-client/src/persistence/database.ts diff --git a/frontend/sync-client/src/file-operations/file-operations.test.ts b/frontend/sync-client/src/file-operations/file-operations.test.ts index 998e47ec..7916ab57 100644 --- a/frontend/sync-client/src/file-operations/file-operations.test.ts +++ b/frontend/sync-client/src/file-operations/file-operations.test.ts @@ -1,15 +1,14 @@ import { describe, it } from "node:test"; -import type { - Database, - DocumentRecord, - RelativePath -} from "../persistence/database"; +import assert from "node:assert/strict"; +import type { RelativePath } from "../sync-operations/types"; import { FileOperations } from "./file-operations"; import { Logger } from "../tracing/logger"; import { assertSetContainsExactly } from "../utils/assert-set-contains-exactly"; import type { FileSystemOperations } from "./filesystem-operations"; import type { TextWithCursors } from "reconcile-text"; import type { ServerConfig, ServerConfigData } from "../services/server-config"; +import { ExpectedFsEvents } from "../sync-operations/expected-fs-events"; +import { FileAlreadyExistsError } from "../errors/file-already-exists-error"; class MockServerConfig implements Pick { public async getConfig(): Promise { @@ -21,29 +20,13 @@ class MockServerConfig implements Pick { } } -class MockDatabase implements Partial { - public getLatestDocumentByRelativePath( - _find: RelativePath - ): DocumentRecord | undefined { - // no-op - return undefined; - } - - public move( - _oldRelativePath: RelativePath, - _newRelativePath: RelativePath - ): void { - // no-op - } -} - class FakeFileSystemOperations implements FileSystemOperations { public readonly names = new Set(); public async listFilesRecursively( _root: RelativePath | undefined ): Promise { - return ["file.md"]; + return Array.from(this.names); } public async read(_path: RelativePath): Promise { throw new Error("Method not implemented."); @@ -63,17 +46,14 @@ class FakeFileSystemOperations implements FileSystemOperations { public async getFileSize(_path: RelativePath): Promise { throw new Error("Method not implemented."); } - public async getModificationTime(_path: RelativePath): Promise { - throw new Error("Method not implemented."); - } public async exists(path: RelativePath): Promise { return this.names.has(path); } public async createDirectory(_path: RelativePath): Promise { - // this is called but irrelevant for this mock + // no-op for the in-memory fake; we only track files } - public async delete(_path: RelativePath): Promise { - throw new Error("Method not implemented."); + public async delete(path: RelativePath): Promise { + this.names.delete(path); } public async rename( oldPath: RelativePath, @@ -84,152 +64,92 @@ class FakeFileSystemOperations implements FileSystemOperations { } } +function makeOps(): { + fs: FakeFileSystemOperations; + ops: FileOperations; +} { + const fs = new FakeFileSystemOperations(); + const ops = new FileOperations( + new Logger(), + fs, + new MockServerConfig() as ServerConfig, // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion + new ExpectedFsEvents() + ); + return { fs, ops }; +} + describe("File operations", () => { - it("should deconflict renames", async () => { - const fileSystemOperations = new FakeFileSystemOperations(); - const fileOperations = new FileOperations( - new Logger(), - new MockDatabase() as Database, // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion - fileSystemOperations, - new MockServerConfig() as ServerConfig // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion - ); + it("create writes the file at the requested path", async () => { + const { fs, ops } = makeOps(); - await fileOperations.create("a", new Uint8Array()); - assertSetContainsExactly(fileSystemOperations.names, "a"); - await fileOperations.move("a", "b"); - assertSetContainsExactly(fileSystemOperations.names, "b"); + const result = await ops.create("a", new Uint8Array()); - await fileOperations.create("c", new Uint8Array()); - assertSetContainsExactly(fileSystemOperations.names, "b", "c"); - - await fileOperations.move("c", "b"); - assertSetContainsExactly(fileSystemOperations.names, "b", "b (1)"); - - await fileOperations.create("c", new Uint8Array()); - await fileOperations.move("c", "b"); - assertSetContainsExactly( - fileSystemOperations.names, - "b", - "b (1)", - "b (2)" - ); + assertSetContainsExactly(fs.names, "a"); + assert.equal(result.actualPath, "a"); }); - it("should deconflict renames with file extension", async () => { - const fileSystemOperations = new FakeFileSystemOperations(); - const fileOperations = new FileOperations( - new Logger(), - new MockDatabase() as Database, // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion - fileSystemOperations, - new MockServerConfig() as ServerConfig // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion + it("create throws FileAlreadyExistsError when the path is occupied", async () => { + const { fs, ops } = makeOps(); + + await ops.create("note.md", new Uint8Array()); + await assert.rejects( + ops.create("note.md", new Uint8Array()), + FileAlreadyExistsError ); - await fileOperations.create("b.md", new Uint8Array()); - await fileOperations.create("c.md", new Uint8Array()); - await fileOperations.move("c.md", "b.md"); - assertSetContainsExactly( - fileSystemOperations.names, - "b.md", - "b (1).md" - ); - - await fileOperations.create("d.md", new Uint8Array()); - await fileOperations.move("d.md", "b.md"); - assertSetContainsExactly( - fileSystemOperations.names, - "b.md", - "b (1).md", - "b (2).md" - ); - - await fileOperations.create("file-23.md", new Uint8Array()); - await fileOperations.create("file-23 (1).md", new Uint8Array()); - await fileOperations.move("file-23.md", "file-23 (1).md"); - assertSetContainsExactly( - fileSystemOperations.names, - "b.md", - "b (1).md", - "b (2).md", - "file-23 (1).md", - "file-23 (2).md" - ); + // The original file is left intact and no other entries appeared. + assertSetContainsExactly(fs.names, "note.md"); }); - it("should deconflict renames with paths", async () => { - const fileSystemOperations = new FakeFileSystemOperations(); - const fileOperations = new FileOperations( - new Logger(), - new MockDatabase() as Database, // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion - fileSystemOperations, - new MockServerConfig() as ServerConfig // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion - ); + it("move to an empty target just renames the file", async () => { + const { fs, ops } = makeOps(); - await fileOperations.create("a/b.c/d", new Uint8Array()); - await fileOperations.create("a/b.c/e", new Uint8Array()); - await fileOperations.move("a/b.c/d", "a/b.c/e"); - assertSetContainsExactly( - fileSystemOperations.names, - "a/b.c/e", - "a/b.c/e (1)" - ); + await ops.create("a", new Uint8Array()); + assertSetContainsExactly(fs.names, "a"); + + const result = await ops.move("a", "b"); + assertSetContainsExactly(fs.names, "b"); + assert.equal(result.actualPath, "b"); }); - it("should continue deconfliction from existing number in filename", async () => { - const fileSystemOperations = new FakeFileSystemOperations(); - const fileOperations = new FileOperations( - new Logger(), - new MockDatabase() as Database, // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion - fileSystemOperations, - new MockServerConfig() as ServerConfig // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion - ); + it("move with same source and target is a no-op", async () => { + const { fs, ops } = makeOps(); - await fileOperations.create("document (5).md", new Uint8Array()); - await fileOperations.create("other.md", new Uint8Array()); + await ops.create("a", new Uint8Array()); + const result = await ops.move("a", "a"); - await fileOperations.move("other.md", "document (5).md"); - assertSetContainsExactly( - fileSystemOperations.names, - "document (5).md", - "document (6).md" - ); - - await fileOperations.create("another.md", new Uint8Array()); - await fileOperations.move("another.md", "document (5).md"); - assertSetContainsExactly( - fileSystemOperations.names, - "document (5).md", - "document (6).md", - "document (7).md" - ); + assertSetContainsExactly(fs.names, "a"); + assert.equal(result.actualPath, "a"); }); - it("should handle dotfiles correctly", async () => { - const fileSystemOperations = new FakeFileSystemOperations(); - const fileOperations = new FileOperations( - new Logger(), - new MockDatabase() as Database, // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion - fileSystemOperations, - new MockServerConfig() as ServerConfig // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion + it("move throws FileAlreadyExistsError when the target is occupied", async () => { + const { fs, ops } = makeOps(); + + await ops.create("source.md", new Uint8Array()); + await ops.create("dest.md", new Uint8Array()); + + await assert.rejects( + ops.move("source.md", "dest.md"), + FileAlreadyExistsError ); - await fileOperations.create(".gitignore", new Uint8Array()); - await fileOperations.create("temp", new Uint8Array()); - await fileOperations.move("temp", ".gitignore"); - assertSetContainsExactly( - fileSystemOperations.names, - ".gitignore", - ".gitignore (1)" - ); + // Both files are left intact — no displacement happens. + assertSetContainsExactly(fs.names, "source.md", "dest.md"); + }); - await fileOperations.create(".config.json", new Uint8Array()); - await fileOperations.create("temp2", new Uint8Array()); - await fileOperations.move("temp2", ".config.json"); - assertSetContainsExactly( - fileSystemOperations.names, - ".gitignore", - ".gitignore (1)", - ".config.json", - ".config (1).json" - ); + it("create works for nested paths (parent-directory creation)", async () => { + const { fs, ops } = makeOps(); + + await ops.create("a/b.c/d", new Uint8Array()); + assertSetContainsExactly(fs.names, "a/b.c/d"); + }); + + it("move works for nested target paths (parent-directory creation)", async () => { + const { fs, ops } = makeOps(); + + await ops.create("source", new Uint8Array()); + await ops.move("source", "a/b.c/dest"); + + assertSetContainsExactly(fs.names, "a/b.c/dest"); }); }); diff --git a/frontend/sync-client/src/file-operations/file-operations.ts b/frontend/sync-client/src/file-operations/file-operations.ts index 2864bd20..17a2c655 100644 --- a/frontend/sync-client/src/file-operations/file-operations.ts +++ b/frontend/sync-client/src/file-operations/file-operations.ts @@ -1,28 +1,40 @@ import type { Logger } from "../tracing/logger"; import type { FileSystemOperations } from "./filesystem-operations"; -import type { Database, RelativePath } from "../persistence/database"; +import type { RelativePath } from "../sync-operations/types"; import { SafeFileSystemOperations } from "./safe-filesystem-operations"; import type { TextWithCursors } from "reconcile-text"; import { reconcile } from "reconcile-text"; import { isFileTypeMergable } from "../utils/is-file-type-mergable"; import { isBinary } from "../utils/is-binary"; import type { ServerConfig } from "../services/server-config"; +import { FileNotFoundError } from "../errors/file-not-found-error"; +import { FileAlreadyExistsError } from "../errors/file-already-exists-error"; +import type { ExpectedFsEvents } from "../sync-operations/expected-fs-events"; + +/** + * Outcome of a `move`/`create`. `actualPath` is where the file ended up; + * with the conflict-path machinery removed it is always equal to the + * requested path. The shape is preserved so callers don't all need to + * change. + */ +export interface FileOpResult { + actualPath: RelativePath; +} export class FileOperations { - private static readonly PARENTHESES_REGEX = / \((?\d+)\)$/; private readonly fs: SafeFileSystemOperations; public constructor( private readonly logger: Logger, - private readonly database: Database, fs: FileSystemOperations, private readonly serverConfig: ServerConfig, + private readonly expectedFsEvents: ExpectedFsEvents, private readonly nativeLineEndings = "\n" ) { this.fs = new SafeFileSystemOperations(fs, logger); } - private static getParentDirAndFile( + private static getParentDirAndFileName( path: RelativePath ): [RelativePath, RelativePath] { const pathParts = path.split("/"); @@ -45,43 +57,42 @@ export class FileOperations { } /** - * Create a file at the specified path. - * - * If a file with the same name already exists, it is moved before creating the new one. - * Parent directories are created if necessary. - */ + * Create a file at the specified path. + * + * Throws `FileAlreadyExistsError` if a file already lives at `path`. + * Parent directories are created if necessary. The reconciler is the + * only caller that places files now and pre-checks for conflicts; + * the throw guards against a TOCTOU race rather than being a normal + * code path. + */ public async create( path: RelativePath, newContent: Uint8Array - ): Promise { - await this.ensureClearPath(path); - return this.fs.write(path, this.toNativeLineEndings(newContent)); - } - - public async ensureClearPath(path: RelativePath): Promise { + ): Promise { if (await this.fs.exists(path)) { - const deconflictedPath = await this.deconflictPath(path); - try { - this.logger.debug( - `Didn't expect ${path} to exist, deconflicting by moving it to '${deconflictedPath}'` - ); - - this.database.move(path, deconflictedPath); - await this.fs.rename(path, deconflictedPath, true); - } finally { - this.fs.unlock(deconflictedPath); - } - } else { - await this.createParentDirectories(path); + throw new FileAlreadyExistsError( + `Refusing to create '${path}': file already exists`, + path + ); } + await this.createParentDirectories(path); + + this.expectedFsEvents.expectCreate(path); + try { + await this.fs.write(path, this.toNativeLineEndings(newContent)); + } catch (e) { + this.expectedFsEvents.unexpectCreate(path); + throw e; + } + return { actualPath: path }; } /** - * Update the file at the given path. - * - * Performs a 3-way merge before writing if the file's content differs from `expectedContent`. - * Does not recreate the file if it no longer exists, returning an empty array instead. - */ + * Update the file at the given path. + * + * Performs a 3-way merge before writing if the file's content differs from `expectedContent`. + * Does not recreate the file if it no longer exists, returning an empty array instead. + */ public async write( path: RelativePath, expectedContent: Uint8Array, @@ -94,58 +105,96 @@ export class FileOperations { return; } - if ( - !isFileTypeMergable( - path, - (await this.serverConfig.getConfig()).mergeableFileExtensions - ) || - isBinary(expectedContent) || - isBinary(newContent) - ) { - this.logger.debug( - `The expected content is not mergable, so we won't perform a 3-way merge, just overwrite it` - ); - await this.fs.write( - path, - // `newContent` might not be binary so we still have to ensure the line endings are correct - this.toNativeLineEndings(newContent) - ); - return; - } - - const expectedText = new TextDecoder().decode(expectedContent); // this comes from a previous read which must only have \n line endings - const newText = new TextDecoder().decode(newContent); // this comes from the server which stores text with \n line endings - - await this.fs.atomicUpdateText( - path, - ({ text, cursors }: TextWithCursors): TextWithCursors => { + // Single-source the expectation registration: register exactly once + // per call, and unexpect from the catch if the underlying fs op + // throws (FileNotFoundError or otherwise). The previous shape + // registered inside each branch and let the catch swallow + // FileNotFoundError, leaking the expectation into the map. + this.expectedFsEvents.expectUpdate(path); + try { + if ( + !isFileTypeMergable( + path, + (await this.serverConfig.getConfig()) + .mergeableFileExtensions + ) || + isBinary(expectedContent) || + isBinary(newContent) + ) { this.logger.debug( - `Performing a 3-way merge for ${path} with the expected content` + `The expected content is not mergable, so we won't perform a 3-way merge, just overwrite it` ); - - text = text.replaceAll(this.nativeLineEndings, "\n"); - const merged = reconcile( - expectedText, - { text, cursors }, - newText + await this.fs.write( + path, + // `newContent` might not be binary so we still have to ensure the line endings are correct + this.toNativeLineEndings(newContent) ); - - const resultText = merged.text.replaceAll( - "\n", - this.nativeLineEndings - ); - - return { - text: resultText, - cursors: merged.cursors - }; + return; } - ); + + let expectedText = ""; + let newText = ""; + try { + expectedText = new TextDecoder("utf-8", { fatal: true }).decode( + expectedContent + ); // this comes from a previous read which must only have \n line endings + newText = new TextDecoder("utf-8", { fatal: true }).decode( + newContent + ); // this comes from the server which stores text with \n line endings + } catch (decodeError) { + this.logger.warn( + `3-way merge aborted for ${path}: one of expected/new is not valid UTF-8 (${decodeError}); falling back to overwrite` + ); + await this.fs.write(path, this.toNativeLineEndings(newContent)); + return; + } + + await this.fs.atomicUpdateText( + path, + ({ text, cursors }: TextWithCursors): TextWithCursors => { + this.logger.debug( + `Performing a 3-way merge for ${path} with the expected content` + ); + + text = text.replaceAll(this.nativeLineEndings, "\n"); + const merged = reconcile( + expectedText, + { text, cursors }, + newText + ); + + const resultText = merged.text.replaceAll( + "\n", + this.nativeLineEndings + ); + + return { + text: resultText, + cursors: merged.cursors + }; + } + ); + } catch (e) { + this.expectedFsEvents.unexpectUpdate(path); + if (e instanceof FileNotFoundError) { + this.logger.debug( + `File ${path} disappeared during write; not recreating` + ); + return; + } + throw e; + } } public async delete(path: RelativePath): Promise { if (await this.exists(path)) { - await this.fs.delete(path); + this.expectedFsEvents.expectDelete(path); + try { + await this.fs.delete(path); + } catch (e) { + this.expectedFsEvents.unexpectDelete(path); + throw e; + } await this.deletingEmptyParentDirectoriesOfDeletedFile(path); } else { this.logger.debug(`No need to delete '${path}', it doesn't exist`); @@ -160,23 +209,39 @@ export class FileOperations { return this.fs.exists(path); } + /** + * Move the file at `oldPath` to `newPath`. + * + * Throws `FileAlreadyExistsError` if a file already lives at `newPath` + * (and `oldPath !== newPath`). The reconciler is the only caller that + * relocates tracked records and pre-checks for conflicts; the throw + * guards against a TOCTOU race. + */ public async move( oldPath: RelativePath, newPath: RelativePath - ): Promise { + ): Promise { if (oldPath === newPath) { - return; + return { actualPath: oldPath }; } - await this.ensureClearPath(newPath); + if (await this.fs.exists(newPath)) { + throw new FileAlreadyExistsError( + `Refusing to move '${oldPath}' onto '${newPath}': target already exists`, + newPath + ); + } + await this.createParentDirectories(newPath); - this.database.move(oldPath, newPath); - await this.fs.rename(oldPath, newPath); + this.expectedFsEvents.expectRename(oldPath, newPath); + try { + await this.fs.rename(oldPath, newPath); + } catch (e) { + this.expectedFsEvents.unexpectRename(oldPath, newPath); + throw e; + } await this.deletingEmptyParentDirectoriesOfDeletedFile(oldPath); - } - - public reset(): void { - this.fs.reset(); + return { actualPath: newPath }; } private async deletingEmptyParentDirectoriesOfDeletedFile( @@ -185,7 +250,7 @@ export class FileOperations { let directory = path; // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (true) { - [directory] = FileOperations.getParentDirAndFile(directory); + [directory] = FileOperations.getParentDirAndFileName(directory); if (directory.length === 0) { break; } @@ -237,55 +302,4 @@ export class FileOperations { } } } - - /** - * Deconflicts the given path by appending (1), (2), etc. before the file extension until a non-existent path is found. - * The returned path has a lock acquired on it; it must be released by the caller when no longer needed. - * - * @param path The starting path to deconflict - * @returns a non-existent path with a lock acquired on it - */ - private async deconflictPath(path: RelativePath): Promise { - // eslint-disable-next-line prefer-const - let [directory, fileName] = FileOperations.getParentDirAndFile(path); - - if (directory) { - directory += "/"; - } - - const nameParts = fileName.split("."); - // Handle dotfiles: ".gitignore" should have no extension, ".config.json" should have ".json" - const isDotfile = fileName.startsWith(".") && nameParts[0] === ""; - const extension = - nameParts.length > 1 && !(isDotfile && nameParts.length === 2) - ? "." + nameParts[nameParts.length - 1] - : ""; - let stem = extension ? nameParts.slice(0, -1).join(".") : fileName; - let currentCount = Number.parseInt( - FileOperations.PARENTHESES_REGEX.exec(stem)?.groups?.count ?? "0" - ); - stem = stem.replace(FileOperations.PARENTHESES_REGEX, ""); - - let newName = path; - - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - while (true) { - currentCount++; - newName = `${directory}${stem} (${currentCount})${extension}`; - - // Avoid multiple deconflictPath calls returning the same path - if (this.fs.tryLock(newName)) { - const newDocument = - this.database.getLatestDocumentByRelativePath(newName); - if ( - newDocument?.isDeleted === false || // the document might have been confirmed by the server at a new path but haven't yet moved there locally - (await this.fs.exists(newName, true)) - ) { - this.fs.unlock(newName); - } else { - return newName; - } - } - } - } } diff --git a/frontend/sync-client/src/file-operations/filesystem-operations.ts b/frontend/sync-client/src/file-operations/filesystem-operations.ts index 36dddfe6..a5fb006b 100644 --- a/frontend/sync-client/src/file-operations/filesystem-operations.ts +++ b/frontend/sync-client/src/file-operations/filesystem-operations.ts @@ -1,4 +1,4 @@ -import type { RelativePath } from "../persistence/database"; +import type { RelativePath } from "../sync-operations/types"; import type { TextWithCursors } from "reconcile-text"; diff --git a/frontend/sync-client/src/file-operations/safe-filesystem-operations.ts b/frontend/sync-client/src/file-operations/safe-filesystem-operations.ts index 904bf805..89b5008c 100644 --- a/frontend/sync-client/src/file-operations/safe-filesystem-operations.ts +++ b/frontend/sync-client/src/file-operations/safe-filesystem-operations.ts @@ -1,24 +1,18 @@ -import type { RelativePath } from "../persistence/database"; +import type { RelativePath } from "../sync-operations/types"; import type { FileSystemOperations } from "./filesystem-operations"; import type { Logger } from "../tracing/logger"; -import { Locks } from "../utils/data-structures/locks"; -import { FileNotFoundError } from "./file-not-found-error"; +import { FileNotFoundError } from "../errors/file-not-found-error"; import type { TextWithCursors } from "reconcile-text"; /** * Decorates `FileSystemOperations` to replace errors with `FileNotFoundError` - * if the accessed file doesn't exist. It also ensures that there's at most a - * single request in-flight for any one file through the use of locks. + * if the accessed file doesn't exist. */ export class SafeFileSystemOperations implements FileSystemOperations { - private readonly locks: Locks; - public constructor( private readonly fs: FileSystemOperations, private readonly logger: Logger - ) { - this.locks = new Locks(logger); - } + ) {} public async listFilesRecursively( root: RelativePath | undefined @@ -31,19 +25,12 @@ export class SafeFileSystemOperations implements FileSystemOperations { public async read(path: RelativePath): Promise { this.logger.debug(`Reading file '${path}'`); - return this.safeOperation( - path, - async () => - this.locks.withLock(path, async () => this.fs.read(path)), - "read" - ); + return this.safeOperation(path, async () => this.fs.read(path), "read"); } public async write(path: RelativePath, content: Uint8Array): Promise { this.logger.debug(`Writing to file '${path}'`); - return this.locks.withLock(path, async () => - this.fs.write(path, content) - ); + return this.fs.write(path, content); } public async atomicUpdateText( @@ -53,10 +40,7 @@ export class SafeFileSystemOperations implements FileSystemOperations { this.logger.debug(`Atomically updating file '${path}'`); return this.safeOperation( path, - async () => - this.locks.withLock(path, async () => - this.fs.atomicUpdateText(path, updater) - ), + async () => this.fs.atomicUpdateText(path, updater), "atomicUpdateText" ); } @@ -65,80 +49,43 @@ export class SafeFileSystemOperations implements FileSystemOperations { // Logging this would be too noisy return this.safeOperation( path, - async () => - this.locks.withLock(path, async () => - this.fs.getFileSize(path) - ), + async () => this.fs.getFileSize(path), "getFileSize" ); } - public async exists( - path: RelativePath, - skipLock = false - ): Promise { + public async exists(path: RelativePath): Promise { this.logger.debug(`Checking if file '${path}' exists`); - if (skipLock) { - return this.fs.exists(path); - } else { - return this.locks.withLock(path, async () => this.fs.exists(path)); - } + return this.fs.exists(path); } public async createDirectory(path: RelativePath): Promise { this.logger.debug(`Creating directory '${path}'`); - return this.locks.withLock(path, async () => - this.fs.createDirectory(path) - ); + return this.fs.createDirectory(path); } public async delete(path: RelativePath): Promise { this.logger.debug(`Deleting file '${path}'`); - return this.locks.withLock(path, async () => this.fs.delete(path)); + return this.fs.delete(path); } public async rename( oldPath: RelativePath, - newPath: RelativePath, - skipLock = false + newPath: RelativePath ): Promise { this.logger.debug(`Renaming file '${oldPath}' to '${newPath}'`); return this.safeOperation( oldPath, - async () => { - if (skipLock) { - return this.fs.rename(oldPath, newPath); - } else { - return this.locks.withLock([oldPath, newPath], async () => - this.fs.rename(oldPath, newPath) - ); - } - }, + async () => this.fs.rename(oldPath, newPath), "rename" ); } - public tryLock(path: RelativePath): boolean { - return this.locks.tryLock(path); - } - - public async waitForLock(path: RelativePath): Promise { - return this.locks.waitForLock(path); - } - - public unlock(path: RelativePath): void { - this.locks.unlock(path); - } - - public reset(): void { - this.locks.reset(); - } - /** - * Decorate an operation to ensure that the file exists before running it. - * If the operation fails, it will check if the file still exists and throw - * a FileNotFoundError if it doesn't. - */ + * Decorate an operation to ensure that the file exists before running it. + * If the operation fails, it will check if the file still exists and throw + * a FileNotFoundError if it doesn't. + */ private async safeOperation( path: RelativePath, operation: () => Promise, @@ -154,9 +101,6 @@ export class SafeFileSystemOperations implements FileSystemOperations { try { return await operation(); } catch (error) { - // Without locking the file, this isn't atomic, however, it's good enough in practice. - // This will only break if the file exists, gets deleted and then immediately - // recreated while `operation` is running. if (await this.fs.exists(path)) { throw error; } else { diff --git a/frontend/sync-client/src/persistence/database.ts b/frontend/sync-client/src/persistence/database.ts deleted file mode 100644 index 86b2845c..00000000 --- a/frontend/sync-client/src/persistence/database.ts +++ /dev/null @@ -1,374 +0,0 @@ -import type { Logger } from "../tracing/logger"; -import { EMPTY_HASH } from "../utils/hash"; -import { CoveredValues } from "../utils/data-structures/min-covered"; -import { awaitAll } from "../utils/await-all"; -import { removeFromArray } from "../utils/remove-from-array"; - -export type VaultUpdateId = number; -export type DocumentId = string; -export type RelativePath = string; - -export interface DocumentMetadata { - parentVersionId: VaultUpdateId; - hash: string; - remoteRelativePath?: RelativePath; -} - -export interface StoredDocumentMetadata { - relativePath: RelativePath; - documentId: DocumentId; - parentVersionId: VaultUpdateId; - remoteRelativePath?: RelativePath; - hash: string; -} - -export interface StoredDatabase { - documents: StoredDocumentMetadata[]; - lastSeenUpdateId: VaultUpdateId | undefined; - hasInitialSyncCompleted: boolean; -} - -/** - * Represents a document in the database. - * - * It is mutable and its content should always represent the latest - * state of the document on disk based on the update events we have seen. - */ -export interface DocumentRecord { - relativePath: RelativePath; - documentId: DocumentId; - metadata: DocumentMetadata | undefined; - isDeleted: boolean; - updates: Promise[]; - parallelVersion: number; -} - -export class Database { - private documents: DocumentRecord[]; - private lastSeenUpdateIds: CoveredValues; - private hasInitialSyncCompleted: boolean; - - public constructor( - private readonly logger: Logger, - initialState: Partial | undefined, - private readonly saveData: (data: StoredDatabase) => Promise - ) { - initialState ??= {}; - - this.documents = - initialState.documents?.map( - ({ relativePath, documentId, ...metadata }) => ({ - relativePath, - documentId, - metadata, - isDeleted: false, - updates: [], - parallelVersion: 0 - }) - ) ?? []; - - this.ensureConsistency(); - this.logger.debug(`Loaded ${this.documents.length} documents`); - - const { lastSeenUpdateId } = initialState; - this.logger.debug(`Loaded last seen update id: ${lastSeenUpdateId}`); - this.lastSeenUpdateIds = new CoveredValues( - Math.max(0, lastSeenUpdateId ?? 0) // the first updateId will be 1 which is the first integer after -1 - ); - - this.documents.forEach((doc) => { - this.lastSeenUpdateIds.add(doc.metadata?.parentVersionId); - }); - - this.hasInitialSyncCompleted = - initialState.hasInitialSyncCompleted ?? false; - this.logger.debug( - `Loaded hasInitialSyncCompleted: ${this.hasInitialSyncCompleted}` - ); - } - - public get length(): number { - return this.documents.length; - } - - public get resolvedDocuments(): DocumentRecord[] { - const paths = new Map(); - this.documents - // eslint-disable-next-line no-restricted-syntax -- Type narrowing, not removing a specific item - .filter(({ metadata }) => metadata !== undefined) - .forEach((record) => - paths.set(record.relativePath, [ - record, - ...(paths.get(record.relativePath) ?? []) - ]) - ); - - return Array.from(paths.values()).map((records) => { - records.sort( - (a, b) => b.parallelVersion - a.parallelVersion // descending - ); - - if ( - records.length > 1 && - records.some((current, i) => - i === 0 - ? false - : records[i - 1].parallelVersion === - current.parallelVersion - ) - ) { - throw new Error( - `Multiple documents with the same parallel version and path at ${records[0].relativePath}` - ); - } - return records[0]; - }); - } - - public updateDocumentMetadata( - metadata: { - parentVersionId: VaultUpdateId; - hash: string; - remoteRelativePath: RelativePath; - }, - toUpdate: DocumentRecord - ): void { - if (!this.documents.includes(toUpdate)) { - throw new Error("Document not found in database"); - } - - toUpdate.metadata = metadata; - - this.saveInTheBackground(); - } - - public removeDocumentPromise(promise: Promise): void { - const entry = this.documents.find(({ updates }) => - updates.includes(promise) - ); - - if (entry === undefined) { - // This method should be idempotent and tolerant of - // stragglers calling it after the databse has been reset. - return; - } - - removeFromArray(entry.updates, promise); - // No need to save as Promises don't get serialized - } - - public removeDocument(find: DocumentRecord): void { - removeFromArray(this.documents, find); - this.saveInTheBackground(); - } - - public getLatestDocumentByRelativePath( - find: RelativePath - ): DocumentRecord | undefined { - const candidates = this.documents.filter( - ({ relativePath }) => relativePath === find - ); - candidates.sort((a, b) => b.parallelVersion - a.parallelVersion); // descending - return candidates[0]; - } - - public async getResolvedDocumentByRelativePath( - relativePath: RelativePath, - promise: Promise - ): Promise { - const entry = this.getLatestDocumentByRelativePath(relativePath); - - if (entry === undefined) { - throw new Error( - `Document not found by relative path: ${relativePath}, ${JSON.stringify( - this.documents, - null, - 2 - )}` - ); - } - - const currentPromises = entry.updates; - entry.updates = [...currentPromises, promise]; - await awaitAll(currentPromises); - - return entry; - } - - public createNewPendingDocument( - documentId: DocumentId, - relativePath: RelativePath, - promise: Promise - ): DocumentRecord { - this.logger.debug( - `Creating new pending document: ${relativePath} (${documentId})` - ); - const previousEntry = - this.getLatestDocumentByRelativePath(relativePath); - - const entry = { - relativePath, - documentId, - metadata: undefined, - isDeleted: false, - updates: [promise], - parallelVersion: - previousEntry?.parallelVersion === undefined - ? 0 - : previousEntry.parallelVersion + 1 - }; - - this.documents.push(entry); - this.saveInTheBackground(); - - return entry; - } - - public createNewEmptyDocument( - documentId: DocumentId, - parentVersionId: VaultUpdateId, - relativePath: RelativePath - ): DocumentRecord { - const entry = { - relativePath, - documentId, - metadata: { - parentVersionId, - hash: EMPTY_HASH, - remoteRelativePath: relativePath - }, - isDeleted: false, - updates: [], - parallelVersion: 0 - }; - - this.documents.push(entry); - this.saveInTheBackground(); - - return entry; - } - - public getDocumentByDocumentId( - find: DocumentId - ): DocumentRecord | undefined { - return this.documents.find(({ documentId }) => documentId === find); - } - - public move( - oldRelativePath: RelativePath, - newRelativePath: RelativePath - ): void { - const oldDocument = - this.getLatestDocumentByRelativePath(oldRelativePath); - - if (oldDocument === undefined) { - return; - } - - const newDocument = - this.getLatestDocumentByRelativePath(newRelativePath); - if (newDocument?.isDeleted === false) { - throw new Error( - `Document already exists at new location: ${newRelativePath}` - ); - } - - oldDocument.relativePath = newRelativePath; - // We're in a strange state where the target of the move has just got deleted, - // however, its metadata might already have a bunch of updates queued up for - // the document at the new location. We need to keep these updates. - oldDocument.parallelVersion = - newDocument !== undefined ? newDocument.parallelVersion + 1 : 0; - - this.saveInTheBackground(); - } - - public delete(relativePath: RelativePath): void { - const candidate = this.getLatestDocumentByRelativePath(relativePath); - if (candidate === undefined) { - throw new Error( - `Document not found by relative path: ${relativePath}` - ); - } - candidate.isDeleted = true; - } - - public getHasInitialSyncCompleted(): boolean { - return this.hasInitialSyncCompleted; - } - - public setHasInitialSyncCompleted(value: boolean): void { - this.hasInitialSyncCompleted = value; - this.saveInTheBackground(); - } - - public getLastSeenUpdateId(): VaultUpdateId { - return this.lastSeenUpdateIds.min; - } - - public addSeenUpdateId(value: number): void { - const previousMin = this.lastSeenUpdateIds.min; - this.lastSeenUpdateIds.add(value); - if (previousMin !== this.lastSeenUpdateIds.min) { - this.saveInTheBackground(); - } - } - - public setLastSeenUpdateId(value: number): void { - this.lastSeenUpdateIds.min = value; - this.saveInTheBackground(); - } - - public reset(): void { - this.documents = []; - this.lastSeenUpdateIds = new CoveredValues( - 0 // the first updateId will be 1 which is the first integer after -1 - ); - this.hasInitialSyncCompleted = false; - this.saveInTheBackground(); - } - - public async save(): Promise { - return this.saveData({ - documents: this.resolvedDocuments.map( - ({ relativePath, documentId, metadata }) => ({ - documentId, - relativePath, - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - ...metadata! // `resolvedDocuments` only returns docs with metadata set - }) - ), - lastSeenUpdateId: this.lastSeenUpdateIds.min, - hasInitialSyncCompleted: this.hasInitialSyncCompleted - }); - } - - private ensureConsistency(): void { - const idToPath = new Map(); - - this.resolvedDocuments.forEach(({ relativePath, documentId }) => { - idToPath.set(documentId, [ - ...(idToPath.get(documentId) ?? []), - relativePath - ]); - }); - - const duplicates = Array.from(idToPath.entries()) - .filter(([_, paths]) => paths.length > 1) - .map(([id, paths]) => `${id} (${paths.join(", ")})`); - - if (duplicates.length > 0) { - throw new Error( - "Document IDs are not unique, found duplicates: " + - duplicates.join("; ") - ); - } - } - - private saveInTheBackground(): void { - this.ensureConsistency(); - void this.save().catch((error: unknown) => { - this.logger.error(`Error saving data: ${error}`); - }); - } -} diff --git a/frontend/sync-client/src/persistence/settings.ts b/frontend/sync-client/src/persistence/settings.ts index d78170e6..c954134f 100644 --- a/frontend/sync-client/src/persistence/settings.ts +++ b/frontend/sync-client/src/persistence/settings.ts @@ -6,7 +6,6 @@ export interface SyncSettings { remoteUri: string; token: string; vaultName: string; - syncConcurrency: number; isSyncEnabled: boolean; maxFileSizeMB: number; ignorePatterns: string[]; @@ -14,22 +13,19 @@ export interface SyncSettings { diffCacheSizeMB: number; enableTelemetry: boolean; networkRetryIntervalMs: number; - minimumSaveIntervalMs: number; } export const DEFAULT_SETTINGS: SyncSettings = { remoteUri: "", token: "", vaultName: "default", - syncConcurrency: 1, isSyncEnabled: false, maxFileSizeMB: 10, ignorePatterns: [], webSocketRetryIntervalMs: 3500, diffCacheSizeMB: 4, enableTelemetry: false, - networkRetryIntervalMs: 1000, - minimumSaveIntervalMs: 1000 + networkRetryIntervalMs: 1000 }; export class Settings { @@ -38,7 +34,7 @@ export class Settings { >(); private settings: SyncSettings; - private readonly lock: Lock = new Lock(); + private readonly lock: Lock; public constructor( private readonly logger: Logger, @@ -50,6 +46,8 @@ export class Settings { ...(initialState ?? {}) }; + this.lock = new Lock(Settings.name, this.logger); + this.logger.debug( `Loaded settings: ${JSON.stringify(this.settings, null, 2)}` ); From 42c9d554899a5e6fac2dd1917cfe863da8b48ea2 Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Fri, 8 May 2026 21:37:26 +0100 Subject: [PATCH 10/17] split: sync-engine rewrite (sync-operations + sync-client.ts) Replace the single unrestricted-syncer.ts with a two-loop architecture: - syncer.ts drains the FIFO wire queue (HTTP + WS handlers). - reconciler.ts moves files to make localPath match remoteRelativePath (topo-sorted move graph, in-memory cycle resolution with crash-safe swap markers). - sync-event-queue.ts holds the byDocId / byLocalPath indexes and the pending-create promise chain. - offline-change-detector.ts, expected-fs-events.ts, types.ts, and a rewritten cursor-tracker.ts / file-change-notifier.ts round it out. Plus sync-client.ts wiring, tracing/sync-history.ts updates, index.ts re-exports, and sync-client tsconfig/webpack/package.json. --- frontend/sync-client/package.json | 18 +- frontend/sync-client/src/index.ts | 15 +- frontend/sync-client/src/sync-client.ts | 376 ++-- .../src/sync-operations/cursor-tracker.ts | 155 +- .../src/sync-operations/expected-fs-events.ts | 138 ++ .../sync-operations/file-change-notifier.ts | 2 +- .../offline-change-detector.test.ts | 185 ++ .../offline-change-detector.ts | 188 ++ .../src/sync-operations/reconciler.test.ts | 69 + .../src/sync-operations/reconciler.ts | 1020 +++++++++++ .../sync-operations/sync-event-queue.test.ts | 907 ++++++++++ .../src/sync-operations/sync-event-queue.ts | 1000 +++++++++++ .../sync-client/src/sync-operations/syncer.ts | 1533 ++++++++++++----- .../sync-client/src/sync-operations/types.ts | 74 + .../sync-operations/unrestricted-syncer.ts | 596 ------- .../sync-client/src/tracing/sync-history.ts | 36 +- frontend/sync-client/tsconfig.json | 4 +- frontend/sync-client/webpack.config.js | 9 - 18 files changed, 5068 insertions(+), 1257 deletions(-) create mode 100644 frontend/sync-client/src/sync-operations/expected-fs-events.ts create mode 100644 frontend/sync-client/src/sync-operations/offline-change-detector.test.ts create mode 100644 frontend/sync-client/src/sync-operations/offline-change-detector.ts create mode 100644 frontend/sync-client/src/sync-operations/reconciler.test.ts create mode 100644 frontend/sync-client/src/sync-operations/reconciler.ts create mode 100644 frontend/sync-client/src/sync-operations/sync-event-queue.test.ts create mode 100644 frontend/sync-client/src/sync-operations/sync-event-queue.ts create mode 100644 frontend/sync-client/src/sync-operations/types.ts delete mode 100644 frontend/sync-client/src/sync-operations/unrestricted-syncer.ts diff --git a/frontend/sync-client/package.json b/frontend/sync-client/package.json index aa369fa7..45c33764 100644 --- a/frontend/sync-client/package.json +++ b/frontend/sync-client/package.json @@ -14,19 +14,17 @@ }, "devDependencies": { "byte-base64": "^1.1.0", - "minimatch": "^10.0.1", - "p-queue": "^8.1.0", + "minimatch": "^10.1.1", + "p-queue": "^9.0.1", "reconcile-text": "^0.8.0", - "uuid": "^13.0.0", - "@types/node": "^24.8.1", - "ts-loader": "^9.5.2", + "@types/node": "^25.0.2", + "ts-loader": "^9.5.4", "tslib": "2.8.1", - "tsx": "^4.20.6", - "typescript": "5.8.3", - "webpack": "^5.99.9", + "tsx": "^4.21.0", + "typescript": "5.9.3", + "webpack": "^5.103.0", "webpack-cli": "^6.0.1", "webpack-merge": "^6.0.1", - "@sentry/browser": "^10.8.0", - "ws": "^8.18.3" + "@sentry/browser": "^10.30.0" } } diff --git a/frontend/sync-client/src/index.ts b/frontend/sync-client/src/index.ts index cfcc5071..f06523a6 100644 --- a/frontend/sync-client/src/index.ts +++ b/frontend/sync-client/src/index.ts @@ -2,6 +2,7 @@ import { awaitAll } from "./utils/await-all"; import { logToConsole } from "./utils/debugging/log-to-console"; import { slowFetchFactory } from "./utils/debugging/slow-fetch-factory"; import { slowWebSocketFactory } from "./utils/debugging/slow-web-socket-factory"; +import { InMemoryFileSystem } from "./utils/debugging/in-memory-file-system"; import { getRandomColor } from "./utils/get-random-color"; import { lineAndColumnToPosition } from "./utils/line-and-column-to-position"; import { positionToLineAndColumn } from "./utils/position-to-line-and-column"; @@ -21,14 +22,19 @@ export { export { Logger, LogLevel, LogLine } from "./tracing/logger"; export { type SyncSettings, DEFAULT_SETTINGS } from "./persistence/settings"; export { rateLimit } from "./utils/rate-limit"; -export type { RelativePath, StoredDatabase } from "./persistence/database"; +export type { + RelativePath, + StoredSyncState as StoredDatabase, + DocumentRecord +} from "./sync-operations/types"; export type { FileSystemOperations } from "./file-operations/filesystem-operations"; export type { PersistenceProvider } from "./persistence/persistence"; export type { CursorSpan } from "./services/types/CursorSpan"; export type { ClientCursors } from "./services/types/ClientCursors"; export type { NetworkConnectionStatus } from "./types/network-connection-status"; -export type { ServerVersionMismatchError } from "./services/server-version-mismatch-error"; -export type { AuthenticationError } from "./services/authentication-error"; +export type { ServerVersionMismatchError } from "./errors/server-version-mismatch-error"; +export type { AuthenticationError } from "./errors/authentication-error"; +export { SyncResetError } from "./errors/sync-reset-error"; export type { MaybeOutdatedClientCursors } from "./types/maybe-outdated-client-cursors"; export { DocumentSyncStatus } from "./types/document-sync-status"; export { SyncClient } from "./sync-client"; @@ -37,7 +43,8 @@ export type { TextWithCursors, CursorPosition } from "reconcile-text"; export const debugging = { slowFetchFactory, slowWebSocketFactory, - logToConsole + logToConsole, + InMemoryFileSystem }; export const utils = { diff --git a/frontend/sync-client/src/sync-client.ts b/frontend/sync-client/src/sync-client.ts index 2a272c86..dd537296 100644 --- a/frontend/sync-client/src/sync-client.ts +++ b/frontend/sync-client/src/sync-client.ts @@ -2,8 +2,12 @@ import type { PersistenceProvider } from "./persistence/persistence"; import type { HistoryEntry, HistoryStats } from "./tracing/sync-history"; import { SyncHistory } from "./tracing/sync-history"; import { Logger, LogLevel, LogLine } from "./tracing/logger"; -import type { RelativePath, StoredDatabase } from "./persistence/database"; -import { Database } from "./persistence/database"; +import type { + DocumentId, + RelativePath, + StoredSyncState +} from "./sync-operations/types"; +import { SyncEventQueue } from "./sync-operations/sync-event-queue"; import * as Sentry from "@sentry/browser"; import type { SyncSettings } from "./persistence/settings"; import { DEFAULT_SETTINGS, Settings } from "./persistence/settings"; @@ -12,7 +16,6 @@ import { Syncer } from "./sync-operations/syncer"; import type { FileSystemOperations } from "./file-operations/filesystem-operations"; import { FileOperations } from "./file-operations/file-operations"; import { FetchController } from "./services/fetch-controller"; -import { UnrestrictedSyncer } from "./sync-operations/unrestricted-syncer"; import { rateLimit } from "./utils/rate-limit"; import type { NetworkConnectionStatus } from "./types/network-connection-status"; import { DocumentSyncStatus } from "./types/document-sync-status"; @@ -24,42 +27,46 @@ import type { MaybeOutdatedClientCursors } from "./types/maybe-outdated-client-c import { FileChangeNotifier } from "./sync-operations/file-change-notifier"; import { FixedSizeDocumentCache } from "./utils/data-structures/fix-sized-cache"; import { setUpTelemetry } from "./utils/set-up-telemetry"; -import { DIFF_CACHE_SIZE_MB } from "./consts"; import { ServerConfig } from "./services/server-config"; import type { EventListeners } from "./utils/data-structures/event-listeners"; +import { Lock } from "./utils/data-structures/locks"; +import { ExpectedFsEvents } from "./sync-operations/expected-fs-events"; export class SyncClient { - private hasStartedOfflineSync = false; private hasFinishedOfflineSync = false; private hasStarted = false; private hasBeenDestroyed = false; private unloadTelemetry?: () => void; private isDestroying = false; private readonly eventUnsubscribers: (() => void)[] = []; + private readonly settingsChangeLock = new Lock( + "SyncClient.onSettingsChange" + ); private constructor( + public readonly logger: Logger, private readonly history: SyncHistory, private readonly settings: Settings, - private readonly database: Database, + private readonly syncEventQueue: SyncEventQueue, private readonly syncer: Syncer, private readonly webSocketManager: WebSocketManager, - public readonly logger: Logger, private readonly fetchController: FetchController, private readonly cursorTracker: CursorTracker, private readonly fileChangeNotifier: FileChangeNotifier, private readonly contentCache: FixedSizeDocumentCache, - private readonly fileOperations: FileOperations, private readonly serverConfig: ServerConfig, + private readonly syncService: SyncService, + private readonly expectedFsEvents: ExpectedFsEvents, private readonly persistence: PersistenceProvider< Partial<{ settings: Partial; - database: Partial; + database: Partial; }> > ) {} - public get documentCount(): number { - return this.database.length; + public get syncedDocumentCount(): number { + return this.syncEventQueue.syncedDocumentCount; } public get isWebSocketConnected(): boolean { @@ -73,6 +80,27 @@ export class SyncClient { return this.history.onHistoryUpdated; } + /** + * Fires whenever a tracked document's local file moves on disk — + * watcher-driven user renames, post-create deconflicts placed by + * the reconciler, lost-rename replays in offline scan, slot + * displacements when another record claims a path. Both + * `oldPath` and `newPath` may be `undefined` (placement-pending + * state). Useful for callers that mirror disk-side path state + * — e.g. test harnesses tracking which paths are safe to mutate + * — and need a signal beyond the user-facing history. + */ + public get onDocumentPathChanged(): EventListeners< + ( + documentId: DocumentId, + oldPath: RelativePath | undefined, + newPath: RelativePath | undefined + ) => unknown + > { + this.checkIfDestroyed("onDocumentPathChanged getter"); + return this.syncEventQueue.onDocumentPathChanged; + } + public get onSettingsChanged(): EventListeners< (newSettings: SyncSettings, oldSettings: SyncSettings) => unknown > { @@ -101,6 +129,13 @@ export class SyncClient { return this.cursorTracker.onRemoteCursorsUpdated; } + public get hasPendingWork(): boolean { + return ( + this.syncEventQueue.pendingUpdateCount > 0 || + this.webSocketManager.hasOutstandingWork + ); + } + public static async create({ fs, persistence, @@ -112,7 +147,8 @@ export class SyncClient { persistence: PersistenceProvider< Partial<{ settings: Partial; - database: Partial; + database: Partial; + deviceId: string; }> >; fetch?: typeof globalThis.fetch; @@ -121,39 +157,46 @@ export class SyncClient { }): Promise { const logger = new Logger(); - const deviceId = createClientId(); - - logger.info(`Creating SyncClient with client id ${deviceId}`); - const history = new SyncHistory(logger); let state = (await persistence.load()) ?? { settings: undefined, - database: undefined + database: undefined, + deviceId: undefined }; + // Persist deviceId across destroy + init so the server's + // lost-create dedup (which scopes by device_id) can recognise + // a retry as belonging to the same client. Without this, + // every fresh `SyncClient` after a destroy would generate a + // new deviceId, the server-side query would miss, and the + // pending-but-lost create would deconflict instead of + // binding to the doc its content was already absorbed into. + let deviceId = state.deviceId; + if (deviceId === undefined) { + deviceId = createClientId(); + state = { ...state, deviceId }; + await persistence.save(state); + } + + logger.info(`Creating SyncClient with client id ${deviceId}`); + const settings = new Settings( logger, state.settings, async (data): Promise => { state = { ...state, settings: data }; - // we're not rate-limiting settings saves as (1) we need to initialise the settings to know the rate limit - // and (2) settings changes are infrequent enough that rate-limiting is not necessary await persistence.save(state); } ); - const rateLimitedSave = rateLimit( - persistence.save, - () => settings.getSettings().minimumSaveIntervalMs - ); - - const database = new Database( + const syncEventQueue = new SyncEventQueue( + settings, logger, state.database, async (data): Promise => { state = { ...state, database: data }; - await rateLimitedSave(state); + await persistence.save(state); } ); @@ -170,32 +213,23 @@ export class SyncClient { fetch ); - const serverConfig = new ServerConfig(syncService); + const serverConfig = new ServerConfig(syncService, settings); + + const expectedFsEvents = new ExpectedFsEvents(); const fileOperations = new FileOperations( logger, - database, fs, serverConfig, + expectedFsEvents, nativeLineEndings ); const contentCache = new FixedSizeDocumentCache( - 1024 * 1024 * DIFF_CACHE_SIZE_MB - ); - const unrestrictedSyncer = new UnrestrictedSyncer( - logger, - database, - settings, - syncService, - fileOperations, - history, - contentCache, - serverConfig + 1024 * 1024 * settings.getSettings().diffCacheSizeMB ); const webSocketManager = new WebSocketManager( - deviceId, logger, settings, webSocket @@ -204,34 +238,38 @@ export class SyncClient { const syncer = new Syncer( deviceId, logger, - database, settings, - syncService, webSocketManager, fileOperations, - unrestrictedSyncer + syncService, + history, + contentCache, + serverConfig, + syncEventQueue ); const fileChangeNotifier = new FileChangeNotifier(); const cursorTracker = new CursorTracker( - database, + logger, + syncEventQueue, webSocketManager, fileOperations, fileChangeNotifier ); const client = new SyncClient( + logger, history, settings, - database, + syncEventQueue, syncer, webSocketManager, - logger, fetchController, cursorTracker, fileChangeNotifier, contentCache, - fileOperations, serverConfig, + syncService, + expectedFsEvents, persistence ); @@ -285,10 +323,10 @@ export class SyncClient { } /** - * Reload settings from disk overriding current in-memory settings. - * Missing values will be filled in from DEFAULT_SETTINGS rather than - * retaining current in-memory settings. - */ + * Reload settings from disk overriding current in-memory settings. + * Missing values will be filled in from DEFAULT_SETTINGS rather than + * retaining current in-memory settings. + */ public async reloadSettings(): Promise { this.checkIfDestroyed("reloadSettings"); @@ -320,10 +358,10 @@ export class SyncClient { } /** - * Wait for the in-flight operations to finish, reset all tracking, - * and the local database but retain the settings. - * The SyncClient can be used again after calling this method. - */ + * Wait for the in-flight operations to finish, reset all tracking, + * and the local state but retain the settings. + * The SyncClient can be used again after calling this method. + */ public async reset(): Promise { this.checkIfDestroyed("reset"); @@ -332,16 +370,16 @@ export class SyncClient { ); await this.pause(); - // clear all local state this.logger.info("Resetting SyncClient's local state"); - this.database.reset(); - await this.database.save(); // ensure the new database reads as empty + await this.syncEventQueue.clearAllState(); + await this.syncEventQueue.save(); this.resetInMemoryState(); - this.hasStartedOfflineSync = false; this.hasFinishedOfflineSync = false; this.serverConfig.reset(); - await this.startSyncing(); + if (this.settings.getSettings().isSyncEnabled) { + await this.startSyncing(); + } } public getSettings(): SyncSettings { @@ -363,40 +401,48 @@ export class SyncClient { await this.settings.setSettings(value); } - public async syncLocallyCreatedFile( - relativePath: RelativePath - ): Promise { + public syncLocallyCreatedFile(relativePath: RelativePath): void { this.checkIfDestroyed("syncLocallyCreatedFile"); - this.fileChangeNotifier.notifyOfFileChange(relativePath); - return this.syncer.syncLocallyCreatedFile(relativePath); + this.fileChangeNotifier.notifyOfFileChange(relativePath); // this is for updating cursors + if (this.expectedFsEvents.matchCreate(relativePath)) { + return; + } + + this.syncer.syncLocallyCreatedFile(relativePath); } - public async syncLocallyDeletedFile( - relativePath: RelativePath - ): Promise { - this.checkIfDestroyed("syncLocallyDeletedFile"); - - this.fileChangeNotifier.notifyOfFileChange(relativePath); - return this.syncer.syncLocallyDeletedFile(relativePath); - } - - public async syncLocallyUpdatedFile({ + public syncLocallyUpdatedFile({ oldPath, relativePath }: { oldPath?: RelativePath; relativePath: RelativePath; - }): Promise { + }): void { this.checkIfDestroyed("syncLocallyUpdatedFile"); - this.fileChangeNotifier.notifyOfFileChange(relativePath); - return this.syncer.syncLocallyUpdatedFile({ + this.fileChangeNotifier.notifyOfFileChange(relativePath); // this is for updating cursors + if (this.expectedFsEvents.matchUpdate(relativePath, oldPath)) { + return; + } + + this.syncer.syncLocallyUpdatedFile({ oldPath, relativePath }); } + public syncLocallyDeletedFile(relativePath: RelativePath): void { + this.checkIfDestroyed("syncLocallyDeletedFile"); + + this.fileChangeNotifier.notifyOfFileChange(relativePath); // this is for updating cursors + if (this.expectedFsEvents.matchDelete(relativePath)) { + return; + } + + this.syncer.syncLocallyDeletedFile(relativePath); + } + public getDocumentSyncingStatus( relativePath: RelativePath ): DocumentSyncStatus { @@ -406,16 +452,11 @@ export class SyncClient { return DocumentSyncStatus.SYNCING_IS_DISABLED; } - if (!this.syncer.isFirstSyncComplete || !this.hasFinishedOfflineSync) { + if (!this.hasFinishedOfflineSync) { return DocumentSyncStatus.SYNCING; } - const document = - this.database.getLatestDocumentByRelativePath(relativePath); - if (document === undefined) { - return DocumentSyncStatus.SYNCING; - } - return document.updates.length > 0 + return this.syncEventQueue.hasPendingEventsForPath(relativePath) ? DocumentSyncStatus.SYNCING : DocumentSyncStatus.UP_TO_DATE; } @@ -429,20 +470,20 @@ export class SyncClient { } public async waitUntilFinished(): Promise { - this.checkIfDestroyed("waitUntilIdle"); - await this.syncer.waitUntilFinished(); - await this.webSocketManager.waitUntilFinished(); - await this.database.save(); // flush all changes to disk + this.checkIfDestroyed("waitUntilFinished"); + await this.waitUntilFinishedInternal(); } /** - * Completely destroy the SyncClient, cancelling all in-progress operations. - * After calling this method, the SyncClient cannot be used again. - */ + * Completely destroy the SyncClient, cancelling all in-progress operations. + * After calling this method, the SyncClient cannot be used again. + */ public async destroy(): Promise { - this.checkIfDestroyed("destroy"); - - // Prevent concurrent destroy calls + if (this.hasBeenDestroyed) { + throw new Error( + "SyncClient has been destroyed and can no longer be used; called from destroy" + ); + } if (this.isDestroying) { this.logger.warn( "destroy() called while already destroying, ignoring" @@ -451,52 +492,92 @@ export class SyncClient { } this.isDestroying = true; - // cancel everything that's in progress - await this.pause(); + // Run cleanup in `finally` so a thrown pause() — or anything else + // mid-shutdown — still leaves the client in the disposed state + // instead of bricked with subscribers/telemetry hanging on. + try { + await this.pause(); + } finally { + this.hasBeenDestroyed = true; - this.hasBeenDestroyed = true; + this.resetInMemoryState(); - this.resetInMemoryState(); + this.eventUnsubscribers.forEach((unsubscribe) => { + unsubscribe(); + }); + this.eventUnsubscribers.length = 0; - // Clean up event listeners to prevent memory leaks - this.eventUnsubscribers.forEach((unsubscribe) => { - unsubscribe(); - }); - this.eventUnsubscribers.length = 0; + this.logger.info("SyncClient has been successfully disposed"); - this.logger.info("SyncClient has been successfully disposed"); + this.unloadTelemetry?.(); + } + } - this.unloadTelemetry?.(); + /** + * The actual drain — separated from `waitUntilFinished` so internal + * shutdown paths (`pause` / `destroy`) can wait for in-flight work + * without tripping the public `checkIfDestroyed` guard, which exists + * only to keep external callers from continuing to use a disposed + * client. + * + * Loops because a WebSocket message handler completing is what enqueues + * a `RemoteChange` into the syncer; if we awaited the syncer first and + * the WS handler second, a message arriving mid-wait would leave a fresh + * drain pending while `save()` ran. Each iteration waits for both, then + * re-checks; we exit only once both report idle in the same pass. + */ + private async waitUntilFinishedInternal(): Promise { + while ( + this.webSocketManager.hasOutstandingWork || + this.syncer.hasPendingWork + ) { + await this.webSocketManager.waitUntilFinished(); + await this.syncer.waitUntilFinished(); + } + await this.syncEventQueue.save(); } private async startSyncing(): Promise { this.checkIfDestroyed("startSyncing"); this.fetchController.finishReset(); + // Undo any earlier `pause()` stop so retryForever keeps retrying. + this.syncService.resume(); - await this.serverConfig.initialize(); + await this.serverConfig.getConfig(); + + await this.syncer.scheduleSyncForOfflineChanges(); + this.syncer.resumeDraining(); this.webSocketManager.start(); - if (!this.hasStartedOfflineSync) { - this.hasStartedOfflineSync = true; - await this.syncer.scheduleSyncForOfflineChanges(); - } - this.hasFinishedOfflineSync = true; } private async pause(): Promise { + this.hasFinishedOfflineSync = false; + this.syncer.pauseDraining(); this.fetchController.startReset(); + // Signal the service so any `retryForever` loop exits at its next + // iteration instead of continuing to retry a network request while + // the rest of the client is winding down. + this.syncService.stop(); await this.webSocketManager.stop(); - await this.waitUntilFinished(); + await this.waitUntilFinishedInternal(); + // Clear the offline-scan gate so a subsequent `startSyncing()` + // re-runs the scan; otherwise any local changes made while sync was + // paused (offline edits, deletes, renames) wouldn't be detected, and + // an incoming remote update would silently overwrite them. + this.syncer.clearOfflineScanGate(); + // Drop any expected fs events that were registered but never matched + // (e.g. an op aborted by SyncResetError). Otherwise a real user edit + // at the same path after re-enable would be swallowed. + this.expectedFsEvents.clear(); } private resetInMemoryState(): void { this.history.reset(); this.contentCache.reset(); - // don't reset the logger this.cursorTracker.reset(); this.syncer.reset(); - this.fileOperations.reset(); } private async onSettingsChange( @@ -505,36 +586,55 @@ export class SyncClient { ): Promise { this.checkIfDestroyed("onSettingsChange"); - if ( - newSettings.vaultName !== oldSettings.vaultName || - newSettings.remoteUri !== oldSettings.remoteUri - ) { - await this.reset(); - } - - if (newSettings.isSyncEnabled !== oldSettings.isSyncEnabled) { - if (newSettings.isSyncEnabled) { - await this.startSyncing(); - } else { - await this.pause(); + // Serialize listener invocations so back-to-back settings updates + // can't run reset()/pause()/startSyncing() concurrently. + await this.settingsChangeLock.withLock(async () => { + // The lock is FIFO, so by the time we run the client may have + // been destroyed in a queued invocation ahead of us. + if (this.hasBeenDestroyed) { + return; } - } - if (newSettings.diffCacheSizeMB !== oldSettings.diffCacheSizeMB) { - this.contentCache.resize(newSettings.diffCacheSizeMB * 1024 * 1024); - } + const connectionChanged = + newSettings.vaultName !== oldSettings.vaultName || + newSettings.remoteUri !== oldSettings.remoteUri; - if (newSettings.enableTelemetry !== oldSettings.enableTelemetry) { - if (newSettings.enableTelemetry) { - this.unloadTelemetry = setUpTelemetry(); - } else { - this.unloadTelemetry?.(); + if (connectionChanged) { + // reset() pauses, clears state, then starts iff isSyncEnabled + // — so any concurrent isSyncEnabled change is already applied. + await this.reset(); + } else if ( + newSettings.isSyncEnabled !== oldSettings.isSyncEnabled + ) { + if (newSettings.isSyncEnabled) { + await this.startSyncing(); + } else { + await this.pause(); + } } - } + + if (newSettings.diffCacheSizeMB !== oldSettings.diffCacheSizeMB) { + this.contentCache.resize( + newSettings.diffCacheSizeMB * 1024 * 1024 + ); + } + + if (newSettings.enableTelemetry !== oldSettings.enableTelemetry) { + if (newSettings.enableTelemetry) { + this.unloadTelemetry = setUpTelemetry(); + } else { + this.unloadTelemetry?.(); + } + } + }); } private checkIfDestroyed(origin: string): void { - if (this.hasBeenDestroyed) { + // Reject new public-API entries the moment destroy() is called, + // not after `pause()` returns. Otherwise an external caller could + // pass the guard and start mutating state while destroy() is + // tearing down the websocket / clearing caches. + if (this.hasBeenDestroyed || this.isDestroying) { throw new Error( `SyncClient has been destroyed and can no longer be used; called from ${origin}` ); diff --git a/frontend/sync-client/src/sync-operations/cursor-tracker.ts b/frontend/sync-client/src/sync-operations/cursor-tracker.ts index bdd7d9b7..c31721b1 100644 --- a/frontend/sync-client/src/sync-operations/cursor-tracker.ts +++ b/frontend/sync-client/src/sync-operations/cursor-tracker.ts @@ -1,5 +1,6 @@ import type { FileOperations } from "../file-operations/file-operations"; -import type { Database, RelativePath } from "../persistence/database"; +import type { RelativePath } from "./types"; +import type { SyncEventQueue } from "./sync-event-queue"; import type { ClientCursors } from "../services/types/ClientCursors"; import type { CursorSpan } from "../services/types/CursorSpan"; import type { DocumentWithCursors } from "../services/types/DocumentWithCursors"; @@ -10,6 +11,7 @@ import { hash } from "../utils/hash"; import type { FileChangeNotifier } from "./file-change-notifier"; import { Lock } from "../utils/data-structures/locks"; import { EventListeners } from "../utils/data-structures/event-listeners"; +import type { Logger } from "../tracing/logger"; // Cursor positions are updated separately from documents. However, a given cursor position is only // valid within a certain version of the document it belongs to. This class tracks previous and the latest @@ -22,22 +24,29 @@ export class CursorTracker { (cursors: MaybeOutdatedClientCursors[]) => unknown >(); - private readonly updateLock = new Lock(); + private readonly updateLock: Lock; private knownRemoteCursors: (ClientCursors & { upToDateness: DocumentUpToDateness; })[] = []; - private lastLocalCursorState: DocumentWithCursors[] = []; - private lastLocalCursorStateWithoutDirtyDocuments: DocumentWithCursors[] = - []; + // Cache the previously sent state as a JSON string rather than as the + // array. We mutate `documentsWithCursors` in-place after the cache check + // (setting `vaultUpdateId = null` for dirty docs); storing the array would + // alias and the next call's equality check would compare against + // post-mutation state. + private lastLocalCursorStateJson = "[]"; + private lastLocalCursorStateWithoutDirtyDocumentsJson = "[]"; public constructor( - private readonly database: Database, + logger: Logger, + private readonly queue: SyncEventQueue, private readonly webSocketManager: WebSocketManager, private readonly fileOperations: FileOperations, private readonly fileChangeNotifier: FileChangeNotifier ) { + this.updateLock = new Lock(CursorTracker.name, logger); + this.webSocketManager.onRemoteCursorsUpdateReceived.add( async (clientCursors) => { await this.updateLock.withLock(async () => { @@ -53,7 +62,7 @@ export class CursorTracker { for (const cursor of clientCursors.filter((client) => client.documentsWithCursors.every( - (doc) => doc.vault_update_id != null + (doc) => doc.vaultUpdateId != null ) )) { updatedKnownRemoteCursors.push({ @@ -77,14 +86,20 @@ export class CursorTracker { for (const clientCursor of this.knownRemoteCursors) { if ( clientCursor.documentsWithCursors.some( - (document) => - document.relative_path === relativePath + (document) => document.relativePath === relativePath ) ) { clientCursor.upToDateness = await this.getDocumentsUpToDateness(clientCursor); } } + // Drop the local-cursor send-cache so the next call re-reads + // the file. The first cache key is the editor's input, which + // doesn't change when the file content does — without this, + // a remote update flipping the file from dirty back to clean + // would never re-send the cursor with a fresh `vaultUpdateId`. + this.lastLocalCursorStateJson = ""; + this.lastLocalCursorStateWithoutDirtyDocumentsJson = ""; }) ); } @@ -95,70 +110,67 @@ export class CursorTracker { public async sendLocalCursorsToServer( documentToCursors: Record ): Promise { - const documentsWithCursors: DocumentWithCursors[] = []; + // Serialise concurrent senders so they don't interleave on the + // disk reads + state mutations and emit out-of-order cursor messages. + await this.updateLock.withLock(async () => { + const documentsWithCursors: DocumentWithCursors[] = []; - for (const [relativePath, cursors] of Object.entries( - documentToCursors - )) { - const record = - this.database.getLatestDocumentByRelativePath(relativePath); + for (const [relativePath, cursors] of Object.entries( + documentToCursors + )) { + const record = this.queue.getRecordByLocalPath(relativePath); - if (!record) { - continue; // Let's wait for the file to be created before sending cursors + if (!record) { + continue; // Let's wait for the file to be created before sending cursors + } + + documentsWithCursors.push({ + relativePath: relativePath, + documentId: record.documentId, + vaultUpdateId: record.parentVersionId, + cursors: cursors.map(({ start, end }) => ({ + start: Math.min(start, end), + end: Math.max(start, end) + })) // the client might send directional selections + }); } - if (!record.metadata) { - continue; // this is a new document, no need to sync the cursors + const beforeJson = JSON.stringify(documentsWithCursors); + if (this.lastLocalCursorStateJson === beforeJson) { + // Caching step to avoid reading the edited files all the time + return; + } + this.lastLocalCursorStateJson = beforeJson; + + for (const doc of documentsWithCursors) { + const readContent = await this.fileOperations.read( + doc.relativePath + ); + const record = this.queue.getRecordByLocalPath( + doc.relativePath + ); + if (record?.remoteHash !== (await hash(readContent))) { + doc.vaultUpdateId = null; + } } - documentsWithCursors.push({ - relative_path: relativePath, - document_id: record.documentId, - vault_update_id: record.metadata.parentVersionId, - cursors: cursors.map(({ start, end }) => ({ - start: Math.min(start, end), - end: Math.max(start, end) - })) // the client might send directional selections - }); - } - - if ( - JSON.stringify(this.lastLocalCursorState) === - JSON.stringify(documentsWithCursors) - ) { - // Caching step to avoid reading the edited files all the time - return; - } - this.lastLocalCursorState = documentsWithCursors; - - for (const doc of documentsWithCursors) { - const readContent = await this.fileOperations.read( - doc.relative_path - ); - const record = this.database.getLatestDocumentByRelativePath( - doc.relative_path - ); - if (record?.metadata?.hash !== hash(readContent)) { - doc.vault_update_id = null; + const afterJson = JSON.stringify(documentsWithCursors); + if ( + this.lastLocalCursorStateWithoutDirtyDocumentsJson === afterJson + ) { + return; } - } - if ( - JSON.stringify(this.lastLocalCursorStateWithoutDirtyDocuments) === - JSON.stringify(documentsWithCursors) - ) { - return; - } + this.lastLocalCursorStateWithoutDirtyDocumentsJson = afterJson; - this.lastLocalCursorStateWithoutDirtyDocuments = documentsWithCursors; - - this.webSocketManager.updateLocalCursors({ documentsWithCursors }); + this.webSocketManager.updateLocalCursors({ documentsWithCursors }); + }); } public reset(): void { this.knownRemoteCursors = []; - this.lastLocalCursorState = []; - this.lastLocalCursorStateWithoutDirtyDocuments = []; + this.lastLocalCursorStateJson = "[]"; + this.lastLocalCursorStateWithoutDirtyDocumentsJson = "[]"; this.updateLock.reset(); } @@ -223,35 +235,28 @@ export class CursorTracker { private async getDocumentUpToDateness( document: DocumentWithCursors ): Promise { - const record = this.database.getLatestDocumentByRelativePath( - document.relative_path - ); + const record = this.queue.getRecordByLocalPath(document.relativePath); if (!record) { // the document of the cursor must be from the future return DocumentUpToDateness.Later; } - if ( - (record.metadata?.parentVersionId ?? 0) < - (document.vault_update_id ?? 0) - ) { + if (record.parentVersionId < (document.vaultUpdateId ?? 0)) { return DocumentUpToDateness.Later; - } else if ( - (document.vault_update_id ?? 0) < - (record.metadata?.parentVersionId ?? 0) - ) { + } else if ((document.vaultUpdateId ?? 0) < record.parentVersionId) { // the document of the cursor must be from the past return DocumentUpToDateness.Prior; } const currentContent = await this.fileOperations.read( - document.relative_path + document.relativePath ); - return this.database.getLatestDocumentByRelativePath( - document.relative_path - )?.metadata?.hash === hash(currentContent) + const currentRecord = this.queue.getRecordByLocalPath( + document.relativePath + ); + return currentRecord?.remoteHash === (await hash(currentContent)) ? DocumentUpToDateness.UpToDate : DocumentUpToDateness.Prior; } diff --git a/frontend/sync-client/src/sync-operations/expected-fs-events.ts b/frontend/sync-client/src/sync-operations/expected-fs-events.ts new file mode 100644 index 00000000..a2c4f52f --- /dev/null +++ b/frontend/sync-client/src/sync-operations/expected-fs-events.ts @@ -0,0 +1,138 @@ +import type { RelativePath } from "./types"; + +/** + * Counter-based registry of filesystem events the syncer is about to + * cause. The syncer's own writes/renames/deletes go through + * `FileOperations`, which calls into the host filesystem; the host then + * fires watcher events that come back through `SyncClient.syncLocallyXxx`. + * Without filtering, those echo events would be re-uploaded to the server + * and broadcast back, producing an unbounded loop. + * + * The fix: every fs call in `FileOperations` registers the event it is + * about to provoke; the matching `syncLocallyXxx` handler consumes it. + * User-initiated edits never register, so they pass through unchanged. + * + * Counts are per (kind, path) so back-to-back syncer ops on the same path + * (e.g. apply remote update then re-apply during convergence) match + * one-for-one. If the watcher never fires for a registered op (e.g. the + * fs throws before notifying), the entry is left behind; `clear()` is + * called on pause/destroy to drop those before they collide with a real + * user event later. + */ +export class ExpectedFsEvents { + private readonly creates = new Map(); + private readonly updates = new Map(); + private readonly deletes = new Map(); + // Renames are keyed by `JSON.stringify({oldPath, newPath})` so the + // delimiter cannot occur inside either path. + private readonly renames = new Map(); + + private static renameKey( + oldPath: RelativePath, + newPath: RelativePath + ): string { + return JSON.stringify({ oldPath, newPath }); + } + + public expectCreate(path: RelativePath): void { + this.bump(this.creates, path); + } + + public expectUpdate(path: RelativePath): void { + this.bump(this.updates, path); + } + + public expectDelete(path: RelativePath): void { + this.bump(this.deletes, path); + } + + public expectRename(oldPath: RelativePath, newPath: RelativePath): void { + this.bump(this.renames, ExpectedFsEvents.renameKey(oldPath, newPath)); + } + + /** + * Cancel a previously-registered expectation when the fs op that registered + * it failed before any watcher event could fire. Without this, a leaked + * expectation silently swallows the next genuine user event at the same + * path (or, for renames, the same `oldPath → newPath` pair). + * + * Floored at zero: if the watcher *did* fire (op partially completed) and + * already consumed the entry, the unexpect is a no-op. The fallback is + * acceptable — at worst we re-upload a real edit we'd otherwise filter. + */ + public unexpectCreate(path: RelativePath): void { + this.decrement(this.creates, path); + } + + public unexpectUpdate(path: RelativePath): void { + this.decrement(this.updates, path); + } + + public unexpectDelete(path: RelativePath): void { + this.decrement(this.deletes, path); + } + + public unexpectRename(oldPath: RelativePath, newPath: RelativePath): void { + this.decrement( + this.renames, + ExpectedFsEvents.renameKey(oldPath, newPath) + ); + } + + public matchCreate(path: RelativePath): boolean { + return this.consume(this.creates, path); + } + + public matchUpdate( + path: RelativePath, + oldPath: RelativePath | undefined + ): boolean { + if (oldPath !== undefined) { + return this.consume( + this.renames, + ExpectedFsEvents.renameKey(oldPath, path) + ); + } + return this.consume(this.updates, path); + } + + public matchDelete(path: RelativePath): boolean { + return this.consume(this.deletes, path); + } + + public clear(): void { + this.creates.clear(); + this.updates.clear(); + this.deletes.clear(); + this.renames.clear(); + } + + private bump(map: Map, key: RelativePath): void { + map.set(key, (map.get(key) ?? 0) + 1); + } + + private consume( + map: Map, + key: RelativePath + ): boolean { + const count = map.get(key) ?? 0; + if (count === 0) { + return false; + } + if (count === 1) { + map.delete(key); + } else { + map.set(key, count - 1); + } + return true; + } + + private decrement(map: Map, key: RelativePath): void { + const count = map.get(key) ?? 0; + if (count <= 1) { + map.delete(key); + } else { + map.set(key, count - 1); + } + } +} diff --git a/frontend/sync-client/src/sync-operations/file-change-notifier.ts b/frontend/sync-client/src/sync-operations/file-change-notifier.ts index d1e49d62..414c9e91 100644 --- a/frontend/sync-client/src/sync-operations/file-change-notifier.ts +++ b/frontend/sync-client/src/sync-operations/file-change-notifier.ts @@ -1,4 +1,4 @@ -import type { RelativePath } from "../persistence/database"; +import type { RelativePath } from "./types"; import { EventListeners } from "../utils/data-structures/event-listeners"; export class FileChangeNotifier { diff --git a/frontend/sync-client/src/sync-operations/offline-change-detector.test.ts b/frontend/sync-client/src/sync-operations/offline-change-detector.test.ts new file mode 100644 index 00000000..cc710e6a --- /dev/null +++ b/frontend/sync-client/src/sync-operations/offline-change-detector.test.ts @@ -0,0 +1,185 @@ +import { describe, it } from "node:test"; +import assert from "node:assert"; +import { Logger } from "../tracing/logger"; +import { Settings } from "../persistence/settings"; +import { STORED_STATE_SCHEMA_VERSION, SyncEventQueue } from "./sync-event-queue"; +import { scheduleOfflineChanges } from "./offline-change-detector"; +import type { FileOperations } from "../file-operations/file-operations"; +import type { RelativePath } from "./types"; + +const makeQueue = async (): Promise => { + const logger = new Logger(); + const settings = new Settings(logger, {}, async () => { + /* no-op */ + }); + return new SyncEventQueue( + settings, + logger, + { schemaVersion: STORED_STATE_SCHEMA_VERSION }, + async () => { + /* no-op */ + } + ); +}; + +const makeOperations = ( + files: Record +): FileOperations => { + return { + listFilesRecursively: async () => Object.keys(files), + read: async (path: RelativePath) => { + const data = files[path]; + if (data === undefined) { + throw new Error(`File not found: ${path}`); + } + return data; + } + } as unknown as FileOperations; +}; + +describe("scheduleOfflineChanges", () => { + it("does not bind a local file to a placement-pending record whose remoteRelativePath was persisted before the doc moved on the server", async () => { + // The bug: persisted byDocId can carry a placement-pending record + // whose `remoteRelativePath` was saved before the doc was moved + // server-side. After restart, offline-scan running before WS + // catch-up would bind an unrelated local file at that stale path + // to the moved doc and push the user's content as an update — + // silently corrupting the moved doc and stranding the local file. + const queue = await makeQueue(); + + // Stale placement-pending record: server has moved this doc + // away from "stale-X.md" since this snapshot was saved. + await queue.upsertRecord({ + documentId: "MOVED-DOC", + parentVersionId: 5, + remoteRelativePath: "stale-X.md" as RelativePath, + remoteHash: "hash-from-old-state", + localPath: undefined + }); + + // User has an unrelated local file at the stale path. + const operations = makeOperations({ + "stale-X.md": new TextEncoder().encode( + "user's unrelated local content" + ) + }); + + const enqueued: { kind: string; path: string }[] = []; + await scheduleOfflineChanges( + new Logger(), + operations, + queue, + (path) => enqueued.push({ kind: "create", path }), + (args) => enqueued.push({ kind: "update", path: args.relativePath }), + (path) => enqueued.push({ kind: "delete", path }) + ); + + // The local file must become a fresh CREATE — never a hostile + // UPDATE on the moved doc. + assert.deepStrictEqual(enqueued, [ + { kind: "create", path: "stale-X.md" } + ]); + + // The placement-pending record must remain placement-pending — + // its localPath must not have been bound to the unrelated user + // file. The reconciler will place it correctly once WS catch-up + // updates `remoteRelativePath` to the doc's current location. + const record = queue.getDocumentByDocumentId("MOVED-DOC"); + assert.notStrictEqual(record, undefined); + assert.strictEqual(record?.localPath, undefined); + }); + + it("schedules an update for a local file that matches a settled record's localPath", async () => { + const queue = await makeQueue(); + await queue.upsertRecord({ + documentId: "SETTLED-DOC", + parentVersionId: 2, + remoteRelativePath: "doc.md" as RelativePath, + remoteHash: "hash", + localPath: "doc.md" as RelativePath + }); + + const operations = makeOperations({ + "doc.md": new TextEncoder().encode("content") + }); + + const enqueued: { kind: string; path: string }[] = []; + await scheduleOfflineChanges( + new Logger(), + operations, + queue, + (path) => enqueued.push({ kind: "create", path }), + (args) => enqueued.push({ kind: "update", path: args.relativePath }), + (path) => enqueued.push({ kind: "delete", path }) + ); + + assert.deepStrictEqual(enqueued, [ + { kind: "update", path: "doc.md" } + ]); + }); + + it("schedules a delete for a settled record whose local file is missing", async () => { + const queue = await makeQueue(); + await queue.upsertRecord({ + documentId: "VANISHED-DOC", + parentVersionId: 4, + remoteRelativePath: "gone.md" as RelativePath, + remoteHash: "hash", + localPath: "gone.md" as RelativePath + }); + + const operations = makeOperations({}); + + const enqueued: { kind: string; path: string }[] = []; + await scheduleOfflineChanges( + new Logger(), + operations, + queue, + (path) => enqueued.push({ kind: "create", path }), + (args) => enqueued.push({ kind: "update", path: args.relativePath }), + (path) => enqueued.push({ kind: "delete", path }) + ); + + assert.deepStrictEqual(enqueued, [ + { kind: "delete", path: "gone.md" } + ]); + }); + + it("detects an offline rename when an untracked file matches a deleted record's content hash", async () => { + const queue = await makeQueue(); + const content = new TextEncoder().encode("body"); + const contentHash = await (await import("../utils/hash")).hash(content); + + await queue.upsertRecord({ + documentId: "DOC-1", + parentVersionId: 5, + remoteRelativePath: "old.md" as RelativePath, + remoteHash: contentHash, + localPath: "old.md" as RelativePath + }); + const operations = makeOperations({ "new.md": content }); + + const enqueued: { + kind: string; + path: string; + oldPath?: string; + }[] = []; + await scheduleOfflineChanges( + new Logger(), + operations, + queue, + (path) => enqueued.push({ kind: "create", path }), + (args) => + enqueued.push({ + kind: "update", + path: args.relativePath, + oldPath: args.oldPath + }), + (path) => enqueued.push({ kind: "delete", path }) + ); + + assert.deepStrictEqual(enqueued, [ + { kind: "update", path: "new.md", oldPath: "old.md" } + ]); + }); +}); diff --git a/frontend/sync-client/src/sync-operations/offline-change-detector.ts b/frontend/sync-client/src/sync-operations/offline-change-detector.ts new file mode 100644 index 00000000..5b91e782 --- /dev/null +++ b/frontend/sync-client/src/sync-operations/offline-change-detector.ts @@ -0,0 +1,188 @@ +import type { DocumentRecord, RelativePath } from "./types"; +import type { Logger } from "../tracing/logger"; +import { hash } from "../utils/hash"; +import type { FileOperations } from "../file-operations/file-operations"; +import { findMatchingFile } from "../utils/find-matching-file"; +import type { SyncEventQueue } from "./sync-event-queue"; +import { removeFromArray } from "../utils/remove-from-array"; +import { FileNotFoundError } from "../errors/file-not-found-error"; + +/** + * Scans the local filesystem and the document database to determine + * which files were created, updated, moved, or deleted while the + * client was offline, then enqueues the appropriate sync events. + * + * Placement-pending records (`localPath === undefined`) are deliberately + * NOT bound to local files at the same `remoteRelativePath` here. The + * persisted byDocId snapshot can be stale — a doc's server-side path + * may have changed since the last save, so binding by stored path would + * fold an unrelated user file into a moved doc and silently corrupt it. + * Local files at those paths fall through to the LocalCreate flow below; + * the server's create_document handler dedupes by path+freshness when + * the doc really is at that path, and otherwise creates a new doc that + * the reconciler places correctly once catch-up updates the stale + * record's `remoteRelativePath`. + */ +export async function scheduleOfflineChanges( + logger: Logger, + operations: FileOperations, + queue: SyncEventQueue, + enqueueCreate: (path: RelativePath) => void, + enqueueUpdate: (args: { + oldPath?: RelativePath; + relativePath: RelativePath; + }) => void, + enqueueDelete: (path: RelativePath) => void +): Promise { + const allLocalFiles = new Set(await operations.listFilesRecursively()); + logger.info(`Scheduling sync for ${allLocalFiles.size} local files`); + // `allSettledDocuments()` skips records with `localPath === undefined` + // — those have no local file by definition and don't participate in + // the disk-vs-record diff. The reconciler will place them on its + // next pass. + const allDocuments = queue.allSettledDocuments(); + + // A doc is "possibly deleted" only if it has no local file. Including + // docs that still exist locally would queue a spurious delete alongside + // the update below. + const locallyPossiblyDeletedFiles: DocumentRecord[] = []; + for (const record of allDocuments.values()) { + // `localPath` is guaranteed non-undefined for entries in + // `allSettledDocuments()`, but narrow explicitly for the type + // checker (and so a future change to that helper doesn't + // silently break this loop). + if ( + record.localPath !== undefined && + !allLocalFiles.has(record.localPath) + ) { + locallyPossiblyDeletedFiles.push(record); + } + } + + const locallyPossibleCreatedFiles: RelativePath[] = []; + const syncedLocalFiles: RelativePath[] = []; + + for (const localFile of allLocalFiles) { + if (allDocuments.has(localFile)) { + syncedLocalFiles.push(localFile); + } else if (queue.hasPendingCreateForPath(localFile)) { + // A LocalCreate for this path is still in flight (no + // record yet — its docId is a Promise). Re-enqueueing + // would fire a second HTTP create that the server then + // deconflicts to a sibling path, leaving the same bytes + // in two docs. Skip; the in-flight create owns this slot. + continue; + } else { + locallyPossibleCreatedFiles.push(localFile); + } + } + + const renamedPaths = new Set(); + // Track paths that were in `allLocalFiles` at scan-start but have + // since disappeared. The scan awaits between `listFilesRecursively` + // and each `read`, so a concurrent delete (slow file events, real + // user activity) can vacate a slot mid-scan. Throwing would abort + // the whole scan; nothing to sync for a file that's already gone. + const disappearedPaths = new Set(); + for (const path of locallyPossibleCreatedFiles) { + let content: Uint8Array; + try { + content = await operations.read(path); + } catch (e) { + if (e instanceof FileNotFoundError) { + logger.debug( + `File ${path} disappeared before offline-scan could read it; skipping` + ); + disappearedPaths.add(path); + continue; + } + throw e; + } + const contentHash = await hash(content); + + const matchingDeletedFile = await findMatchingFile( + contentHash, + locallyPossiblyDeletedFiles + ); + if (matchingDeletedFile !== undefined) { + // localPath is guaranteed defined for records in + // locallyPossiblyDeletedFiles (we filtered above). + const oldPath = matchingDeletedFile.localPath; + if (oldPath === undefined) { + continue; + } + logger.debug( + `File ${path} might have been moved from ${oldPath} while offline, scheduling sync to move it` + ); + enqueueUpdate({ + oldPath, + relativePath: path + }); + removeFromArray(locallyPossiblyDeletedFiles, matchingDeletedFile); + renamedPaths.add(path); + } + } + + for (const path of locallyPossibleCreatedFiles) { + if (renamedPaths.has(path) || disappearedPaths.has(path)) { + continue; + } + + logger.info( + `File ${path} was created while offline, scheduling sync to create it` + ); + + enqueueCreate(path); + } + + for (const item of locallyPossiblyDeletedFiles) { + if (item.localPath === undefined) { + continue; + } + logger.info( + `File ${item.localPath} was deleted while offline, scheduling sync to delete it` + ); + enqueueDelete(item.localPath); + } + + for (const path of syncedLocalFiles) { + const record = allDocuments.get(path); + if ( + record !== undefined && + record.localPath !== undefined && + record.localPath !== record.remoteRelativePath && + !allLocalFiles.has(record.remoteRelativePath) && + queue.byLocalPath.get(record.remoteRelativePath) === undefined + ) { + // Lost local-rename recovery. The record's `localPath` + // (where the user has the file now) and + // `remoteRelativePath` (where the server still thinks it + // lives) disagree, which means a queued user-rename's + // LocalUpdate never reached the server before the queue + // was wiped (typically a sync reset). Without this + // branch the next `enqueueUpdate({ relativePath: path })` + // is a content-only update — server keeps the doc at the + // old path, the user's file at the new path orphans, and + // other clients never see the rename. Replay the rename + // by restoring the OLD localPath so the queue's enqueue + // can find the record by `oldPath`, then enqueueUpdate + // moves it back to the new path with `isUserRename`. + // Only fires when the old slot is genuinely empty + // (neither on disk nor claimed by another tracked + // record) — otherwise the rename target is occupied and + // we'd be confusing the byLocalPath index. + const oldPath = record.remoteRelativePath; + const newPath = record.localPath; + logger.info( + `Lost local rename detected: doc ${record.documentId} at ${oldPath} (server) vs ${newPath} (local); replaying rename to server` + ); + await queue.setLocalPath(record.documentId, oldPath); + enqueueUpdate({ oldPath, relativePath: newPath }); + continue; + } + logger.info( + `File ${path} may have been updated while offline, scheduling sync to update it` + ); + enqueueUpdate({ relativePath: path }); + } +} diff --git a/frontend/sync-client/src/sync-operations/reconciler.test.ts b/frontend/sync-client/src/sync-operations/reconciler.test.ts new file mode 100644 index 00000000..13a08363 --- /dev/null +++ b/frontend/sync-client/src/sync-operations/reconciler.test.ts @@ -0,0 +1,69 @@ +import { describe, it } from "node:test"; +import assert from "node:assert"; +import { Logger, LogLevel } from "../tracing/logger"; +import { Settings } from "../persistence/settings"; +import { STORED_STATE_SCHEMA_VERSION, SyncEventQueue } from "./sync-event-queue"; +import { Reconciler } from "./reconciler"; +import { SyncResetError } from "../errors/sync-reset-error"; +import type { FileOperations } from "../file-operations/file-operations"; +import type { SyncService } from "../services/sync-service"; +import type { RelativePath } from "./types"; + +describe("Reconciler", () => { + it("does not emit an error when placement fetch is interrupted by reset", async () => { + const logger = new Logger(); + const settings = new Settings(logger, {}, async () => { + /* no-op */ + }); + const queue = new SyncEventQueue( + settings, + logger, + { schemaVersion: STORED_STATE_SCHEMA_VERSION }, + async () => { + /* no-op */ + } + ); + + await queue.upsertRecord({ + documentId: "DOC-1", + parentVersionId: 1, + remoteHash: "hash", + remoteRelativePath: "remote.md" as RelativePath, + localPath: undefined + }); + + const operations = { + exists: async () => false, + create: async () => { + assert.fail("reset-interrupted placement should not write"); + } + } as unknown as FileOperations; + + const syncService = { + getDocumentVersionContent: async () => { + throw new SyncResetError(); + } + } as unknown as SyncService; + + const reconciler = new Reconciler( + logger, + operations, + syncService, + queue, + new Map() + ); + + await reconciler.run(); + + assert.deepStrictEqual(logger.getMessages(LogLevel.ERROR), []); + assert.ok( + logger + .getMessages(LogLevel.INFO) + .some((line) => + line.message.includes( + "content fetch for DOC-1 interrupted by sync reset" + ) + ) + ); + }); +}); diff --git a/frontend/sync-client/src/sync-operations/reconciler.ts b/frontend/sync-client/src/sync-operations/reconciler.ts new file mode 100644 index 00000000..93505a3c --- /dev/null +++ b/frontend/sync-client/src/sync-operations/reconciler.ts @@ -0,0 +1,1020 @@ +import type { FileOperations } from "../file-operations/file-operations"; +import { FileNotFoundError } from "../errors/file-not-found-error"; +import { FileAlreadyExistsError } from "../errors/file-already-exists-error"; +import type { Logger } from "../tracing/logger"; +import type { SyncService } from "../services/sync-service"; +import type { SyncEventQueue } from "./sync-event-queue"; +import type { DocumentId, DocumentRecord, RelativePath } from "./types"; +import { hash } from "../utils/hash"; +import { SyncResetError } from "../errors/sync-reset-error"; + +const SWAP_MARKER_DIR = ".vaultlink"; +const SWAP_MARKER_PREFIX = "swap-"; +const SWAP_MARKER_SUFFIX = ".json"; + +interface SwapLeg { + documentId: DocumentId; + from: RelativePath; + to: RelativePath; + expectedHashOnFrom: string; +} + +interface SwapMarker { + uuid: string; + legs: SwapLeg[]; +} + +interface PlannedMove { + record: DocumentRecord; + from: RelativePath; + to: RelativePath; +} + +function tryParseSwapMarker(bytes: Uint8Array): SwapMarker | undefined { + try { + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + return JSON.parse(new TextDecoder().decode(bytes)) as SwapMarker; + } catch { + return undefined; + } +} + +/** + * The Reconciler is the second of the sync engine's two loops. The wire + * loop (records ↔ server) updates `record.remoteRelativePath` and writes + * file content into `record.localPath`; it does not move files for path + * placement. The Reconciler (records ↔ disk) runs after every wire-loop + * step and best-effort lines disk up with `remoteRelativePath` for every + * tracked record. + * + * "Best effort" means: any per-record obstacle (slot occupied, file + * missing, etc.) is silently skipped and retried on the next pass. + * `run()` never throws — per-record errors are logged and the next + * record is processed. + * + * Three shapes of work exist: + * 1. Initial placement — `localPath === undefined`. The wire loop + * created the record with no on-disk presence (e.g. a remote create + * whose target slot was occupied at receive time). If the slot is + * free now, fetch content (from `pendingPlacementContent` if a + * handler stuffed it for us, otherwise from the server) and write. + * 2. Simple rename — `localPath !== remoteRelativePath` and no other + * tracked record wants our current slot. Plain rename. + * 3. Cycle — two or more records want each others' current slots + * (A → B, B → A; or longer rotations). Resolved by reading every + * member's bytes into memory then overwriting each target slot. + * A write-ahead marker file lets `recoverFromInterruptedSwap()` + * finish a swap that crashed mid-flight on next startup. + */ +export class Reconciler { + public constructor( + private readonly logger: Logger, + private readonly operations: FileOperations, + private readonly syncService: SyncService, + private readonly queue: SyncEventQueue, + // Bytes already in hand from a recent server response, keyed by + // docId. Wire-loop handlers populate this transiently when they + // have content for a record they just upserted with `localPath + // === undefined`; the reconciler uses it on the same pass + // instead of re-fetching from the server. Keys are deleted when + // consumed. + private readonly pendingPlacementContent: Map + ) {} + + /** + * Single best-effort pass. Walks every tracked record, places + * unplaced ones, and reorganises any whose `localPath !== + * remoteRelativePath`. Never throws — per-record failures are + * logged and the next record is processed. The Syncer is expected + * to call this after every wire-loop drain step, so any record + * skipped this pass gets another shot once the obstructing event + * is processed. + */ + public async run(): Promise { + const allRecords = this.collectAllRecords(); + + const movesNeeded: PlannedMove[] = []; + const deferredPlacements: DocumentRecord[] = []; + + for (const record of allRecords) { + if (record.localPath === record.remoteRelativePath) { + continue; + } + + // The reconciler operates on settled records. A record with a + // pending LocalUpdate or LocalDelete is mid-flight: the wire + // loop owns the user's intent (rename target, edit content, + // deletion) and the record's `remoteRelativePath` may still + // reflect the pre-rename server state. Touching disk now + // would race the wire loop — e.g. a queued user-rename + // LocalUpdate would find its source path vacated by the + // reconciler moving the file back to the stale + // `remoteRelativePath`. Skip; once the wire loop drains the + // pending events, a subsequent reconciler pass sees a + // settled record and converges. + if ( + this.queue.hasPendingLocalEventsForDocumentId(record.documentId) + ) { + continue; + } + + // The doc has been deleted server-side (HTTP DELETE acked) but + // the WebSocket receipt that would `removeDocumentById` hasn't + // arrived yet. The record looks like "needs initial placement" + // (`localPath === undefined`, since the LocalDelete enqueue + // cleared it), but placing would resurrect a doc the user + // explicitly deleted. Skip; `processRemoteDelete` will remove + // the record entirely once the WS receipt arrives. + if (this.queue.hasPendingServerDelete(record.documentId)) { + continue; + } + + if (record.localPath === undefined) { + deferredPlacements.push(record); + continue; + } + + // localPath !== undefined and !== remoteRelativePath. Plan a + // move. First defensive existence check: the file may have + // been deleted between the wire loop touching disk and this + // reconciler pass — the watcher's LocalDelete will land + // shortly and fix the record. Skip silently. + try { + if (!(await this.operations.exists(record.localPath))) { + this.logger.debug( + `Reconciler: record ${record.documentId} localPath ${record.localPath} ` + + `is missing on disk; skipping (LocalDelete will catch up)` + ); + continue; + } + } catch (e) { + this.logger.error( + `Reconciler: existence check failed for ${record.localPath}: ${String(e)}` + ); + continue; + } + + movesNeeded.push({ + record, + from: record.localPath, + to: record.remoteRelativePath + }); + } + + if (movesNeeded.length > 0) { + await this.executeMoves(movesNeeded); + } + + // Run placements *after* moves so a placement whose target slot + // was occupied by a tracked record at the start of the pass can + // still succeed once that record's move frees the slot. Without + // this ordering, a placement-pending record stalls until the + // next reconciler tick — which only fires when new events + // arrive, leaving the doc absent on disk if the queue happens + // to be quiescent at that moment. + for (const record of deferredPlacements) { + // Re-check the gating conditions: a pending event may have + // been enqueued for this doc while we were processing + // moves above, and an interleaved placement would race + // it. + if ( + this.queue.hasPendingLocalEventsForDocumentId(record.documentId) + ) { + continue; + } + if (this.queue.hasPendingServerDelete(record.documentId)) { + continue; + } + if (record.localPath !== undefined) { + continue; + } + await this.tryInitialPlacement(record); + } + } + + /** + * Read any swap-marker file left behind by a crash mid-swap and + * roll forward. Called once on startup before the Reconciler + * begins normal passes. Idempotent: with no marker, a no-op. + */ + public async recoverFromInterruptedSwap(): Promise { + let markerPaths: RelativePath[] = []; + try { + markerPaths = await this.findSwapMarkerFiles(); + } catch (e) { + this.logger.error( + `Reconciler: failed to scan for swap markers: ${String(e)}` + ); + return; + } + + for (const markerPath of markerPaths) { + try { + await this.recoverFromOneMarker(markerPath); + } catch (e) { + this.logger.error( + `Reconciler: recovery from ${markerPath} failed: ${String(e)}` + ); + } + } + } + + private collectAllRecords(): DocumentRecord[] { + // Iterate every tracked record — placement-pending ones + // (`localPath === undefined`) included. `allSettledDocuments` + // filters those out, which would render records born from a + // remote create that landed on an occupied slot (no on-disk + // file, no entry in `pendingPlacementContent` either, since the + // wire loop deliberately doesn't buffer their content) invisible + // forever. `pendingPlacementContent` is purely a cache for + // `tryInitialPlacement`'s content fetch — not a record-discovery + // channel. + const out: DocumentRecord[] = []; + for (const record of this.queue.allRecords()) { + out.push(record); + } + + // Best-effort cleanup: drop cached content for docs the queue + // no longer tracks. Previously this happened as a side effect of + // the placement-pending discovery loop; do it explicitly now. + if (this.pendingPlacementContent.size > 0) { + for (const docId of this.pendingPlacementContent.keys()) { + if (this.queue.getDocumentByDocumentId(docId) === undefined) { + this.pendingPlacementContent.delete(docId); + } + } + } + + return out; + } + + private async tryInitialPlacement(record: DocumentRecord): Promise { + const target = record.remoteRelativePath; + + if (this.queue.hasPendingCreateForPath(target)) { + this.logger.debug( + `Reconciler: cannot place ${record.documentId} at ${target} ` + + `— pending local create still claims that path; will retry next pass` + ); + return; + } + + // Slot occupancy: pre-check both the disk and our tracked + // records. Either form of occupancy means we wait — the + // occupant's own reconciliation pass (after their next wire-loop + // step) will move them off this slot. + try { + if (await this.operations.exists(target)) { + this.logger.debug( + `Reconciler: cannot place ${record.documentId} at ${target} ` + + `— slot occupied on disk; will retry next pass` + ); + return; + } + } catch (e) { + this.logger.error( + `Reconciler: existence check failed for ${target}: ${String(e)}` + ); + return; + } + if (this.queue.byLocalPath.get(target) !== undefined) { + this.logger.debug( + `Reconciler: cannot place ${record.documentId} at ${target} ` + + `— slot tracked by another record; will retry next pass` + ); + return; + } + + let content = this.pendingPlacementContent.get(record.documentId); + if (content === undefined) { + try { + content = await this.syncService.getDocumentVersionContent({ + documentId: record.documentId, + vaultUpdateId: record.parentVersionId + }); + } catch (e) { + if (e instanceof SyncResetError) { + this.logger.info( + `Reconciler: content fetch for ${record.documentId} interrupted by sync reset` + ); + return; + } + this.logger.error( + `Reconciler: failed to fetch content for ${record.documentId}: ${String(e)}` + ); + return; + } + } + + try { + await this.operations.create(target, content); + } catch (e) { + if (e instanceof FileNotFoundError) { + this.logger.debug( + `Reconciler: create at ${target} hit FileNotFound (likely parent ` + + `directory race); will retry next pass` + ); + return; + } + if (e instanceof FileAlreadyExistsError) { + this.logger.debug( + `Reconciler: create at ${target} lost TOCTOU race ` + + `(slot occupied between pre-check and write); will retry next pass` + ); + return; + } + this.logger.error( + `Reconciler: create at ${target} failed: ${String(e)}` + ); + return; + } + + try { + await this.queue.setLocalPath(record.documentId, target); + } catch (e) { + this.logger.error( + `Reconciler: setLocalPath after create failed for ${record.documentId}: ${String(e)}` + ); + return; + } + this.pendingPlacementContent.delete(record.documentId); + this.logger.debug( + `Reconciler: placed ${record.documentId} at ${target}` + ); + } + + private async executeMoves(moves: PlannedMove[]): Promise { + // Build a directed graph: each move (record currently at `from`, + // wants to go to `to`) gets an edge to whatever tracked record + // currently holds `to`. A node with no outgoing edge is a leaf + // in the DAG: its target slot is held by no tracked record. If + // the slot is held by an *untracked* file we can't safely + // displace it (no record to relocate); skip those moves and + // let the next pass retry. + const movesByDocId = new Map(); + for (const move of moves) { + movesByDocId.set(move.record.documentId, move); + } + + const skipped = new Set(); + const edges = new Map(); + + for (const move of moves) { + const occupant = this.queue.byLocalPath.get(move.to); + if (occupant === undefined) { + let occupied = false; + try { + occupied = await this.operations.exists(move.to); + } catch (e) { + this.logger.error( + `Reconciler: existence check failed for ${move.to}: ${String(e)}` + ); + skipped.add(move.record.documentId); + continue; + } + if (occupied) { + this.logger.debug( + `Reconciler: move ${move.record.documentId} -> ${move.to} blocked ` + + `by untracked file; will retry next pass` + ); + skipped.add(move.record.documentId); + continue; + } + edges.set(move.record.documentId, null); + } else if (occupant.documentId === move.record.documentId) { + // Self-loop on `to` shouldn't normally happen — we + // skipped records where localPath===remoteRelativePath + // up front. Defensive: nothing to do. + continue; + } else if (movesByDocId.has(occupant.documentId)) { + edges.set(move.record.documentId, occupant.documentId); + } else { + // Occupant is a tracked record that doesn't *want* to + // move (its localPath === its remoteRelativePath). We + // can't dislodge it without orphaning its on-disk + // file; skip and retry. + this.logger.debug( + `Reconciler: move ${move.record.documentId} -> ${move.to} blocked by ` + + `tracked record ${occupant.documentId} which is not moving; ` + + `will retry next pass` + ); + skipped.add(move.record.documentId); + } + } + + // SCC decomposition (Tarjan's algorithm) over the move graph. + const sccs = this.tarjanSccs(edges, skipped); + + // Topo-sort the DAG of SCCs (leaves first). Tarjan emits SCCs + // in reverse topological order — leaves first — which is + // already what we want. + for (const scc of sccs) { + if (scc.length === 1) { + const [docId] = scc; + if (skipped.has(docId)) { + continue; + } + const move = movesByDocId.get(docId); + if (move === undefined) { + continue; + } + // Self-loop check: if the only edge from this node + // points back to itself, treat as a 1-cycle (impossible + // given our up-front filter, but cheap defensiveness). + const target = edges.get(docId); + if (target === docId) { + await this.executeCycle([move]); + } else { + await this.executeSimpleRename(move); + } + } else { + const cycleMoves = scc + .map((id) => movesByDocId.get(id)) + .filter( + (m): m is PlannedMove => + m !== undefined && !skipped.has(m.record.documentId) + ); + if (cycleMoves.length === scc.length) { + await this.executeCycle(cycleMoves); + } else { + // A member of the cycle was skipped — the cycle + // can't be resolved as a unit. Skip the rest; next + // pass tries again with whatever's still relevant. + this.logger.debug( + `Reconciler: cycle of ${scc.length} skipped because a ` + + `member dropped out; will retry next pass` + ); + } + } + } + } + + private async executeSimpleRename(move: PlannedMove): Promise { + // Defense-in-depth: the queue's invariant says + // `record.localPath !== undefined ⇒ byLocalPath.get(record.localPath) === record`. + // If the byLocalPath index disagrees with the record we + // captured when planning, the invariant was violated somewhere + // upstream — the file at `move.from` belongs to a different + // record now and renaming it would clobber that record's + // content. Refuse the move; the next pass re-plans. + const indexed = this.queue.byLocalPath.get(move.from); + if (indexed !== move.record) { + this.logger.warn( + `Reconciler: refusing rename ${move.from} -> ${move.to} for ` + + `${move.record.documentId}: byLocalPath says ${move.from} ` + + `belongs to ${indexed?.documentId ?? ""} ` + + `(invariant violation upstream); skipping` + ); + return; + } + // The target may have been freed by an earlier move in this + // pass (a leaf we processed first). Re-check both source and + // target before committing. + try { + if (!(await this.operations.exists(move.from))) { + this.logger.debug( + `Reconciler: source ${move.from} vanished before rename; skipping` + ); + return; + } + } catch (e) { + this.logger.error( + `Reconciler: existence check failed for ${move.from}: ${String(e)}` + ); + return; + } + try { + if (await this.operations.exists(move.to)) { + if (this.queue.byLocalPath.get(move.to) !== undefined) { + // Slot got reclaimed by a tracked doc mid-pass — + // back off and retry next pass. + this.logger.debug( + `Reconciler: target ${move.to} reclaimed by another record ` + + `mid-pass; skipping` + ); + return; + } + // Untracked file appeared; same reasoning as in + // executeMoves' planning step. Defer. + this.logger.debug( + `Reconciler: target ${move.to} now occupied by untracked file; skipping` + ); + return; + } + } catch (e) { + this.logger.error( + `Reconciler: existence check failed for ${move.to}: ${String(e)}` + ); + return; + } + + try { + await this.operations.move(move.from, move.to); + } catch (e) { + if (e instanceof FileNotFoundError) { + this.logger.debug( + `Reconciler: rename ${move.from} -> ${move.to} hit FileNotFound; ` + + `will retry next pass` + ); + return; + } + if (e instanceof FileAlreadyExistsError) { + this.logger.debug( + `Reconciler: rename ${move.from} -> ${move.to} lost TOCTOU race ` + + `(target reclaimed between pre-check and rename); will retry next pass` + ); + return; + } + this.logger.error( + `Reconciler: rename ${move.from} -> ${move.to} failed: ${String(e)}` + ); + return; + } + + try { + await this.queue.setLocalPath(move.record.documentId, move.to); + } catch (e) { + this.logger.error( + `Reconciler: setLocalPath after rename failed for ${move.record.documentId}: ${String(e)}` + ); + return; + } + this.logger.debug( + `Reconciler: renamed ${move.record.documentId} from ${move.from} to ${move.to}` + ); + } + + private async executeCycle(members: PlannedMove[]): Promise { + // Defense-in-depth: same invariant check as + // `executeSimpleRename` but cycle-wide. If any member's `from` + // slot no longer matches the planned record per byLocalPath, + // abort the whole cycle — partial-cycle progress under a + // shadowed-record race is the worst case (it can shuffle bytes + // between the wrong docs). + for (const member of members) { + const indexed = this.queue.byLocalPath.get(member.from); + if (indexed !== member.record) { + this.logger.warn( + `Reconciler: refusing cycle: byLocalPath says ${member.from} ` + + `belongs to ${indexed?.documentId ?? ""} ` + + `but planned for ${member.record.documentId} ` + + `(invariant violation upstream); skipping cycle` + ); + return; + } + } + // Read every member's bytes first; we'll overwrite the target + // slots with these. All reads happen before any write, so the + // cycle is fully captured in memory before we start mutating + // disk. If any read fails the whole cycle is aborted — + // partial-cycle work is the riskiest case (it can leave docs + // pointing at the wrong content). + const contentByDocId = new Map(); + // We also need the pre-write content of each `to` slot for the + // 3-way merge in `operations.write` — passing the freshly-read + // disk bytes as `expectedContent` makes the merge resolve to a + // clean overwrite (since `expected === current` at write time). + const oldToContentByDocId = new Map(); + try { + for (const member of members) { + contentByDocId.set( + member.record.documentId, + await this.operations.read(member.from) + ); + } + // The `to` of each member is guaranteed to be the `from` of + // some other member (it's a cycle). We've already read all + // those `from`s, so reuse those reads. + const fromToDocId = new Map(); + for (const member of members) { + fromToDocId.set(member.from, member.record.documentId); + } + for (const member of members) { + const sourceDocId = fromToDocId.get(member.to); + if (sourceDocId === undefined) { + throw new Error( + `Reconciler: cycle ${member.record.documentId} -> ${member.to} ` + + `has no member at ${member.to}; graph is not a true cycle` + ); + } + const oldBytes = contentByDocId.get(sourceDocId); + if (oldBytes === undefined) { + throw new Error( + `Reconciler: missing pre-read content for ${sourceDocId}` + ); + } + oldToContentByDocId.set(member.record.documentId, oldBytes); + } + } catch (e) { + this.logger.error( + `Reconciler: cycle pre-read failed: ${String(e)}; aborting cycle` + ); + return; + } + + // Write-ahead marker so a crash mid-swap can be repaired on + // next start. Recovery decides what's been written by hashing + // each `from` slot — anything still matching `expectedHashOnFrom` + // hasn't been overwritten yet. + const legs: SwapLeg[] = []; + try { + for (const member of members) { + const memberContent = contentByDocId.get( + member.record.documentId + ); + if (memberContent === undefined) { + throw new Error( + `Reconciler: cycle member ${member.record.documentId} missing content` + ); + } + legs.push({ + documentId: member.record.documentId, + from: member.from, + to: member.to, + expectedHashOnFrom: await hash(memberContent) + }); + } + } catch (e) { + this.logger.error( + `Reconciler: cycle hashing failed: ${String(e)}; aborting cycle` + ); + return; + } + + const markerUuid = crypto.randomUUID(); + const markerPath = this.markerPathFor(markerUuid); + const markerBytes = new TextEncoder().encode( + JSON.stringify({ uuid: markerUuid, legs } satisfies SwapMarker) + ); + try { + // The marker path embeds a fresh uuid, so a FileAlreadyExistsError + // is statistically impossible here. + await this.operations.create(markerPath, markerBytes); + } catch (e) { + this.logger.error( + `Reconciler: failed to write swap marker ${markerPath}: ${String(e)}; ` + + `aborting cycle` + ); + return; + } + + // Now apply the writes. Each leg overwrites the bytes at `to` + // with the bytes that were at the cycle predecessor's `from`. + // We pass the freshly-read pre-write content as + // `expectedContent` so the 3-way merge inside `operations.write` + // becomes a clean overwrite (no concurrent edits to merge with). + // `operations.write` registers `expectUpdate` itself, so the + // watcher swallows each leg's modify event. + const writtenLegs: SwapLeg[] = []; + for (const leg of legs) { + const newBytes = contentByDocId.get(leg.documentId); + const oldBytes = oldToContentByDocId.get(leg.documentId); + if (newBytes === undefined || oldBytes === undefined) { + this.logger.error( + `Reconciler: cycle leg ${leg.from} -> ${leg.to} missing ` + + `content; aborting cycle` + ); + return; + } + try { + await this.operations.write(leg.to, oldBytes, newBytes); + writtenLegs.push(leg); + } catch (e) { + this.logger.error( + `Reconciler: cycle leg ${leg.from} -> ${leg.to} write failed: ` + + `${String(e)}; cycle is now in a half-applied state — recovery ` + + `marker ${markerPath} will roll forward on next start` + ); + // Don't delete the marker — it's load-bearing for + // recovery. The records' localPath assignments are + // intentionally NOT updated for the failed leg or any + // subsequent leg, so the next reconciler pass will + // observe the same situation and re-plan. + return; + } + } + + // Re-key records to their new localPaths. We do this AFTER + // all writes succeeded; if a setLocalPath fails partway the + // marker is still on disk and recovery covers it. + for (const leg of writtenLegs) { + try { + await this.queue.setLocalPath(leg.documentId, leg.to); + } catch (e) { + this.logger.error( + `Reconciler: setLocalPath after cycle write failed for ` + + `${leg.documentId}: ${String(e)}` + ); + } + } + + try { + await this.operations.delete(markerPath); + } catch (e) { + this.logger.warn( + `Reconciler: failed to delete swap marker ${markerPath}: ${String(e)}; ` + + `next start's recovery will see it but find every leg already applied` + ); + } + this.logger.debug( + `Reconciler: completed cycle of ${members.length} members` + ); + } + + private async findSwapMarkerFiles(): Promise { + let entries: RelativePath[] = []; + try { + entries = + await this.operations.listFilesRecursively(SWAP_MARKER_DIR); + } catch (e) { + if (e instanceof FileNotFoundError) { + return []; + } + throw e; + } + return entries.filter((p) => { + const name = p.split("/").pop() ?? ""; + return ( + name.startsWith(SWAP_MARKER_PREFIX) && + name.endsWith(SWAP_MARKER_SUFFIX) + ); + }); + } + + private async recoverFromOneMarker( + markerPath: RelativePath + ): Promise { + const markerBytes = await this.operations.read(markerPath); + const marker = this.parseSwapMarker(markerBytes); + if (marker === undefined) { + this.logger.error( + `Reconciler: corrupt swap marker ${markerPath}; deleting` + ); + try { + await this.operations.delete(markerPath); + } catch (deleteErr) { + this.logger.error( + `Reconciler: failed to delete corrupt marker ${markerPath}: ${String(deleteErr)}` + ); + } + return; + } + + this.logger.info( + `Reconciler: recovering from interrupted swap ${marker.uuid} ` + + `with ${marker.legs.length} legs` + ); + + // Recovery rules per leg: + // - hash(from) === expectedHashOnFrom — the swap was + // interrupted BEFORE this leg overwrote `to`. We need to + // write the source bytes to `to` AND update the record. + // - hash(from) differs (or `from` is missing) — this leg + // already ran (someone else's bytes are now at `from`, + // which means the cycle predecessor's leg ran too). Mark + // as already-applied for record bookkeeping. + for (const leg of marker.legs) { + let needsApply = false; + try { + if (await this.operations.exists(leg.from)) { + const fromBytes = await this.operations.read(leg.from); + const fromHash = await hash(fromBytes); + needsApply = fromHash === leg.expectedHashOnFrom; + } + } catch (e) { + this.logger.error( + `Reconciler: hash check during recovery for ${leg.from} failed: ` + + `${String(e)}; skipping leg` + ); + continue; + } + + if (needsApply) { + try { + const sourceBytes = await this.operations.read(leg.from); + // We don't know what (if anything) is at `to`. If + // it exists we want to overwrite. operations.write + // refuses if the file doesn't exist, so: + if (await this.operations.exists(leg.to)) { + const currentToBytes = await this.operations.read( + leg.to + ); + await this.operations.write( + leg.to, + currentToBytes, + sourceBytes + ); + } else { + await this.operations.create(leg.to, sourceBytes); + } + } catch (e) { + this.logger.error( + `Reconciler: applying recovery leg ${leg.from} -> ${leg.to} ` + + `failed: ${String(e)}` + ); + continue; + } + } + + // Whether we just applied or it was already applied, + // update the record so its localPath matches the + // post-swap state. + try { + const record = this.queue.getDocumentByDocumentId( + leg.documentId + ); + if (record !== undefined) { + await this.queue.setLocalPath(leg.documentId, leg.to); + } + } catch (e) { + this.logger.error( + `Reconciler: setLocalPath during recovery for ${leg.documentId} ` + + `failed: ${String(e)}` + ); + } + } + + try { + await this.operations.delete(markerPath); + } catch (e) { + this.logger.error( + `Reconciler: failed to delete swap marker ${markerPath} after recovery: ` + + String(e) + ); + } + } + + private markerPathFor(uuid: string): RelativePath { + return `${SWAP_MARKER_DIR}/${SWAP_MARKER_PREFIX}${uuid}${SWAP_MARKER_SUFFIX}`; + } + + /** + * SCC decomposition over the move graph, returning components in + * leaves-first order (so the caller can process leaves before + * cycles, freeing target slots progressively). + * + * Exploits the fact that this is a *functional graph*: each node + * has at most one outgoing edge (the doc whose slot we want). So + * every non-trivial SCC is a single simple cycle; any non-cycle + * node is its own singleton component. To detect cycles, walk + * from each unvisited node following edges and mark the path; if + * we hit a node on the current path, the segment from that node + * to the current frontier is a cycle. If we hit a visited node + * not on the current path (or a null), we just chain leaves. + * + * Skipped nodes are treated as having no outgoing edge (their + * targets are blocked). + */ + private tarjanSccs( + edges: Map, + skipped: Set + ): DocumentId[][] { + const allNodes = new Set(); + for (const id of edges.keys()) { + allNodes.add(id); + } + for (const id of skipped) { + allNodes.add(id); + } + + const visited = new Set(); + const componentOf = new Map(); + const sccs: DocumentId[][] = []; + + const edgeOf = (node: DocumentId): DocumentId | null => { + if (skipped.has(node)) { + return null; + } + return edges.get(node) ?? null; + }; + + for (const root of allNodes) { + if (visited.has(root)) { + continue; + } + + // Walk forward marking the path until we hit a visited node + // or a null. `pathIndex` lets us detect "did we land back on + // our own path". + const path: DocumentId[] = []; + const pathIndex = new Map(); + let cursor: DocumentId | null = root; + + while ( + cursor !== null && + !visited.has(cursor) && + !pathIndex.has(cursor) + ) { + pathIndex.set(cursor, path.length); + path.push(cursor); + cursor = edgeOf(cursor); + } + + // We stopped because either (a) cursor is null, (b) cursor + // is already visited (chain merges into an earlier-explored + // subgraph — every node on `path` is its own singleton + // component), or (c) cursor is on `path` itself — the + // suffix of `path` from `pathIndex.get(cursor)` onward is a + // cycle; the prefix is a tail of singletons. + let cycleStart = path.length; + if (cursor !== null) { + const idx = pathIndex.get(cursor); + if (idx !== undefined) { + cycleStart = idx; + } + } + + // Singletons in `path[0..cycleStart)`. Emit them in + // leaves-first order: the deepest (closest to the cycle or + // chain-end) is the leaf in the DAG of SCCs, so we emit + // from the END of the prefix backward to get topo order + // (children before parents). + for (let i = cycleStart - 1; i >= 0; i--) { + const node = path[i]; + visited.add(node); + const componentId = sccs.length; + componentOf.set(node, componentId); + sccs.push([node]); + } + // Cycle (if any). + if (cycleStart < path.length) { + const cycleNodes = path.slice(cycleStart); + const componentId = sccs.length; + for (const node of cycleNodes) { + visited.add(node); + componentOf.set(node, componentId); + } + sccs.push(cycleNodes); + } + } + + // The order produced above is mostly leaves-first per chain, + // but chains explored later may include singletons that merge + // into earlier-emitted components. Re-sort by (component points + // to anything? if so, target's component must come first). With + // a functional graph this is equivalent to emitting any node + // before the node it points to. Do a final stable topo sort. + const componentTarget = new Map(); + for (let cid = 0; cid < sccs.length; cid++) { + // Pick a representative; in a functional-graph SCC, every + // node's edge points either inside the SCC (cycle) or to + // exactly one other SCC (singleton chain). For singletons + // the representative's edge gives us the parent component. + const [rep] = sccs[cid]; + const edge = edgeOf(rep); + if (edge === null) { + componentTarget.set(cid, null); + } else { + const targetCid = componentOf.get(edge); + if (targetCid === undefined || targetCid === cid) { + componentTarget.set(cid, null); + } else { + componentTarget.set(cid, targetCid); + } + } + } + + // Topo-sort: emit a component only after its target has been + // emitted. + const emitted = new Set(); + const ordered: DocumentId[][] = []; + const tryEmit = (cid: number, stack: Set): void => { + if (emitted.has(cid)) { + return; + } + if (stack.has(cid)) { + return; + } // shouldn't happen given functional-graph SCC contraction + stack.add(cid); + const target = componentTarget.get(cid) ?? null; + if (target !== null) { + tryEmit(target, stack); + } + stack.delete(cid); + if (!emitted.has(cid)) { + emitted.add(cid); + ordered.push(sccs[cid]); + } + }; + for (let cid = 0; cid < sccs.length; cid++) { + tryEmit(cid, new Set()); + } + + return ordered; + } + + private parseSwapMarker(bytes: Uint8Array): SwapMarker | undefined { + // Marker files are written by us (`writeSwapMarker`) and only + // consumed here on startup recovery; the shape is closed. Treat + // a parse failure as a corrupt marker. + const parsed = tryParseSwapMarker(bytes); + if ( + parsed === undefined || + typeof parsed.uuid !== "string" || + !Array.isArray(parsed.legs) + ) { + return undefined; + } + return parsed; + } +} diff --git a/frontend/sync-client/src/sync-operations/sync-event-queue.test.ts b/frontend/sync-client/src/sync-operations/sync-event-queue.test.ts new file mode 100644 index 00000000..d2676011 --- /dev/null +++ b/frontend/sync-client/src/sync-operations/sync-event-queue.test.ts @@ -0,0 +1,907 @@ +import { describe, it } from "node:test"; +import assert from "node:assert"; +import { + STORED_STATE_SCHEMA_VERSION, + SyncEventQueue +} from "./sync-event-queue"; +import { Settings } from "../persistence/settings"; +import { Logger } from "../tracing/logger"; +import type { DocumentVersionWithoutContent } from "../services/types/DocumentVersionWithoutContent"; +import { SyncEventType } from "./types"; +import type { DocumentRecord, RelativePath, StoredSyncState } from "./types"; + +interface QueueHarness { + queue: SyncEventQueue; + settings: Settings; + saveCalls: StoredSyncState[]; +} + +function createHarness( + options: { + ignorePatterns?: string[]; + initialState?: Partial; + omitSchemaVersion?: boolean; + } = {} +): QueueHarness { + const logger = new Logger(); + const settings = new Settings( + logger, + { ignorePatterns: options.ignorePatterns ?? [] }, + async () => { + /* no-op */ + } + ); + + const saveCalls: StoredSyncState[] = []; + const initialState: Partial | undefined = + options.initialState === undefined && options.omitSchemaVersion !== true + ? { schemaVersion: STORED_STATE_SCHEMA_VERSION } + : options.initialState; + + const queue = new SyncEventQueue( + settings, + logger, + initialState, + async (data) => { + saveCalls.push(data); + } + ); + return { queue, settings, saveCalls }; +} + +function createQueue(ignorePatterns: string[] = []): SyncEventQueue { + return createHarness({ ignorePatterns }).queue; +} + +function fakeRemoteVersion( + documentId: string, + overrides: Partial = {} +): DocumentVersionWithoutContent { + return { + vaultUpdateId: 1, + documentId, + relativePath: `${documentId}.md`, + updatedDate: "2026-01-01", + isDeleted: false, + userId: "user", + deviceId: "device", + contentSize: 100, + isNewFile: true, + ...overrides + }; +} + +function fakeRecord( + documentId: string, + overrides: Partial = {} +): DocumentRecord { + const path = `${documentId.toLowerCase()}.md`; + return { + documentId, + parentVersionId: 1, + remoteHash: `hash-${documentId}`, + remoteRelativePath: path, + localPath: path, + ...overrides + }; +} + +describe("SyncEventQueue", () => { + it("returns enqueued events in FIFO order with no coalescing", async () => { + const queue = createQueue(); + await queue.upsertRecord(fakeRecord("A")); + + await queue.enqueue({ type: SyncEventType.LocalCreate, path: "b.md" }); + await queue.enqueue({ type: SyncEventType.LocalCreate, path: "c.md" }); + await queue.enqueue({ type: SyncEventType.LocalDelete, path: "a.md" }); + + const first = await queue.next(); + assert.strictEqual(first?.type, SyncEventType.LocalCreate); + + const second = await queue.next(); + assert.strictEqual(second?.type, SyncEventType.LocalCreate); + + const third = await queue.next(); + assert.strictEqual(third?.type, SyncEventType.LocalDelete); + assert.strictEqual(third.documentId, "A"); + + assert.strictEqual(await queue.next(), undefined); + }); + + it("create events are returned FIFO", async () => { + const queue = createQueue(); + await queue.enqueue({ type: SyncEventType.LocalCreate, path: "a.md" }); + await queue.enqueue({ type: SyncEventType.LocalCreate, path: "b.md" }); + + const first = await queue.next(); + assert.strictEqual(first?.type, SyncEventType.LocalCreate); + assert.strictEqual(first.path, "a.md"); + + const second = await queue.next(); + assert.strictEqual(second?.type, SyncEventType.LocalCreate); + assert.strictEqual(second.path, "b.md"); + }); + + it("delete resolves documentId from path", async () => { + const queue = createQueue(); + await queue.upsertRecord(fakeRecord("A")); + + await queue.enqueue({ type: SyncEventType.LocalDelete, path: "a.md" }); + + const event = await queue.next(); + assert.strictEqual(event?.type, SyncEventType.LocalDelete); + assert.strictEqual(event.documentId, "A"); + }); + + it("delete for unknown path is silently ignored", async () => { + const queue = createQueue(); + await queue.enqueue({ + type: SyncEventType.LocalDelete, + path: "unknown.md" + }); + assert.strictEqual(queue.pendingUpdateCount, 0); + }); + + it("delete clears the localPath of the affected record", async () => { + const queue = createQueue(); + await queue.upsertRecord(fakeRecord("A")); + + await queue.enqueue({ type: SyncEventType.LocalDelete, path: "a.md" }); + + const record = queue.getDocumentByDocumentId("A"); + assert.ok(record !== undefined); + assert.strictEqual(record.localPath, undefined); + assert.strictEqual( + queue.getRecordByLocalPath("a.md" as RelativePath), + undefined + ); + }); + + it("document store CRUD operations work correctly", async () => { + const queue = createQueue(); + + assert.strictEqual( + queue.getRecordByLocalPath("a.md" as RelativePath), + undefined + ); + assert.strictEqual(queue.syncedDocumentCount, 0); + + await queue.upsertRecord(fakeRecord("A")); + assert.strictEqual(queue.syncedDocumentCount, 1); + + const settled = queue.getRecordByLocalPath("a.md" as RelativePath); + assert.strictEqual(settled?.documentId, "A"); + assert.strictEqual(settled.localPath, "a.md"); + assert.strictEqual(settled.remoteRelativePath, "a.md"); + + const found = queue.getDocumentByDocumentId("A"); + assert.strictEqual(found?.localPath, "a.md"); + assert.strictEqual(found.documentId, "A"); + + await queue.removeDocumentById("A"); + assert.strictEqual(queue.syncedDocumentCount, 0); + assert.strictEqual( + queue.getRecordByLocalPath("a.md" as RelativePath), + undefined + ); + assert.strictEqual(queue.getDocumentByDocumentId("A"), undefined); + }); + + it("LocalUpdate with oldPath moves the document on disk", async () => { + const queue = createQueue(); + await queue.upsertRecord(fakeRecord("A")); + + await queue.enqueue({ + type: SyncEventType.LocalUpdate, + path: "b.md", + oldPath: "a.md" + }); + + assert.strictEqual( + queue.getRecordByLocalPath("a.md" as RelativePath), + undefined + ); + const moved = queue.getRecordByLocalPath("b.md" as RelativePath); + assert.strictEqual(moved?.documentId, "A"); + assert.strictEqual(moved.localPath, "b.md"); + + // The doc's remoteRelativePath is owned by the wire loop, not the + // watcher path — a local rename does not move the server-side path. + assert.strictEqual(moved.remoteRelativePath, "a.md"); + }); + + it("LocalUpdate rename onto a tracked slot enqueues a delete for the displaced doc", async () => { + const queue = createQueue(); + await queue.upsertRecord(fakeRecord("A")); + await queue.upsertRecord(fakeRecord("B")); + + // User renames a.md onto b.md, clobbering b.md on disk. + await queue.enqueue({ + type: SyncEventType.LocalUpdate, + path: "b.md", + oldPath: "a.md" + }); + + // Doc A now lives at b.md. + const aRecord = queue.getDocumentByDocumentId("A"); + assert.strictEqual(aRecord?.localPath, "b.md"); + const slot = queue.getRecordByLocalPath("b.md" as RelativePath); + assert.strictEqual(slot?.documentId, "A"); + + // Doc B has no local file anymore (its bytes were overwritten). + const bRecord = queue.getDocumentByDocumentId("B"); + assert.strictEqual(bRecord?.localPath, undefined); + + // Two events should be queued: the LocalDelete for B, then the + // LocalUpdate for A (push order in `enqueue`). + assert.strictEqual(queue.pendingUpdateCount, 2); + + const first = await queue.next(); + assert.strictEqual(first?.type, SyncEventType.LocalDelete); + assert.strictEqual(first.documentId, "B"); + assert.strictEqual(first.path, "b.md"); + + const second = await queue.next(); + assert.strictEqual(second?.type, SyncEventType.LocalUpdate); + assert.strictEqual(second.documentId, "A"); + assert.strictEqual(second.path, "b.md"); + assert.strictEqual(second.isUserRename, true); + }); + + it("settled record owns a path over a stale pending create", async () => { + const queue = createQueue(); + await queue.upsertRecord(fakeRecord("A", { localPath: "b.md" })); + + await queue.enqueue({ type: SyncEventType.LocalCreate, path: "b.md" }); + await queue.enqueue({ + type: SyncEventType.LocalUpdate, + path: "c.md", + oldPath: "b.md" + }); + + const aRecord = queue.getDocumentByDocumentId("A"); + assert.strictEqual(aRecord?.localPath, "c.md"); + assert.strictEqual( + queue.getRecordByLocalPath("b.md" as RelativePath), + undefined + ); + assert.strictEqual( + queue.getRecordByLocalPath("c.md" as RelativePath)?.documentId, + "A" + ); + + const create = await queue.next(); + assert.strictEqual(create?.type, SyncEventType.LocalCreate); + assert.strictEqual(create.path, "b.md"); + + const update = await queue.next(); + assert.strictEqual(update?.type, SyncEventType.LocalUpdate); + assert.strictEqual(update.documentId, "A"); + assert.strictEqual(update.path, "c.md"); + }); + + it("byLocalPath stays consistent across upsertRecord, setLocalPath, and rename", async () => { + const queue = createQueue(); + + await queue.upsertRecord(fakeRecord("A")); + assert.strictEqual(queue.byLocalPath.size, 1); + assert.strictEqual( + queue.byLocalPath.get("a.md" as RelativePath)?.documentId, + "A" + ); + + // upsertRecord on an existing record with a non-undefined + // localPath does NOT rewrite localPath. The watcher path and the + // reconciler are the only authorities on localPath of an + // already-placed record; letting the wire loop re-key here would + // race a user rename that landed during an HTTP roundtrip. + await queue.upsertRecord( + fakeRecord("A", { localPath: "renamed.md" as RelativePath }) + ); + assert.strictEqual(queue.byLocalPath.size, 1); + assert.strictEqual( + queue.byLocalPath.get("a.md" as RelativePath)?.documentId, + "A" + ); + assert.strictEqual( + queue.byLocalPath.get("renamed.md" as RelativePath), + undefined + ); + assert.strictEqual(queue.getDocumentByDocumentId("A")?.localPath, "a.md"); + + // setLocalPath does re-key — it's the explicit path-mutation API. + await queue.setLocalPath("A", "later.md" as RelativePath); + assert.strictEqual(queue.byLocalPath.size, 1); + assert.strictEqual( + queue.byLocalPath.get("a.md" as RelativePath), + undefined + ); + assert.strictEqual( + queue.byLocalPath.get("later.md" as RelativePath)?.documentId, + "A" + ); + + // setLocalPath to undefined should drop the entry. + await queue.setLocalPath("A", undefined); + assert.strictEqual(queue.byLocalPath.size, 0); + assert.strictEqual( + queue.byLocalPath.get("later.md" as RelativePath), + undefined + ); + + // The record is still tracked by docId. + assert.strictEqual( + queue.getDocumentByDocumentId("A")?.localPath, + undefined + ); + }); + + it("upsertRecord installs localPath only when the existing record has none (placement-pending → placed)", async () => { + const queue = createQueue(); + + // Same-docId-collapse shape: a placement-pending record (created + // earlier by a remote-create handler when the slot was occupied) + // gets resolved by a LocalCreate that returns the same docId. + // The watcher hasn't touched localPath since the record is + // placement-pending, so installing the now-known path is correct. + await queue.upsertRecord(fakeRecord("A", { localPath: undefined })); + assert.strictEqual(queue.byLocalPath.size, 0); + + await queue.upsertRecord( + fakeRecord("A", { localPath: "fresh.md" as RelativePath }) + ); + assert.strictEqual(queue.byLocalPath.size, 1); + assert.strictEqual( + queue.byLocalPath.get("fresh.md" as RelativePath)?.documentId, + "A" + ); + assert.strictEqual( + queue.getDocumentByDocumentId("A")?.localPath, + "fresh.md" + ); + }); + + it("upsertRecord ignores stale localPath from the wire loop after a watcher rename", async () => { + const queue = createQueue(); + await queue.upsertRecord(fakeRecord("A")); + + // Watcher renames a.md -> renamed.md while the wire loop is + // mid-roundtrip. The wire loop captured an earlier snapshot of + // localPath and now tries to write it back through upsertRecord. + await queue.enqueue({ + type: SyncEventType.LocalUpdate, + path: "renamed.md", + oldPath: "a.md" + }); + assert.strictEqual( + queue.getDocumentByDocumentId("A")?.localPath, + "renamed.md" + ); + + await queue.upsertRecord( + fakeRecord("A", { + parentVersionId: 2, + remoteRelativePath: "a.md", + remoteHash: "hash-A-v2", + localPath: "a.md" as RelativePath + }) + ); + + // The watcher's rename wins: localPath stays at renamed.md. + const record = queue.getDocumentByDocumentId("A"); + assert.strictEqual(record?.localPath, "renamed.md"); + assert.strictEqual(record.parentVersionId, 2); + assert.strictEqual(record.remoteRelativePath, "a.md"); + assert.strictEqual(record.remoteHash, "hash-A-v2"); + assert.strictEqual( + queue.byLocalPath.get("renamed.md" as RelativePath)?.documentId, + "A" + ); + assert.strictEqual( + queue.byLocalPath.get("a.md" as RelativePath), + undefined + ); + }); + + it("create can be re-enqueued after being dequeued", async () => { + const queue = createQueue(); + await queue.enqueue({ type: SyncEventType.LocalCreate, path: "a.md" }); + await queue.next(); + + await queue.enqueue({ type: SyncEventType.LocalCreate, path: "a.md" }); + assert.strictEqual(queue.pendingUpdateCount, 1); + }); + + it("silently ignores create events matching ignore patterns", async () => { + const queue = createQueue(["*.tmp", ".hidden/**"]); + + await queue.enqueue({ + type: SyncEventType.LocalCreate, + path: "scratch.tmp" + }); + await queue.enqueue({ + type: SyncEventType.LocalCreate, + path: ".hidden/secret.md" + }); + assert.strictEqual(queue.pendingUpdateCount, 0); + + await queue.enqueue({ + type: SyncEventType.LocalCreate, + path: "notes-new.md" + }); + assert.strictEqual(queue.pendingUpdateCount, 1); + + await queue.enqueue({ + type: SyncEventType.RemoteChange, + remoteVersion: fakeRemoteVersion("N") + }); + assert.strictEqual(queue.pendingUpdateCount, 2); + }); + + it("addInternalIgnorePattern hides paths from enqueue and survives settings reload", async () => { + const harness = createHarness({ ignorePatterns: ["*.tmp"] }); + const { queue, settings } = harness; + + queue.addInternalIgnorePattern(".vaultlink/**"); + + await queue.enqueue({ + type: SyncEventType.LocalCreate, + path: ".vaultlink/swap" + }); + assert.strictEqual(queue.pendingUpdateCount, 0); + + // User-pattern matching still works alongside the internal pattern. + await queue.enqueue({ + type: SyncEventType.LocalCreate, + path: "scratch.tmp" + }); + assert.strictEqual(queue.pendingUpdateCount, 0); + + // Settings reload must not forget the internal pattern. + await settings.setSettings({ ignorePatterns: ["*.bak"] }); + + await queue.enqueue({ + type: SyncEventType.LocalCreate, + path: ".vaultlink/another" + }); + assert.strictEqual(queue.pendingUpdateCount, 0); + + // The new user pattern took effect. + await queue.enqueue({ + type: SyncEventType.LocalCreate, + path: "old.bak" + }); + assert.strictEqual(queue.pendingUpdateCount, 0); + + // And paths outside both pattern sets still pass through. + await queue.enqueue({ + type: SyncEventType.LocalCreate, + path: "notes.md" + }); + assert.strictEqual(queue.pendingUpdateCount, 1); + }); + + it("clearPending removes events but keeps documents", async () => { + const queue = createQueue(); + await queue.upsertRecord(fakeRecord("A")); + await queue.enqueue({ type: SyncEventType.LocalCreate, path: "b.md" }); + await queue.enqueue({ type: SyncEventType.LocalCreate, path: "c.md" }); + + assert.strictEqual(queue.pendingUpdateCount, 2); + + queue.clearPending(); + + assert.strictEqual(queue.pendingUpdateCount, 0); + assert.strictEqual(queue.syncedDocumentCount, 1); + assert.strictEqual( + queue.getRecordByLocalPath("a.md" as RelativePath)?.documentId, + "A" + ); + }); + + it("allSettledDocuments returns all tracked documents that have a localPath", async () => { + const queue = createQueue(); + await queue.upsertRecord(fakeRecord("A")); + await queue.upsertRecord(fakeRecord("B")); + // A doc with no local file (e.g. a remote create whose slot was + // occupied) should not appear in the localPath-keyed view. + await queue.upsertRecord(fakeRecord("C", { localPath: undefined })); + + const docs = queue.allSettledDocuments(); + assert.strictEqual(docs.size, 2); + const paths = Array.from(docs.keys()).sort(); + assert.deepStrictEqual(paths, ["a.md", "b.md"]); + }); + + it("loads initial state from persistence", () => { + const harness = createHarness({ + initialState: { + schemaVersion: STORED_STATE_SCHEMA_VERSION, + documents: [ + fakeRecord("A", { parentVersionId: 5 }), + fakeRecord("B", { parentVersionId: 3 }) + ], + lastSeenUpdateId: 4 + } + }); + const { queue } = harness; + + assert.strictEqual(queue.syncedDocumentCount, 2); + assert.strictEqual( + queue.getRecordByLocalPath("a.md" as RelativePath)?.documentId, + "A" + ); + assert.strictEqual( + queue.getRecordByLocalPath("b.md" as RelativePath)?.documentId, + "B" + ); + assert.strictEqual(queue.lastSeenUpdateId, 4); + }); + + it("constructor with mismatched schema version wipes state and saves the new version", () => { + const harness = createHarness({ + initialState: { + schemaVersion: 0, + documents: [fakeRecord("A"), fakeRecord("B")], + lastSeenUpdateId: 7 + } + }); + + // Persisted documents and watermark were discarded. + assert.strictEqual(harness.queue.syncedDocumentCount, 0); + assert.strictEqual(harness.queue.lastSeenUpdateId, 0); + + // The constructor scheduled a save (don't await — fire-and-forget), + // but we synchronously enqueued it so it should have landed by now. + // The recorded save uses the current schema version. + assert.ok(harness.saveCalls.length >= 1); + const last = harness.saveCalls[harness.saveCalls.length - 1]; + assert.strictEqual(last.schemaVersion, STORED_STATE_SCHEMA_VERSION); + assert.deepStrictEqual(last.documents, []); + assert.strictEqual(last.lastSeenUpdateId, 0); + }); + + it("constructor with missing schema version also wipes state", () => { + const harness = createHarness({ + initialState: { + documents: [fakeRecord("A")], + lastSeenUpdateId: 3 + } + }); + + assert.strictEqual(harness.queue.syncedDocumentCount, 0); + assert.strictEqual(harness.queue.lastSeenUpdateId, 0); + assert.ok(harness.saveCalls.length >= 1); + assert.strictEqual( + harness.saveCalls[harness.saveCalls.length - 1].schemaVersion, + STORED_STATE_SCHEMA_VERSION + ); + }); + + it("resolveCreate settles the document and resolves the create promise", async () => { + const queue = createQueue(); + + await queue.enqueue({ type: SyncEventType.LocalCreate, path: "a.md" }); + + const event = await queue.next(); // dequeue the create + assert.ok(event?.type === SyncEventType.LocalCreate); + const createPromise = event.resolvers.promise; + + await queue.resolveCreate( + event, + fakeRecord("DOC-1", { + parentVersionId: 5, + localPath: "a.md" as RelativePath, + remoteRelativePath: "a.md" as RelativePath + }) + ); + + // Document is now settled + assert.strictEqual( + queue.getRecordByLocalPath("a.md" as RelativePath)?.documentId, + "DOC-1" + ); + + // Promise was resolved + assert.strictEqual(await createPromise, "DOC-1"); + }); + + it("delete collapses a pending create that has not started processing", async () => { + const queue = createQueue(); + + await queue.enqueue({ type: SyncEventType.LocalCreate, path: "a.md" }); + const create = queue.peekFront(); + assert.ok(create?.type === SyncEventType.LocalCreate); + + await queue.enqueue({ type: SyncEventType.LocalDelete, path: "a.md" }); + + assert.strictEqual(queue.pendingUpdateCount, 0); + assert.strictEqual(await queue.next(), undefined); + await assert.rejects(create.resolvers.promise, /cancelled/); + }); + + it("resolveCreate does not claim a localPath after an in-flight pending create was deleted", async () => { + const queue = createQueue(); + + await queue.enqueue({ type: SyncEventType.LocalCreate, path: "a.md" }); + const create = queue.peekFront(); + assert.ok(create?.type === SyncEventType.LocalCreate); + create.isProcessing = true; + + await queue.enqueue({ type: SyncEventType.LocalDelete, path: "a.md" }); + + await queue.resolveCreate( + create, + fakeRecord("DOC-1", { + localPath: "a.md" as RelativePath, + remoteRelativePath: "a.md" as RelativePath + }) + ); + + assert.strictEqual( + queue.getDocumentByDocumentId("DOC-1")?.localPath, + undefined + ); + assert.strictEqual( + queue.getRecordByLocalPath("a.md" as RelativePath), + undefined + ); + + const deleteEvent = await queue.next(); + assert.strictEqual(deleteEvent?.type, SyncEventType.LocalDelete); + assert.strictEqual(deleteEvent.documentId, "DOC-1"); + }); + + it("resolveCreate only clears localPath for a pending delete of that path", async () => { + const queue = createQueue(); + + await queue.enqueue({ + type: SyncEventType.LocalCreate, + path: "old.md" + }); + const create = queue.peekFront(); + assert.ok(create?.type === SyncEventType.LocalCreate); + create.isProcessing = true; + + await queue.enqueue({ + type: SyncEventType.LocalDelete, + path: "old.md" + }); + + await queue.resolveCreate( + create, + fakeRecord("DOC-1", { + localPath: "new.md" as RelativePath, + remoteRelativePath: "new.md" as RelativePath + }) + ); + + assert.strictEqual( + queue.getDocumentByDocumentId("DOC-1")?.localPath, + "new.md" + ); + assert.strictEqual( + queue.getRecordByLocalPath("new.md" as RelativePath)?.documentId, + "DOC-1" + ); + + const deleteEvent = await queue.next(); + assert.strictEqual(deleteEvent?.type, SyncEventType.LocalDelete); + assert.strictEqual(deleteEvent.documentId, "DOC-1"); + assert.strictEqual(deleteEvent.path, "old.md"); + }); + + it("pending create owns a same-path delete over a stale deleting record", async () => { + const queue = createQueue(); + await queue.upsertRecord( + fakeRecord("OLD", { localPath: "a.md" as RelativePath }) + ); + queue.markServerDeletePending("OLD"); + + await queue.enqueue({ type: SyncEventType.LocalCreate, path: "a.md" }); + const create = queue.peekFront(); + assert.ok(create?.type === SyncEventType.LocalCreate); + create.isProcessing = true; + + await queue.enqueue({ type: SyncEventType.LocalDelete, path: "a.md" }); + + assert.strictEqual( + queue.getDocumentByDocumentId("OLD")?.localPath, + undefined + ); + assert.strictEqual( + queue.getRecordByLocalPath("a.md" as RelativePath), + undefined + ); + + const createEvent = await queue.next(); + assert.strictEqual(createEvent, create); + + const deleteEvent = await queue.next(); + assert.strictEqual(deleteEvent?.type, SyncEventType.LocalDelete); + assert.strictEqual(deleteEvent.documentId, create.resolvers.promise); + }); + + it("rename of a queued create drains same-path deletes first", async () => { + const queue = createQueue(); + await queue.upsertRecord( + fakeRecord("OLD", { localPath: "target.md" as RelativePath }) + ); + + await queue.enqueue({ + type: SyncEventType.LocalCreate, + path: "source.md" + }); + const create = queue.peekFront(); + assert.ok(create?.type === SyncEventType.LocalCreate); + + await queue.enqueue({ + type: SyncEventType.LocalDelete, + path: "target.md" + }); + await queue.enqueue({ + type: SyncEventType.LocalUpdate, + oldPath: "source.md", + path: "target.md" + }); + + const deleteEvent = await queue.next(); + assert.strictEqual(deleteEvent?.type, SyncEventType.LocalDelete); + assert.strictEqual(deleteEvent.documentId, "OLD"); + assert.strictEqual(deleteEvent.path, "target.md"); + + const createEvent = await queue.next(); + assert.strictEqual(createEvent, create); + assert.strictEqual(createEvent.path, "target.md"); + + const updateEvent = await queue.next(); + assert.strictEqual(updateEvent?.type, SyncEventType.LocalUpdate); + assert.strictEqual(updateEvent.documentId, create.resolvers.promise); + assert.strictEqual(updateEvent.path, "target.md"); + }); + + it("findLatestCreateForPath returns the pending create", async () => { + const queue = createQueue(); + + await queue.enqueue({ type: SyncEventType.LocalCreate, path: "a.md" }); + await queue.enqueue({ type: SyncEventType.LocalCreate, path: "b.md" }); + + const found = queue.findLatestCreateForPath("a.md" as RelativePath); + assert.ok(found !== undefined); + assert.strictEqual(found.path, "a.md"); + + const missing = queue.findLatestCreateForPath("c.md" as RelativePath); + assert.strictEqual(missing, undefined); + }); + + it("hasPendingEventsForPath reflects pending events", async () => { + const queue = createQueue(); + await queue.upsertRecord(fakeRecord("A")); + + assert.strictEqual( + queue.hasPendingEventsForPath("a.md" as RelativePath), + false + ); + + await queue.enqueue({ type: SyncEventType.LocalDelete, path: "a.md" }); + // After a delete the localPath is cleared; an unknown path is treated + // as "must be pending creation", so this still returns true. + assert.strictEqual( + queue.hasPendingEventsForPath("a.md" as RelativePath), + true + ); + }); + + it("setLocalPath displaces a previous holder of the same path", async () => { + const queue = createQueue(); + await queue.upsertRecord(fakeRecord("A")); + await queue.upsertRecord( + fakeRecord("B", { localPath: "b.md" as RelativePath }) + ); + + // Move B onto a.md — the slot already held by A. The invariant + // requires A's localPath to be cleared (placement-pending), + // and byLocalPath["a.md"] === B. + await queue.setLocalPath("B", "a.md" as RelativePath); + + const a = queue.getDocumentByDocumentId("A"); + const b = queue.getDocumentByDocumentId("B"); + assert.strictEqual(a?.localPath, undefined); + assert.strictEqual(b?.localPath, "a.md"); + assert.strictEqual( + queue.getRecordByLocalPath("a.md" as RelativePath)?.documentId, + "B" + ); + // B's old slot is now empty — nothing else moved into it. + assert.strictEqual( + queue.getRecordByLocalPath("b.md" as RelativePath), + undefined + ); + }); + + it("upsertRecord displaces a previous holder of the same path", async () => { + const queue = createQueue(); + await queue.upsertRecord(fakeRecord("A")); + + // A new record (different docId) claims a.md. The prior holder + // (A) must be displaced — its localPath cleared, and + // byLocalPath["a.md"] now points at the new record. + await queue.upsertRecord( + fakeRecord("B", { localPath: "a.md" as RelativePath }) + ); + + const a = queue.getDocumentByDocumentId("A"); + const b = queue.getDocumentByDocumentId("B"); + assert.strictEqual(a?.localPath, undefined); + assert.strictEqual(b?.localPath, "a.md"); + assert.strictEqual( + queue.getRecordByLocalPath("a.md" as RelativePath)?.documentId, + "B" + ); + }); + + it("the localPath/byLocalPath invariant holds across rename + recreate cycles", async () => { + // Construct the exact same-path create cycle that produces the + // bug-D race: docA at P, then docB created at P (via + // upsertRecord), and finally a setLocalPath that would move a + // third doc onto P. The invariant must hold at every step: + // exactly one record has localPath===P at any given time, and + // byLocalPath.get(P) returns it. + const queue = createQueue(); + + const path = "p.md" as RelativePath; + + await queue.upsertRecord( + fakeRecord("A", { localPath: path, remoteRelativePath: path }) + ); + + // Sanity: A holds the slot. + assert.strictEqual(queue.getRecordByLocalPath(path)?.documentId, "A"); + assert.strictEqual(queue.getDocumentByDocumentId("A")?.localPath, path); + + // docB created at P via upsertRecord (e.g. a remote create + // that races A's local file onto the same slot). A must be + // displaced. + await queue.upsertRecord( + fakeRecord("B", { localPath: path, remoteRelativePath: path }) + ); + assert.strictEqual( + queue.getDocumentByDocumentId("A")?.localPath, + undefined + ); + assert.strictEqual(queue.getDocumentByDocumentId("B")?.localPath, path); + assert.strictEqual(queue.getRecordByLocalPath(path)?.documentId, "B"); + + // Now setLocalPath moves a third doc C onto P. B must in turn + // be displaced; the invariant still holds. + await queue.upsertRecord( + fakeRecord("C", { localPath: "c.md" as RelativePath }) + ); + await queue.setLocalPath("C", path); + assert.strictEqual( + queue.getDocumentByDocumentId("B")?.localPath, + undefined + ); + assert.strictEqual(queue.getDocumentByDocumentId("C")?.localPath, path); + assert.strictEqual(queue.getRecordByLocalPath(path)?.documentId, "C"); + + // Across the whole cycle exactly one record holds the slot. + const holders = Array.from(queue.allRecords()).filter( + (r) => r.localPath === path + ); + assert.strictEqual(holders.length, 1); + assert.strictEqual(holders[0].documentId, "C"); + }); + + it("clearAllState clears everything", async () => { + const queue = createQueue(); + await queue.upsertRecord(fakeRecord("A")); + await queue.enqueue({ type: SyncEventType.LocalCreate, path: "b.md" }); + + await queue.clearAllState(); + + assert.strictEqual(queue.syncedDocumentCount, 0); + assert.strictEqual(queue.pendingUpdateCount, 0); + assert.strictEqual(queue.byLocalPath.size, 0); + }); +}); diff --git a/frontend/sync-client/src/sync-operations/sync-event-queue.ts b/frontend/sync-client/src/sync-operations/sync-event-queue.ts new file mode 100644 index 00000000..75f675d0 --- /dev/null +++ b/frontend/sync-client/src/sync-operations/sync-event-queue.ts @@ -0,0 +1,1000 @@ +import type { Settings } from "../persistence/settings"; +import type { Logger } from "../tracing/logger"; +import { globsToRegexes } from "../utils/globs-to-regexes"; +import { removeFromArray } from "../utils/remove-from-array"; +import { EventListeners } from "../utils/data-structures/event-listeners"; +import { + SyncEventType, + type DocumentId, + type DocumentRecord, + type FileSyncEvent, + type RelativePath, + type StoredSyncState, + type SyncEvent, + type VaultUpdateId +} from "./types"; +import { MinCovered } from "../utils/data-structures/min-covered"; + +export const STORED_STATE_SCHEMA_VERSION = 2; + +export class SyncEventQueue { + // Fires synchronously whenever the events array length changes (push, pop, + // remove, bulk-clear). The Syncer mirrors this into its public count + // listener; without this hook, listeners only saw deltas at consume time + // and missed the "queue grew" / "queue cleared on reset" transitions. + public readonly onPendingUpdateCountChanged = new EventListeners< + (count: number) => unknown + >(); + + // Fires whenever a record's `localPath` transitions to a different + // value. Subscribers see every disk-side path change — watcher- + // driven user renames, post-create deconflicts placed by the + // reconciler, lost-rename replays in offline-scan, displacements + // when another record claims a slot. Useful for callers that + // mirror disk-side state (e.g. test harnesses that maintain a + // "do-not-touch" list keyed by current path). Both `oldPath` and + // `newPath` may be `undefined` (placement-pending state). + public readonly onDocumentPathChanged = new EventListeners< + ( + documentId: DocumentId, + oldPath: RelativePath | undefined, + newPath: RelativePath | undefined + ) => unknown + >(); + + private readonly _lastSeenUpdateId: MinCovered; + + // Primary index of every settled document, keyed by docId. The wire loop + // (records ↔ server) updates `remoteRelativePath` here as the server + // assigns/relocates a doc; the Reconciler (records ↔ disk) updates + // `localPath` here as it places files on disk. + private readonly byDocId = new Map(); + + // Derived index from `localPath -> record`. Maintained alongside every + // mutation that touches `localPath` so callers (the watcher path through + // `enqueue`, the Reconciler) get O(1) lookups by disk location. Only + // contains records whose `localPath !== undefined`. + private readonly _byLocalPath = new Map(); + + // All outstanding operations in order of occurrence, + // can include multiple generations of the same document, + // e.g.: a create, delete, create sequence for the same path. + // + // The paths within the events must always correspond to the latest + // path on disk, so the path of each event may be updated multiple + // times. + // + // It maps pending changes onto the local filesystem. + private readonly events: SyncEvent[] = []; + + // file creations for paths matching any of these patterns are ignored + // because the user explicitly told us to ignore them. + private userIgnorePatterns: RegExp[]; + + // Hard-coded ignores that callers (e.g. the Syncer for `.vaultlink/**` + // swap-marker files) pin via `addInternalIgnorePattern`. Folded into + // `userIgnorePatterns` so the existing match path doesn't need to know + // about two arrays. Stored separately so a later `onSettingsChanged` + // event that re-derives `userIgnorePatterns` from settings doesn't + // forget the internal patterns. + private readonly internalIgnorePatterns: RegExp[] = []; + + // DocIds whose HTTP DELETE has been acked by the server but whose + // WebSocket-receipt-driven `removeDocumentById` hasn't run yet (the + // record is still in `byDocId` because the wire loop keeps it around to + // recognise late remote updates as "file is missing"). The Reconciler + // and the remote-update wire-loop handlers consult this set to skip any + // work that would resurrect the doc — without it, a placement-pending + // record (`localPath === undefined` after the LocalDelete enqueue) would + // be re-fetched from the server and written back to disk, or a late + // RemoteChange for the same doc would stash the pre-delete bytes into + // `pendingPlacementContent` for the Reconciler to "place". + // + // Cleared as a side effect of `removeDocumentById`. Also cleared on + // `clearAllState` / schema-version-mismatch reset. + private readonly _pendingServerDeletes = new Set(); + + public constructor( + private readonly settings: Settings, + private readonly logger: Logger, + initialState: Partial | undefined, + private readonly saveData: (data: StoredSyncState) => Promise + ) { + this.userIgnorePatterns = globsToRegexes( + this.settings.getSettings().ignorePatterns, + this.logger + ); + + this.settings.onSettingsChanged.add((newSettings) => { + this.userIgnorePatterns = [ + ...globsToRegexes(newSettings.ignorePatterns, this.logger), + ...this.internalIgnorePatterns + ]; + }); + + initialState ??= {}; + + const persistedSchemaVersion = initialState.schemaVersion; + if (persistedSchemaVersion !== STORED_STATE_SCHEMA_VERSION) { + this.logger.info( + `Persisted state schema version is ${persistedSchemaVersion ?? "unset"}, expected ${STORED_STATE_SCHEMA_VERSION}; discarding persisted documents and watermark so the offline scan re-derives state from disk` + ); + initialState = {}; + // Schedule a save so the new schema version sticks even if the user + // never makes a change. Don't await here (constructor is sync); the + // first real save in `save()` will pin it down anyway. + void this.saveData({ + schemaVersion: STORED_STATE_SCHEMA_VERSION, + documents: [], + lastSeenUpdateId: 0 + }); + } + + if (initialState.documents !== undefined) { + for (const record of initialState.documents) { + this.byDocId.set(record.documentId, record); + if (record.localPath !== undefined) { + // Defensive: if two persisted records share the same + // localPath (shouldn't happen given the invariant + // enforced at every mutation point, but persisted + // state from older buggy versions could violate it), + // displace the prior holder so we don't end up with + // a shadowed record on load. + const displaced = this._byLocalPath.get(record.localPath); + if (displaced !== undefined && displaced !== record) { + displaced.localPath = undefined; + this.logger.warn( + `Persisted state had two records sharing localPath ` + + `${record.localPath} (${displaced.documentId} and ` + + `${record.documentId}); clearing the prior holder's ` + + `localPath so the reconciler re-places it` + ); + } + this._byLocalPath.set(record.localPath, record); + } + } + } + this._lastSeenUpdateId = new MinCovered( + initialState.lastSeenUpdateId ?? 0 + ); + + this.logger.debug( + `Loaded ${this.byDocId.size} documents and lastSeenUpdateId=${this._lastSeenUpdateId.min} from storage` + ); + } + + public get pendingUpdateCount(): number { + return this.events.length; + } + + public get syncedDocumentCount(): number { + return this.byDocId.size; + } + + /** + * Read-only view of the `localPath -> record` index. Use for O(1) lookups + * by disk location; the index is maintained by every mutation that + * touches `localPath` (`upsertRecord`, `setLocalPath`, the rename branch + * of `enqueue`, `removeDocumentById`). + */ + public get byLocalPath(): ReadonlyMap { + return this._byLocalPath; + } + + public get lastSeenUpdateId(): VaultUpdateId { + return this._lastSeenUpdateId.min; + } + + public set lastSeenUpdateId(id: VaultUpdateId) { + this._lastSeenUpdateId.add(id); + } + + /** + * Watermark to send with our own `POST /documents` requests. + * + * The contiguous-prefix `lastSeenUpdateId` lags behind reality whenever + * there are gaps in the vuid stream we've observed: if the server has + * committed vuids 1..N from various clients but we've only processed + * a non-contiguous subset, `min` stays at the last hole. The server's + * create handler reads this watermark to decide whether to merge a + * new POST into an existing doc at the same path: + * + * creation_vault_update_id > last_seen_vault_update_id → merge + * + * That check is meant to fire only for docs the client genuinely + * couldn't have known about. But on a same-device "rename a + * pending-create away then create something else at that path" race, + * the second POST went out with `last_seen = min` while we already + * held a record for the first create at vuid=N — and the server + * happily merged the second create into our own doc, aliasing two + * physically distinct local files onto a single docId. + * + * The fix is path-scoped: if we already track a doc whose + * `remoteRelativePath` matches the path we're about to POST, the + * server's existing doc at that path is exactly the one we'd alias + * into. Bumping `last_seen` to that record's `parentVersionId` + * forces the server's `creation_vuid > last_seen` check to fail and + * fall through to the deconflict path. For paths we don't yet + * track, we send the regular `min` watermark — so a legitimate + * cross-device merge (two clients independently creating the same + * path) still fires when neither side holds a record for the + * collision target. + */ + public lastSeenUpdateIdForCreate( + requestPath: RelativePath + ): VaultUpdateId { + let watermark = this._lastSeenUpdateId.min; + for (const record of this.byDocId.values()) { + if ( + record.remoteRelativePath === requestPath && + record.parentVersionId > watermark + ) { + watermark = record.parentVersionId; + } + } + return watermark; + } + + /** + * Pin an additional ignore pattern that survives setting reloads. Used + * by the Syncer to hide internal scratch paths (e.g. `.vaultlink/**` + * swap markers written by the Reconciler) from the watcher-driven + * enqueue path. The pattern is compiled with the same `globsToRegexes` + * used for user-configurable ignores; matching uses the existing + * userIgnorePatterns array so there's only one match path. + */ + public addInternalIgnorePattern(pattern: string): void { + const compiled = globsToRegexes([pattern], this.logger); + this.internalIgnorePatterns.push(...compiled); + this.userIgnorePatterns.push(...compiled); + } + + public async enqueue(input: FileSyncEvent): Promise { + const path = + input.type === SyncEventType.RemoteChange + ? input.remoteVersion.relativePath + : input.path; + + if (this.userIgnorePatterns.some((pattern) => pattern.test(path))) { + this.logger.info( + `Ignoring ${input.type} for ${path} as it matches ignore patterns` + ); + return; + } + + if (input.type === SyncEventType.RemoteChange) { + this.events.push(input); + this.notifyPendingUpdateCountChanged(); + return; + } + + if (input.type === SyncEventType.LocalCreate) { + this.events.push({ + type: SyncEventType.LocalCreate, + path, + isProcessing: false, + resolvers: Promise.withResolvers() + }); + this.notifyPendingUpdateCountChanged(); + return; + } + + const lookupPath = + input.type === SyncEventType.LocalUpdate && + input.oldPath !== undefined + ? input.oldPath + : path; + const record = this._byLocalPath.get(lookupPath); + + // If a settled record and a pending create both claim this path, the + // settled record owns the current disk slot, unless the record is + // already being deleted. A deleting record can briefly remain in the + // localPath index when a create/delete pair was queued while the + // create was pending; it must not steal the next same-path create's + // delete/update. + const pendingCreate = this.findLatestCreateForPath(lookupPath); + const pendingDocumentId: Promise | undefined = + pendingCreate?.resolvers.promise; + + const recordIsDeleting = + record !== undefined && + (this.hasPendingLocalDeleteForDocumentId(record.documentId) || + this.hasPendingServerDelete(record.documentId)); + const recordOwnsLookupPath = + record !== undefined && + !(recordIsDeleting && pendingDocumentId !== undefined); + + const documentId: DocumentId | undefined = recordOwnsLookupPath + ? record.documentId + : undefined; + + const effectiveDocumentId: + | Promise + | DocumentId + | undefined = documentId ?? pendingDocumentId; + if (effectiveDocumentId === undefined) { + // we can get here when deleting a local document after a remote update + return; + } + + if (input.type === SyncEventType.LocalDelete) { + if ( + documentId === undefined && + pendingCreate !== undefined && + !pendingCreate.isProcessing + ) { + this.cancelPendingCreate(pendingCreate); + if (recordIsDeleting && record !== undefined) { + // A stale deleting record was still claiming this path. + // The not-yet-started create/delete pair collapsed to + // nothing, and the disk file is gone, so clear the stale + // claim too. + await this.setLocalPath(record.documentId, undefined); + } + return; + } + + // Push BEFORE awaiting `setLocalPath` (and its inner `save()`). + // See the comment below on the synchronicity contract with + // `ensureDraining()`. + this.events.push({ + type: SyncEventType.LocalDelete, + documentId: effectiveDocumentId, + path: lookupPath + }); + this.notifyPendingUpdateCountChanged(); + if (recordOwnsLookupPath && record !== undefined) { + // The file is gone from disk; clear the doc's localPath so the + // Reconciler doesn't try to operate on a vacated slot. + await this.setLocalPath(record.documentId, undefined); + } else if (recordIsDeleting && record !== undefined) { + // A stale deleting record was still claiming this path while a + // newer pending create owned the actual disk file. Drop the + // stale claim now that the file is gone. + await this.setLocalPath(record.documentId, undefined); + } + return; + } + + const isUserRename = input.oldPath !== undefined; + let needsSave = false; + if (input.oldPath !== undefined) { + if (!recordOwnsLookupPath && pendingDocumentId !== undefined) { + this.updatePendingCreatePath(input.oldPath, path); + } else { + if (record === undefined || !recordOwnsLookupPath) { + throw new Error( + "Unreachable: record must be defined for non-pending update" + ); + } + // The user renamed `oldPath` onto `path`. If `path` was + // already tracked by a *different* doc (the OS rename + // overwrote that file), that doc effectively no longer + // exists locally — its content was clobbered. Without + // explicitly recording the loss the doc would silently + // drop out of the byLocalPath index below and we'd skip + // notifying the server, leaving a phantom on the remote + // that other agents still see. Enqueue a LocalDelete for + // it so the server learns about the deletion. + const displacedRecord = this._byLocalPath.get(path); + if ( + displacedRecord !== undefined && + displacedRecord.documentId !== record.documentId + ) { + this.events.push({ + type: SyncEventType.LocalDelete, + documentId: displacedRecord.documentId, + // Snapshot the path; once we move `record` onto + // `path` below the displaced doc will no longer + // resolve via `byLocalPath`. + path + }); + // Drop the displaced doc's localPath: its file on + // disk is gone (overwritten by the rename). + // Mutate synchronously so the byLocalPath index is + // correct before we move `record` onto the same + // slot below; the persist runs in the trailing + // `save()` so we don't await before pushing the + // LocalUpdate (synchronicity contract). + this.mutateLocalPathInPlace(displacedRecord, undefined); + needsSave = true; + } + // Move record's localPath onto the new slot. We mutate + // the record in place rather than re-creating it so any + // held reference (drain handlers, queued events) sees + // the new path on its next read. + this.mutateLocalPathInPlace(record, path); + // Retarget any queued LocalUpdates for this doc onto + // the new path. The queue's invariant — and what + // `skipIfOversized` and the watcher dedup checks bake + // in — is that `event.path` always points at the doc's + // current disk location. + for (const e of this.events) { + if ( + e.type === SyncEventType.LocalUpdate && + e.documentId === record.documentId + ) { + e.path = path; + } + } + needsSave = true; + } + } + + // Push BEFORE awaiting `save()`. The synchronicity contract is: + // `Syncer.ensureDraining()` runs immediately after each `enqueue`, + // and the drain only sees what's in `events[]`. Pushing after an + // await would let the drain start, see an empty queue, exit, and + // leave the event stranded. + this.events.push({ + type: SyncEventType.LocalUpdate, + documentId: effectiveDocumentId, + path, + originalPath: path, + isUserRename + }); + this.notifyPendingUpdateCountChanged(); + + if (needsSave) { + await this.save(); + } + } + + public async next(): Promise { + const event = this.events.shift(); + if (event !== undefined) { + this.notifyPendingUpdateCountChanged(); + } + return event; + } + + /** + * Return the next event without removing it. Drain uses this so the + * event stays visible in the queue while it is being processed — + * critical for `findLatestCreateForPath` to update an in-flight + * `LocalCreate`'s local read path when a rename arrives mid-process. + */ + public peekFront(): SyncEvent | undefined { + return this.events[0]; + } + + /** + * Remove a specific event after `peekFront`-based processing is done. + * Idempotent — safe to call when the event was already taken out by + * `resolveCreate` (which clears a same-path pending create that a + * remote-create handler just absorbed). + */ + public consumeEvent(event: SyncEvent): void { + if (removeFromArray(this.events, event)) { + this.notifyPendingUpdateCountChanged(); + } + } + + /** + * Call once a create has been acknowledged by the server. + * + * Queued `LocalUpdate` / `LocalDelete` events that were pushed while + * this create was still in-flight carry the create's `resolvers.promise` + * as their `documentId` (see the `pendingDocumentId` branch of + * `enqueue`). We must rewrite those references to the resolved string + * id *before* calling `upsertRecord`, otherwise its event-rewrite loop + * (which compares `e.documentId === record.documentId`) would silently + * skip them — leaving their `event.path` pointing at the pre-rename + * slot and causing the next drain step's `getFileSize(event.path)` to + * throw `FileNotFoundError`, dropping the user's intent. + */ + public async resolveCreate( + event: Extract, + record: DocumentRecord + ): Promise { + if (removeFromArray(this.events, event)) { + this.notifyPendingUpdateCountChanged(); + } + this.replacePendingDocumentId( + event.resolvers.promise, + record.documentId + ); + const localPath = this.hasPendingLocalDeleteForDocumentId( + record.documentId, + record.localPath + ) + ? undefined + : record.localPath; + await this.upsertRecord({ ...record, localPath }); + event.resolvers.resolve(record.documentId); + } + + /** + * Swap a pending create's `Promise` reference for the + * resolved string id across every queued `LocalUpdate` / `LocalDelete`. + * Call this whenever a create resolves (regular ack OR + * displacement-merge into an existing doc) — see `resolveCreate` for + * the failure mode if it's skipped. + */ + public replacePendingDocumentId( + promise: Promise, + documentId: DocumentId + ): void { + for (const e of this.events) { + if ( + (e.type === SyncEventType.LocalUpdate || + e.type === SyncEventType.LocalDelete) && + e.documentId === promise + ) { + e.documentId = documentId; + } + } + } + + /** + * Insert or merge a document record by `documentId`. When a record with + * the same docId already exists it is mutated in place so any held + * references (drain handlers, queued events) keep seeing the up-to-date + * fields on their next read — this stays load-bearing for the Syncer's + * drain handlers, which await across HTTP roundtrips. + * + * For an existing record this updates the wire fields + * (`parentVersionId`, `remoteHash`, `remoteRelativePath`) and, only + * when the existing record has no local file yet + * (`localPath === undefined`), installs the supplied `localPath`. A + * non-undefined existing localPath is owned by the watcher path and + * the Reconciler — overwriting it from the wire loop would race a + * user rename that landed during an HTTP roundtrip and silently + * resurrect a stale slot. + */ + public async upsertRecord(record: DocumentRecord): Promise { + const existing = this.byDocId.get(record.documentId); + if (existing === undefined) { + const target: DocumentRecord = { ...record }; + this.byDocId.set(record.documentId, target); + if (target.localPath !== undefined) { + // Route through `mutateLocalPathInPlace` so the + // localPath/byLocalPath invariant is upheld: if another + // record already holds this slot, displace it (clear + // its localPath) before installing `target`. Otherwise + // we'd leave the displaced record shadowed (its + // `localPath` still points at a slot that no longer + // belongs to it), which the Reconciler would then + // "rescue" by reading/renaming the file at that path + // — but that file belongs to `target` now, causing + // data loss. + target.localPath = undefined; + this.mutateLocalPathInPlace(target, record.localPath); + } + } else { + existing.parentVersionId = record.parentVersionId; + existing.remoteHash = record.remoteHash; + existing.remoteRelativePath = record.remoteRelativePath; + if ( + existing.localPath === undefined && + record.localPath !== undefined + ) { + return this.setLocalPath(record.documentId, record.localPath); + } + } + return this.save(); + } + + /** + * Update the `localPath` of an already-tracked record (by docId) and + * re-key the `byLocalPath` index. Called by both the watcher path + * (through `enqueue`) and the Reconciler. + * + * Pass `undefined` to mark the doc as "no local file" — the Reconciler + * will place a file later (e.g. a remote create whose + * `remoteRelativePath` slot is occupied at receive time). + */ + public async setLocalPath( + documentId: DocumentId, + newLocalPath: RelativePath | undefined + ): Promise { + const record = this.byDocId.get(documentId); + if (record === undefined) { + return; + } + this.mutateLocalPathInPlace(record, newLocalPath); + return this.save(); + } + + public async removeDocumentById(documentId: DocumentId): Promise { + const record = this.byDocId.get(documentId); + if (record === undefined) { + // Still clear any deletion-pending mark and purge stale + // RemoteChange events so a never-tracked doc doesn't accumulate + // entries. + this._pendingServerDeletes.delete(documentId); + this.purgeRemoteChangesForDocumentId(documentId); + return; + } + if ( + record.localPath !== undefined && + this._byLocalPath.get(record.localPath) === record + ) { + this._byLocalPath.delete(record.localPath); + } + this.byDocId.delete(documentId); + this._pendingServerDeletes.delete(documentId); + // Drop any pending RemoteChange events for this doc. A common case: + // a catch-up RemoteChange for the doc was deferred indefinitely + // while the user's LocalDelete (and any LocalUpdate behind it) sat + // in the queue ahead of it. Once those drain and the doc is + // removed, a still-pending RemoteChange for an earlier version + // would be processed by `processRemoteCreateForNewDocument` (the + // doc is now untracked, and catch-up's `isNewFile=true` semantics + // qualify it as a fresh create), resurrecting the doc on disk + // with stale bytes that disagree with every other agent. + this.purgeRemoteChangesForDocumentId(documentId); + return this.save(); + } + + /** + * Mark a doc as "HTTP DELETE has been acked by the server but the + * WebSocket receipt that would call `removeDocumentById` hasn't arrived + * yet". The Reconciler and remote-update wire-loop handlers consult + * `hasPendingServerDelete` to skip any work that would resurrect the + * doc. Cleared automatically by `removeDocumentById`. + */ + public markServerDeletePending(documentId: DocumentId): void { + this._pendingServerDeletes.add(documentId); + } + + public hasPendingServerDelete(documentId: DocumentId): boolean { + return this._pendingServerDeletes.has(documentId); + } + + public getDocumentByDocumentId( + target: DocumentId + ): DocumentRecord | undefined { + return this.byDocId.get(target); + } + + public getDocumentByDocumentIdOrFail(target: DocumentId): DocumentRecord { + const result = this.getDocumentByDocumentId(target); + if (!result) { + throw new Error(`No document found with id ${target}`); + } + return result; + } + + public getRecordByLocalPath( + path: RelativePath + ): DocumentRecord | undefined { + return this._byLocalPath.get(path); + } + + public async save(): Promise { + return this.saveData({ + schemaVersion: STORED_STATE_SCHEMA_VERSION, + documents: Array.from(this.byDocId.values()), + lastSeenUpdateId: this.lastSeenUpdateId + }); + } + + public allSettledDocuments(): Map { + const result = new Map(); + for (const record of this.byDocId.values()) { + if (record.localPath !== undefined) { + result.set(record.localPath, record); + } + } + return result; + } + + /** + * Every tracked record, regardless of whether it has been placed on + * disk yet. The Reconciler uses this to find records whose + * `localPath === undefined` (e.g. a remote create that landed when + * its target slot was occupied) and try to place them once the + * obstruction clears. `allSettledDocuments` filters those out, so + * relying on it would render placement-pending records invisible + * forever. + */ + public allRecords(): Iterable { + return this.byDocId.values(); + } + + public hasPendingEventsForPath(path: RelativePath): boolean { + const record = this._byLocalPath.get(path); + if (record === undefined) { + return true; // if we don't know about this path, it must be pending creation + } + const docId = record.documentId; + return this.events.some( + (e) => + (e.type === SyncEventType.LocalCreate && e.path === path) || + (e.type === SyncEventType.LocalUpdate && + e.documentId === docId) || + (e.type === SyncEventType.LocalDelete && + e.documentId === docId) || + (e.type === SyncEventType.RemoteChange && + // we care about the local path not the remote + this.getDocumentByDocumentId(e.remoteVersion.documentId) + ?.localPath === path) + ); + } + + public hasPendingLocalEventsForDocumentId(documentId: DocumentId): boolean { + return this.events.some( + (e) => + (e.type === SyncEventType.LocalUpdate && + e.documentId === documentId) || + (e.type === SyncEventType.LocalDelete && + e.documentId === documentId) + ); + } + + public hasPendingLocalDeleteForDocumentId( + documentId: DocumentId, + path?: RelativePath + ): boolean { + return this.events.some( + (e) => + e.type === SyncEventType.LocalDelete && + e.documentId === documentId && + (path === undefined || e.path === path) + ); + } + + public async clearAllState(): Promise { + this.clearPending(); + this.byDocId.clear(); + this._byLocalPath.clear(); + this._pendingServerDeletes.clear(); + this._lastSeenUpdateId.reset(); + await this.save(); + } + + public clearPending(): void { + const hadEvents = this.events.length > 0; + this.rejectAllPendingCreates(); + this.events.length = 0; + if (hadEvents) { + this.notifyPendingUpdateCountChanged(); + } + } + + public findLatestCreateForPath( + path: RelativePath + ): Extract | undefined { + for (let i = this.events.length - 1; i >= 0; i--) { + const e = this.events[i]; + if (e.type === SyncEventType.LocalCreate && e.path === path) { + return e; + } + } + return undefined; + } + + public hasPendingCreateForPath(path: RelativePath): boolean { + return this.events.some( + (e) => e.type === SyncEventType.LocalCreate && e.path === path + ); + } + + public updatePendingCreatePath( + oldPath: RelativePath, + newPath: RelativePath + ): void { + const createEvent = this.findLatestCreateForPath(oldPath); + if (createEvent === undefined) { + return; + } + + const { promise } = createEvent.resolvers; + createEvent.path = newPath; + if (!createEvent.isProcessing) { + this.moveBlockingDeletesBeforeCreate(createEvent, newPath); + this.moveBlockingRenamesBeforeCreate(createEvent, newPath); + } + + for (const e of this.events) { + if ( + e.type === SyncEventType.LocalUpdate && + e.documentId === promise + ) { + e.path = newPath; + } + } + } + + private moveBlockingDeletesBeforeCreate( + createEvent: Extract, + path: RelativePath + ): void { + const { promise } = createEvent.resolvers; + let createIndex = this.events.indexOf(createEvent); + if (createIndex < 0) { + return; + } + + for (let i = createIndex + 1; i < this.events.length; ) { + const event = this.events[i]; + if ( + event.type === SyncEventType.LocalDelete && + event.path === path && + event.documentId !== promise + ) { + this.events.splice(i, 1); + this.events.splice(createIndex, 0, event); + createIndex++; + continue; + } + i++; + } + } + + /** + * The `path` argument is the create's just-retargeted target. Any + * other tracked doc whose server-side path is still `path` (its + * watcher-driven local rename hasn't reached the server yet) needs + * its pending LocalUpdate to drain *before* this create — otherwise + * the create's HTTP request hits the server while the doc is still + * at `path` and triggers a same-path same-docId merge that + * silently consumes the user's "new doc" intent into the + * already-tracked doc. The pending LocalUpdate is the rename that + * moves the existing doc off `path` server-side; running it first + * frees the slot. Skipped when the create has already been sent — + * at that point the merge has already happened or hasn't, and + * reordering the queue can't unwind it. + */ + private moveBlockingRenamesBeforeCreate( + createEvent: Extract, + path: RelativePath + ): void { + const blockingDocIds = new Set(); + for (const record of this.byDocId.values()) { + if ( + record.remoteRelativePath === path && + record.localPath !== path + ) { + blockingDocIds.add(record.documentId); + } + } + if (blockingDocIds.size === 0) { + return; + } + + let createIndex = this.events.indexOf(createEvent); + if (createIndex < 0) { + return; + } + + for (let i = createIndex + 1; i < this.events.length; ) { + const event = this.events[i]; + if ( + event.type === SyncEventType.LocalUpdate && + typeof event.documentId === "string" && + blockingDocIds.has(event.documentId) + ) { + this.events.splice(i, 1); + this.events.splice(createIndex, 0, event); + createIndex++; + continue; + } + i++; + } + } + + /** + * Synchronous half of `setLocalPath`: mutate `record.localPath` and + * re-key `_byLocalPath` without persisting. Used by `enqueue`'s + * rename branch where the synchronicity contract requires we push + * the LocalUpdate event before awaiting the save. + * + * Enforces the invariant + * `record.localPath !== undefined ⇒ byLocalPath.get(record.localPath) === record`. + * If `newLocalPath` is currently held by a different record, that + * record is *displaced*: its `localPath` is cleared so it enters + * placement-pending state, and the Reconciler's next pass will + * re-place it via `tryInitialPlacement`. Without this displacement + * the prior holder would remain shadowed (its `localPath === P` + * but `byLocalPath[P]` points elsewhere) and the Reconciler could + * later try to "rescue" the shadowed record by reading/renaming + * the file at `P` — which belongs to the new owner now — causing + * data loss. This is the architectural fix for bug D + * (`Files from agent-1 missing in agent-0` after a same-path + * create cycle). + */ + private mutateLocalPathInPlace( + record: DocumentRecord, + newLocalPath: RelativePath | undefined + ): void { + const previousLocalPath = record.localPath; + if ( + previousLocalPath !== undefined && + this._byLocalPath.get(previousLocalPath) === record + ) { + this._byLocalPath.delete(previousLocalPath); + } + record.localPath = newLocalPath; + let displacedRecord: DocumentRecord | undefined; + let displacedOldPath: RelativePath | undefined; + if (newLocalPath !== undefined) { + const displaced = this._byLocalPath.get(newLocalPath); + if (displaced !== undefined && displaced !== record) { + // Invariant: `byLocalPath[displaced.localPath] === displaced`. + // We're about to overwrite that slot, so clear the + // displaced record's localPath; the reconciler will + // re-place it via tryInitialPlacement on the next pass. + displacedOldPath = displaced.localPath; + displaced.localPath = undefined; + displacedRecord = displaced; + } + this._byLocalPath.set(newLocalPath, record); + } + if (previousLocalPath !== newLocalPath) { + this.onDocumentPathChanged.trigger( + record.documentId, + previousLocalPath, + newLocalPath + ); + } + if (displacedRecord !== undefined) { + this.onDocumentPathChanged.trigger( + displacedRecord.documentId, + displacedOldPath, + undefined + ); + } + } + + private notifyPendingUpdateCountChanged(): void { + this.onPendingUpdateCountChanged.trigger(this.events.length); + } + + private rejectAllPendingCreates(): void { + for (const event of this.events) { + if (event.type === SyncEventType.LocalCreate) { + event.resolvers.promise.catch(() => { + /* suppressed — consumer may not be listening */ + }); + event.resolvers.reject(new Error("Create was cancelled")); + } + } + } + + private cancelPendingCreate( + createEvent: Extract + ): void { + const { promise } = createEvent.resolvers; + const toRemove = this.events.filter( + (event) => + event === createEvent || + ((event.type === SyncEventType.LocalUpdate || + event.type === SyncEventType.LocalDelete) && + event.documentId === promise) + ); + + for (const event of toRemove) { + removeFromArray(this.events, event); + } + + createEvent.resolvers.promise.catch(() => { + /* suppressed — the create/delete pair collapsed locally */ + }); + createEvent.resolvers.reject(new Error("Create was cancelled")); + + if (toRemove.length > 0) { + this.notifyPendingUpdateCountChanged(); + } + } + + private purgeRemoteChangesForDocumentId(documentId: DocumentId): void { + const toRemove = this.events.filter( + (e) => + e.type === SyncEventType.RemoteChange && + e.remoteVersion.documentId === documentId + ); + for (const event of toRemove) { + if (event.type === SyncEventType.RemoteChange) { + // Advance the watermark for the dropped event so the gap + // doesn't leave the catch-up replay this id forever. + this._lastSeenUpdateId.add(event.remoteVersion.vaultUpdateId); + } + removeFromArray(this.events, event); + } + if (toRemove.length > 0) { + this.notifyPendingUpdateCountChanged(); + } + } +} diff --git a/frontend/sync-client/src/sync-operations/syncer.ts b/frontend/sync-client/src/sync-operations/syncer.ts index 71dedd85..4e908600 100644 --- a/frontend/sync-client/src/sync-operations/syncer.ts +++ b/frontend/sync-client/src/sync-operations/syncer.ts @@ -1,238 +1,191 @@ -import type { - Database, - DocumentId, - DocumentRecord, - RelativePath -} from "../persistence/database"; -import type { SyncService } from "../services/sync-service"; +// Two-loop sync engine. The wire loop (this file) keeps records in step +// with the server: HTTP/WS handlers update record fields and write +// content to the file at `record.localPath`. They never move files for +// path placement. The Reconciler (reconciler.ts) handles record↔disk +// path reconciliation, running after every wire-loop drained event. +import { + SyncEventType, + type DocumentId, + type DocumentRecord, + type SyncEvent, + type RelativePath, + type VaultUpdateId +} from "./types"; import type { Logger } from "../tracing/logger"; -import PQueue from "p-queue"; import { hash } from "../utils/hash"; -import { v4 as uuidv4 } from "uuid"; import type { Settings } from "../persistence/settings"; import type { FileOperations } from "../file-operations/file-operations"; -import { findMatchingFile } from "../utils/find-matching-file"; -import type { UnrestrictedSyncer } from "./unrestricted-syncer"; -import { createPromise } from "../utils/create-promise"; -import { SyncResetError } from "../services/sync-reset-error"; -import { Locks } from "../utils/data-structures/locks"; +import { FileAlreadyExistsError } from "../errors/file-already-exists-error"; +import { scheduleOfflineChanges } from "./offline-change-detector"; +import { SyncResetError } from "../errors/sync-reset-error"; import type { DocumentVersionWithoutContent } from "../services/types/DocumentVersionWithoutContent"; import type { WebSocketVaultUpdate } from "../services/types/WebSocketVaultUpdate"; import type { WebSocketManager } from "../services/websocket-manager"; import type { WebSocketClientMessage } from "../services/types/WebSocketClientMessage"; -import { awaitAll } from "../utils/await-all"; import { EventListeners } from "../utils/data-structures/event-listeners"; +import type { SyncEventQueue } from "./sync-event-queue"; +import type { SyncService } from "../services/sync-service"; +import { FileNotFoundError } from "../errors/file-not-found-error"; +import { HttpClientError } from "../errors/http-client-error"; +import type { SyncHistory } from "../tracing/sync-history"; +import { + SyncStatus, + SyncType, + type HistoryEntry +} from "../tracing/sync-history"; +import { isBinary } from "../utils/is-binary"; +import { isFileTypeMergable } from "../utils/is-file-type-mergable"; +import { diff } from "reconcile-text"; +import type { ServerConfig } from "../services/server-config"; +import type { FixedSizeDocumentCache } from "../utils/data-structures/fix-sized-cache"; +import { base64ToBytes } from "byte-base64"; +import type { DocumentUpdateResponse } from "../services/types/DocumentUpdateResponse"; +import { Reconciler } from "./reconciler"; + +// Internal ignore pattern pinned on the queue at construction time so +// the watcher's enqueue path doesn't pick up Reconciler swap markers. +const VAULTLINK_INTERNAL_DIR_IGNORE = ".vaultlink/**"; export class Syncer { public readonly onRemainingOperationsCountChanged = new EventListeners< (remainingOperations: number) => unknown >(); - private readonly remoteDocumentsLock: Locks; + private readonly queue: SyncEventQueue; + private readonly reconciler: Reconciler; + // Bytes the wire loop received for a doc whose `localPath` is not yet + // set (e.g. a remote create whose target slot was occupied). Shared + // with the Reconciler, which consumes (and deletes the entry) when it + // places the file. Keeping the bytes here avoids a redundant + // server fetch on the very next reconciler pass. + private readonly pendingPlacementContent = new Map< + DocumentId, + Uint8Array + >(); - // FIFO to limit the number of concurrent sync operations - private readonly syncQueue: PQueue; - - private _isFirstSyncComplete = false; private runningScheduleSyncForOfflineChanges: Promise | undefined; + private drainPromise: Promise | undefined; + private drainRequestedWhileRunning = false; + private isDrainingPaused = false; + private isScanning = false; private previousRemainingOperationsCount = 0; public constructor( private readonly deviceId: string, private readonly logger: Logger, - private readonly database: Database, private readonly settings: Settings, - private readonly syncService: SyncService, private readonly webSocketManager: WebSocketManager, private readonly operations: FileOperations, - private readonly internalSyncer: UnrestrictedSyncer + private readonly syncService: SyncService, + private readonly history: SyncHistory, + private readonly contentCache: FixedSizeDocumentCache, + private readonly serverConfig: ServerConfig, + queue: SyncEventQueue ) { - this.syncQueue = new PQueue({ - concurrency: settings.getSettings().syncConcurrency - }); + this.queue = queue; - this.remoteDocumentsLock = new Locks(this.logger); + // Hide the Reconciler's swap-marker scratch directory from the + // watcher's enqueue path. Without this, the marker file the + // Reconciler writes during a cycle swap would race onto the + // queue as a LocalCreate, and the queue would push that to the + // server. + this.queue.addInternalIgnorePattern(VAULTLINK_INTERNAL_DIR_IGNORE); - settings.onSettingsChanged.add((newSettings, oldSettings) => { - if (newSettings.syncConcurrency !== oldSettings.syncConcurrency) { - this.syncQueue.concurrency = newSettings.syncConcurrency; - } - }); + this.reconciler = new Reconciler( + this.logger, + this.operations, + this.syncService, + this.queue, + this.pendingPlacementContent + ); - this.syncQueue.on("active", () => { - if (this.previousRemainingOperationsCount !== this.syncQueue.size) { - this.previousRemainingOperationsCount = this.syncQueue.size; - this.onRemainingOperationsCountChanged.trigger( - this.syncQueue.size - ); - } - }); + // Fire-and-forget: any swap marker left behind by a crash gets + // rolled forward before the first wire-loop event runs. Errors + // are logged inside the reconciler. + void this.reconciler.recoverFromInterruptedSwap(); this.webSocketManager.onWebSocketStatusChanged.add((isConnected) => { if (isConnected) { - // The JS WebSocket API doesn't support setting headers, so we have to send the token as a message this.sendHandshakeMessage(); } }); this.webSocketManager.onRemoteVaultUpdateReceived.add( this.syncRemotelyUpdatedFile.bind(this) ); + // Funnel every queue mutation (enqueue, consume, clearPending) through + // the public count notifier so listeners see grow/shrink transitions + // immediately rather than only when a drain consumes an event. + this.queue.onPendingUpdateCountChanged.add(() => { + this.notifyRemainingOperationsChanged(); + }); } - public get isFirstSyncComplete(): boolean { - return this._isFirstSyncComplete; + /** + * True while the syncer has *active* work the caller should wait on: a + * running offline scan or an in-flight drain. Pending queue events alone + * don't count — `pause()` and `SyncResetError` exit drain early without + * clearing the queue, and nothing will pick those events back up until + * sync is re-enabled. Treating queued-but-stuck events as pending work + * would deadlock `waitUntilFinishedInternal` (the awaits inside its loop + * are no-ops once the active work has settled). + * + * The contract that makes "in-flight only" sufficient: every codepath + * that enqueues an event ends in `ensureDraining()` (the local-sync + * methods, `syncRemotelyUpdatedFile`, and the tail of + * `internalScheduleSyncForOfflineChanges`). So if a WebSocket handler + * lands new work mid-await, the next loop iteration sees `drainPromise` + * set and waits on it. + * + * Uses `isScanning` rather than `runningScheduleSyncForOfflineChanges` + * because the latter is a "have we already scanned this session" latch + * that stays set after the scan resolves. + */ + public get hasPendingWork(): boolean { + return this.isScanning || this.drainPromise !== undefined; } - public async syncLocallyCreatedFile( - relativePath: RelativePath - ): Promise { - if ( - this.database.getLatestDocumentByRelativePath(relativePath) - ?.isDeleted === false - ) { - this.logger.debug( - `Document ${relativePath} already exists in the database, skipping` - ); - return; - } - - const [promise, resolve, reject] = createPromise(); - - const id = uuidv4(); - const document = this.database.createNewPendingDocument( - id, - relativePath, - promise - ); - - try { - await this.syncQueue.add(async () => - this.internalSyncer.unrestrictedSyncLocallyCreatedFile(document) - ); - - resolve(); - } catch (e) { - reject(e); - } finally { - this.database.removeDocumentPromise(promise); - } + public syncLocallyCreatedFile(relativePath: RelativePath): void { + void this.queue.enqueue({ + type: SyncEventType.LocalCreate, + path: relativePath + }); + this.ensureDraining(); } - public async syncLocallyDeletedFile( - relativePath: RelativePath - ): Promise { - if ( - this.database.getLatestDocumentByRelativePath(relativePath) - ?.isDeleted === true - ) { - // This is must be a consequence of us deleting a file because of a remote update - // which triggered a local delete, so we don't need to do anything here. - this.logger.debug( - `Document ${relativePath} has already been markes as deleted, skipping` - ); - return; - } - - // We have to have a record of the delete in case there's an in-flight update for the same - // document which finishes after the delete has succeeded and would introduce a phantom metadata record. - this.database.delete(relativePath); - - const [promise, resolve, reject] = createPromise(); - - const document = await this.database.getResolvedDocumentByRelativePath( - relativePath, - promise - ); - - try { - await this.syncQueue.add(async () => - this.internalSyncer.unrestrictedSyncLocallyDeletedFile(document) - ); - - resolve(); - - this.database.removeDocument(document); - } catch (e) { - reject(e); - } finally { - this.database.removeDocumentPromise(promise); - } - } - - public async syncLocallyUpdatedFile({ + public syncLocallyUpdatedFile({ oldPath, relativePath }: { oldPath?: RelativePath; relativePath: RelativePath; - }): Promise { - if (oldPath !== undefined) { - // We might have moved the document in the database before calling this method, - // in that case, we mustn't move it again. - if ( - this.database.getLatestDocumentByRelativePath(relativePath) === - undefined || - this.database.getLatestDocumentByRelativePath(relativePath) - ?.isDeleted === true - ) { - if (oldPath === relativePath) { - throw new Error( - `Old path and new path are the same: ${oldPath}` - ); - } + }): void { + void this.queue.enqueue({ + type: SyncEventType.LocalUpdate, + path: relativePath, + oldPath + }); + this.ensureDraining(); + } - this.database.move(oldPath, relativePath); - } - } + public syncLocallyDeletedFile(relativePath: RelativePath): void { + void this.queue.enqueue({ + type: SyncEventType.LocalDelete, + path: relativePath + }); + this.ensureDraining(); + } - let document = - this.database.getLatestDocumentByRelativePath(relativePath); + public async syncRemotelyUpdatedFile( + message: WebSocketVaultUpdate + ): Promise { + await this.scheduleSyncForOfflineChanges(); - if ( - oldPath !== undefined && - document?.metadata?.remoteRelativePath === relativePath - ) { - this.logger.debug( - `Document ${relativePath} has been moved as a result of a remote update, skipping sync` - ); - return; - } + void this.queue.enqueue({ + type: SyncEventType.RemoteChange, + remoteVersion: message.document + }); - if (document === undefined) { - this.logger.debug( - `Cannot find document ${relativePath} in the database, skipping` - ); - return; - } - - if (document.isDeleted) { - this.logger.debug( - `Document ${relativePath} has been deleted locally, skipping` - ); - return; - } - - const [promise, resolve, reject] = createPromise(); - - document = await this.database.getResolvedDocumentByRelativePath( - relativePath, - promise - ); - - try { - await this.syncQueue.add(async () => - this.internalSyncer.unrestrictedSyncLocallyUpdatedFile({ - oldPath, - document - }) - ); - - resolve(); - } catch (e) { - reject(e); - } finally { - this.database.removeDocumentPromise(promise); - } + this.ensureDraining(); } public async scheduleSyncForOfflineChanges(): Promise { @@ -245,7 +198,7 @@ export class Syncer { this.runningScheduleSyncForOfflineChanges = this.internalScheduleSyncForOfflineChanges(); await this.runningScheduleSyncForOfflineChanges; - this.logger.info(`All local changes have been applied remotely`); + this.logger.info(`All local changes have been queued`); } catch (e) { if (e instanceof SyncResetError) { this.logger.info( @@ -257,47 +210,49 @@ export class Syncer { `Not all local changes have been applied remotely: ${e}` ); throw e; - } finally { - this.runningScheduleSyncForOfflineChanges = undefined; } } public async waitUntilFinished(): Promise { await this.runningScheduleSyncForOfflineChanges; - await this.syncQueue.onIdle(); // Wait for queue to be empty and running tasks to finish - } - - public async syncRemotelyUpdatedFile( - message: WebSocketVaultUpdate - ): Promise { - try { - const handlerPromise = awaitAll( - message.documents.map(async (document) => - this.internalSyncRemotelyUpdatedFile(document) - ) - ); - - await handlerPromise; - - if (message.isInitialSync && message.documents.length > 0) { - this.database.setLastSeenUpdateId( - message.documents - .map((document) => document.vaultUpdateId) - .reduce((a, b) => Math.max(a, b)) - ); - } - - this._isFirstSyncComplete = true; - } catch (e) { - this.logger.error(`Failed to sync remotely updated file: ${e}`); + // A drain that finishes can be immediately followed by a new one + // (e.g. a remote event arriving), so re-check after each await. + while (this.drainPromise !== undefined) { + await this.drainPromise; } } public reset(): void { - this._isFirstSyncComplete = false; - this.syncQueue.clear(); - this.remoteDocumentsLock.reset(); - this.runningScheduleSyncForOfflineChanges = undefined; + this.queue.clearPending(); + this.clearOfflineScanGate(); + this.previousRemainingOperationsCount = 0; + } + + /** + * Reset the "have we already scanned this session" gate so a later + * `scheduleSyncForOfflineChanges()` actually performs a fresh scan + * instead of returning the previous (resolved) promise. Called when + * sync is paused so the next start picks up any offline edits made + * while sync was off. + */ + public clearOfflineScanGate(): void { + const current = this.runningScheduleSyncForOfflineChanges; + if (current !== undefined) { + void current.finally(() => { + if (this.runningScheduleSyncForOfflineChanges === current) { + this.runningScheduleSyncForOfflineChanges = undefined; + } + }); + } + } + + public pauseDraining(): void { + this.isDrainingPaused = true; + } + + public resumeDraining(): void { + this.isDrainingPaused = false; + this.ensureDraining(); } private sendHandshakeMessage(): void { @@ -305,218 +260,994 @@ export class Syncer { type: "handshake", deviceId: this.deviceId, token: this.settings.getSettings().token, - lastSeenVaultUpdateId: this.database.getLastSeenUpdateId() + lastSeenVaultUpdateId: this.queue.lastSeenUpdateId }; this.webSocketManager.sendHandshakeMessage(message); } - private async internalSyncRemotelyUpdatedFile( - remoteVersion: DocumentVersionWithoutContent - ): Promise { - let document = this.database.getDocumentByDocumentId( - remoteVersion.documentId - ); + private async internalScheduleSyncForOfflineChanges(): Promise { + this.isScanning = true; + try { + this.queue.clearPending(); // can't have conflicts between the offline scan and ongoing operations created during the preceeding pause - if (document === undefined) { - // Let's avoid the same documents getting created in parallel multiple times. - // There might be multiple tasks waiting for the lock - return this.remoteDocumentsLock.withLock( - remoteVersion.documentId, - async () => { - document = this.database.getDocumentByDocumentId( - remoteVersion.documentId - ); - - // We're either the first one to get the lock, so we have to create the document in `unrestrictedSyncRemotelyUpdatedFile` - if (document === undefined) { - await this.syncQueue.add(async () => - this.internalSyncer.unrestrictedSyncRemotelyUpdatedFile( - remoteVersion - ) - ); - } else { - const [promise, resolve, reject] = createPromise(); - - document = - await this.database.getResolvedDocumentByRelativePath( - document.relativePath, - promise - ); - - try { - await this.syncQueue.add(async () => - this.internalSyncer.unrestrictedSyncRemotelyUpdatedFile( - remoteVersion, - document - ) - ); - - resolve(); - } catch (e) { - reject(e); - } finally { - this.database.removeDocumentPromise(promise); - } - } - - this.database.addSeenUpdateId(remoteVersion.vaultUpdateId); + await scheduleOfflineChanges( + this.logger, + this.operations, + this.queue, + (path) => { + this.syncLocallyCreatedFile(path); + }, + (args) => { + this.syncLocallyUpdatedFile(args); + }, + (path) => { + this.syncLocallyDeletedFile(path); } ); - } - - // We're either the first one to get the lock, so we have to create the document in `unrestrictedSyncRemotelyUpdatedFile` - const [promise, resolve, reject] = createPromise(); - - document = await this.database.getResolvedDocumentByRelativePath( - document.relativePath, - promise - ); - - try { - await this.syncQueue.add(async () => - this.internalSyncer.unrestrictedSyncRemotelyUpdatedFile( - remoteVersion, - document - ) - ); - - resolve(); - } catch (e) { - reject(e); } finally { - this.database.removeDocumentPromise(promise); + this.isScanning = false; } - this.database.addSeenUpdateId(remoteVersion.vaultUpdateId); + this.ensureDraining(); } - private async internalScheduleSyncForOfflineChanges(): Promise { - await this.createFakeDocumentsFromRemoteState(); - - const allLocalFiles = await this.operations.listFilesRecursively(); - this.logger.info( - `Scheduling sync for ${allLocalFiles.length} local files` - ); - - let locallyPossiblyDeletedFiles: DocumentRecord[] = []; - - for (const document of this.database.resolvedDocuments) { - if ( - !document.isDeleted && - !(await this.operations.exists(document.relativePath)) - ) { - locallyPossiblyDeletedFiles.push(document); - } + private ensureDraining(): void { + if (this.drainPromise !== undefined) { + this.drainRequestedWhileRunning = true; + return; } + if (this.isScanning) { + return; + } + if (this.isDrainingPaused) { + return; + } + this.drainPromise = this.drain().finally(() => { + this.drainPromise = undefined; + const shouldRestart = + this.drainRequestedWhileRunning && + this.queue.pendingUpdateCount > 0 && + !this.isScanning && + !this.isDrainingPaused && + this.settings.getSettings().isSyncEnabled; + this.drainRequestedWhileRunning = false; + if (shouldRestart) { + this.ensureDraining(); + } + }); + } - await awaitAll( - allLocalFiles.map(async (relativePath) => { - if ( - this.database.getLatestDocumentByRelativePath(relativePath) - ?.metadata !== undefined - ) { - this.logger.debug( - `Document ${relativePath} might have been updated locally, scheduling sync to validate and update it` - ); + private async drain(): Promise { + // Peek then remove-after-processing (instead of shift-then-process): + // the event must remain reachable through `findLatestCreateForPath` + // while it is in flight, so a rename event arriving mid-process can + // call `updatePendingCreatePath` to retarget this create's local path. + for (;;) { + if ( + this.isDrainingPaused || + !this.settings.getSettings().isSyncEnabled + ) { + this.logger.debug( + "Drain pausing because sync is disabled; events stay queued" + ); + return; + } + const event = this.queue.peekFront(); - return this.syncLocallyUpdatedFile({ - relativePath - }); - } + if (event === undefined) { + break; + } - // Perhaps the file has been moved; let's check by looking at the deleted files - const contentHash = await this.syncQueue.add(async () => { - const contentBytes = - await this.operations.read(relativePath); // this can throw FileNotFoundError - return hash(contentBytes); - }); - - if (contentHash == undefined) { - // The file was deleted before we had a chance to read it, no need to sync it here + try { + await this.processEvent(event); + } catch (e) { + if (e instanceof SyncResetError) { + this.logger.info("Drain interrupted by sync reset"); return; } - - const originalFile = findMatchingFile( - contentHash, - locallyPossiblyDeletedFiles + this.logger.error( + `Failed to process sync event ${event.type}: ${e}` ); - if (originalFile !== undefined) { - // `originalFile` hasn't been deleted but it got moved instead - /* eslint-disable no-restricted-syntax -- Comparing by property, not direct equality */ - locallyPossiblyDeletedFiles = - locallyPossiblyDeletedFiles.filter( - (item) => - item.relativePath !== originalFile.relativePath - ); - /* eslint-enable no-restricted-syntax */ - - this.logger.debug( - `Document '${originalFile.relativePath}' was not found under its current path in the database but was found under a different path (${relativePath}), scheduling sync to move it` - ); - - // We're outside of the pqueue, so we need to call the public wrapper - return this.syncLocallyUpdatedFile({ - oldPath: originalFile.relativePath, - relativePath - }); - } - - this.logger.debug( - `Document ${relativePath} not found in database, scheduling sync to create it` - ); - // We're outside of the pqueue, so we need to call the public wrapper - return this.syncLocallyCreatedFile(relativePath); - }) - ); - - // this has to happen strictly after the previous awaitAll, as that one - // might have removed some of the documents from the list - await awaitAll( - locallyPossiblyDeletedFiles.map(async ({ relativePath }) => { - this.logger.debug( - `Document ${relativePath} has been deleted locally, scheduling sync to delete it` - ); - - // We're outside of the pqueue, so we need to call the public wrapper - return this.syncLocallyDeletedFile(relativePath); - }) - ); + } + this.queue.consumeEvent(event); + // Reconciler runs after every wire-loop step; any record whose + // localPath drifted from remoteRelativePath gets a chance to + // converge before the next event. Best-effort — per-record + // failures are logged and retried on the next pass. + await this.reconciler.run(); + this.notifyRemainingOperationsChanged(); + } } - /** - * Create fake documents in the database for all files that are present locally - * and also exist remotely. This will stop the subequent syncs from duplicating - * the documents by creating the same documents from multiple clients. - */ - private async createFakeDocumentsFromRemoteState(): Promise { - if (this.database.getHasInitialSyncCompleted()) { + private async processEvent(event: SyncEvent): Promise { + try { + if (event.type === SyncEventType.LocalCreate) { + event.isProcessing = true; + } + + if (await this.skipIfOversized(event)) { + return; + } + + switch (event.type) { + case SyncEventType.LocalCreate: + await this.processCreate(event); + break; + case SyncEventType.LocalDelete: + await this.processDelete(event); + break; + case SyncEventType.LocalUpdate: + await this.processLocalUpdate(event); + break; + case SyncEventType.RemoteChange: + await this.processRemoteChange(event); + break; + } + } catch (e) { + // If a LocalCreate fails terminally, queued LocalDelete / + // LocalUpdate events whose `documentId` is this Create's + // `resolvers.promise` would `await` it forever — reject the + // resolver so they fail-fast with the same error class and + // hit their matching skip/log branch below. + // + // Only do this for terminal errors. `SyncResetError` is + // transient: drain returns without consuming the event, so + // the next drain retries the same Create. Rejecting the + // resolver now would permanently poison it, and the eventual + // `resolveCreate(...resolve)` after the retry succeeds is a + // no-op on an already-settled promise — leaving every + // dependent event stuck failing on `await event.documentId`. + if ( + event.type === SyncEventType.LocalCreate && + !(e instanceof SyncResetError) + ) { + event.resolvers.promise.catch(() => { + /* suppressed */ + }); + event.resolvers.reject(e); + } + + if (e instanceof FileNotFoundError) { + this.logger.info( + `Skipping sync event '${event.type}' because the file no longer exists` + ); + return; + } + if (e instanceof HttpClientError) { + this.logger.error( + `Server rejected ${event.type} request: ${e.message}` + ); + return; + } + throw e; + } + } + + private async skipIfOversized(event: SyncEvent): Promise { + let sizeInBytes = 0; + let relativePath: RelativePath = ""; + + switch (event.type) { + case SyncEventType.LocalDelete: + return false; + case SyncEventType.LocalCreate: + case SyncEventType.LocalUpdate: + sizeInBytes = await this.operations.getFileSize(event.path); + relativePath = event.path; + break; + case SyncEventType.RemoteChange: + if (event.remoteVersion.isDeleted) { + return false; + } + sizeInBytes = event.remoteVersion.contentSize; + ({ relativePath } = event.remoteVersion); + break; + } + + const oversizedEntry = this.getHistoryEntryForSkippedOversizedFile( + sizeInBytes, + relativePath + ); + if (oversizedEntry === undefined) { + return false; + } + + this.history.addHistoryEntry(oversizedEntry); + + if (event.type === SyncEventType.LocalCreate) { + event.resolvers.promise.catch(() => { + /* suppressed */ + }); + event.resolvers.reject(new Error("Create was cancelled")); + } + + // Advance the cursor so the server doesn't replay this update on every + // reconnect — the skip is permanent for this version. + if (event.type === SyncEventType.RemoteChange) { + this.queue.lastSeenUpdateId = event.remoteVersion.vaultUpdateId; + } + + return true; + } + + private getHistoryEntryForSkippedOversizedFile( + sizeInBytes: number, + relativePath: RelativePath + ): HistoryEntry | undefined { + const sizeInMB = Math.round(sizeInBytes / 1024 / 1024); + const { maxFileSizeMB } = this.settings.getSettings(); + if (sizeInMB > maxFileSizeMB) { + return { + status: SyncStatus.SKIPPED, + details: { + type: SyncType.SKIPPED as const, + relativePath + }, + message: `File size of ${sizeInMB} MB exceeds the maximum file size limit of ${maxFileSizeMB} MB`, + timestamp: new Date() + }; + } + } + + private async processCreate( + event: Extract + ): Promise { + const requestPath = event.path; + const contentBytes = await this.operations.read(requestPath); + const contentHash = await hash(contentBytes); + + // Use the path the pending create has when it reaches the wire loop. + // `updatePendingCreatePath` mutates queued creates when a not-yet-sent + // local file is renamed, so a renamed-away generation does not create + // a server document at a path that a newer local file has reused. + // + // `lastSeenUpdateIdForCreate(requestPath)` (rather than the contiguous + // `lastSeenUpdateId`) blocks the server from path-merging this POST + // into a doc we already track at the same path. Without that, a + // same-device rename race can alias two physically distinct local + // files onto one docId. See `SyncEventQueue.lastSeenUpdateIdForCreate`. + const response = await this.syncService.create({ + relativePath: requestPath, + lastSeenVaultUpdateId: + this.queue.lastSeenUpdateIdForCreate(requestPath), + contentBytes + }); + + // Same-docId collapse. While our LocalCreate sat in the queue, a + // RemoteCreate may have arrived for this same path. The wire-loop's + // `processRemoteCreateForNewDocument` would have built a record with + // `localPath === undefined` carrying the same docId the server is + // about to return us. `upsertRecord` keys by docId and merges in + // place, so the record we pass below collapses into that existing + // one — its claim is dropped and `localPath` becomes `event.path`. + // The reconciler will reconcile if `response.relativePath` differs. + let remoteHash = contentHash; + if (response.type === "MergingUpdate") { + const responseBytes = base64ToBytes(response.contentBase64); + // Read `event.path` live for both the write target and the + // cache key. A user rename arriving between HTTP-send and + // HTTP-response rewrites `event.path` via + // `updatePendingCreatePath`; the merge write must land on + // the current slot so the queued LocalUpdate that follows + // sees the merged bytes. + await this.operations.write( + event.path, + contentBytes, + responseBytes + ); + remoteHash = await hash(responseBytes); + await this.updateCache( + response.vaultUpdateId, + responseBytes, + event.path + ); + } else { + await this.updateCache( + response.vaultUpdateId, + contentBytes, + event.path + ); + } + + // Drop any stashed bytes for this docId — the file is on disk at + // event.path, so the reconciler shouldn't try to fetch & write + // its content. (The reconciler's job for this record is now just + // path placement, if needed.) + this.pendingPlacementContent.delete(response.documentId); + + // Snapshot `event.path` only after the write has settled. The + // write itself can drive synchronous watcher callbacks (e.g. + // an atomic-update fileSystemOperations that fires a "file + // changed" event back into the queue), and the test harness's + // user-facing renames also race here. Either path mutates + // `event.path` via `updatePendingCreatePath`; reading it once + // up front would lock in a stale slot and leave + // `record.localPath` pointing at a vacated path with no + // LocalRename ever materializing. + const localPath = event.path; + + await this.queue.resolveCreate(event, { + documentId: response.documentId, + parentVersionId: response.vaultUpdateId, + remoteRelativePath: response.relativePath, + remoteHash, + localPath + }); + + this.queue.lastSeenUpdateId = response.vaultUpdateId; + this.history.addHistoryEntry({ + status: SyncStatus.SUCCESS, + details: { type: SyncType.CREATE, relativePath: localPath }, + message: + response.type === "MergingUpdate" + ? "Created file and merged with existing remote version" + : "Successfully created file on the server", + author: response.userId, + timestamp: new Date(response.updatedDate) + }); + } + + private async processDelete( + event: Extract + ): Promise { + const documentId = await event.documentId; + const record = this.queue.getDocumentByDocumentId(documentId); + if ( + record?.localPath !== undefined && + record.localPath !== event.path + ) { + this.logger.debug( + `Skipping local-delete for ${documentId} at ${event.path}: ` + + `record now owns ${record.localPath}` + ); return; } - const [allLocalFiles, remote] = await awaitAll([ - this.operations.listFilesRecursively(), - this.syncQueue.add(async () => this.syncService.getAll()) - ]); + // The disk file is already gone when a LocalDelete reaches the wire + // loop. This is redundant for settled records deleted through + // `enqueue`, but load-bearing for creates that were deleted while the + // create request was still pending: their record only exists after the + // create ack resolves. + await this.queue.setLocalPath(documentId, undefined); - if (remote !== undefined) { - remote.latestDocuments - .filter( - (remoteDocument) => - allLocalFiles.includes(remoteDocument.relativePath) && - !remoteDocument.isDeleted && - this.database.getDocumentByDocumentId( - remoteDocument.documentId - ) === undefined - ) - .forEach((remoteDocument) => { - this.database.createNewEmptyDocument( - remoteDocument.documentId, - remoteDocument.vaultUpdateId, - remoteDocument.relativePath - ); - }); + const response = await this.syncService.delete({ + documentId + }); + + // Don't remove the doc from the queue or advance lastSeenUpdateId + // here. The server broadcasts the delete back to us over the + // WebSocket; that receipt drives `processRemoteDelete`'s cleanup + // and history entry. Keeping the entry in the map until then lets + // late remote updates be recognised as "file is missing" and + // skipped, instead of resurrecting the doc. + // + // Mark the doc as deletion-pending so the Reconciler doesn't + // resurrect it during the gap between HTTP-ack and WS-receipt. + // Without this, the LocalDelete enqueue's `setLocalPath(undefined)` + // leaves the record looking like a "needs initial placement" case + // to the Reconciler — which would then fetch the pre-delete bytes + // from the server and write them to disk. The mark also blocks + // any late RemoteChange from stashing pre-delete bytes into + // `pendingPlacementContent` (see processRemoteUpdate). The mark is + // cleared automatically by `removeDocumentById`. We also drop any + // already-stashed content for this doc since it cannot be placed. + this.queue.markServerDeletePending(documentId); + this.pendingPlacementContent.delete(documentId); + this.history.addHistoryEntry({ + status: SyncStatus.SUCCESS, + details: { + type: SyncType.DELETE, + relativePath: event.path + }, + message: "Successfully deleted file on the server", + author: response.userId, + timestamp: new Date(response.updatedDate) + }); + } + + private async processLocalUpdate( + event: Extract + ): Promise { + const documentId = await event.documentId; + + const record = this.queue.getDocumentByDocumentId(documentId); + if (record === undefined) { + // The doc was deleted between this event being queued and + // drained — skip silently. Common when a LocalDelete drains + // ahead of a LocalUpdate that was already in the queue. + this.logger.debug( + `Skipping local-update for ${documentId} — doc no longer tracked (deleted)` + ); + return; + } + // The record may exist with no local file (e.g. a pending-delete + // raced ahead and nulled out localPath). Nothing to upload from. + if (record.localPath === undefined) { + this.logger.debug( + `Skipping local-update for ${documentId} — record has no local file` + ); + return; + } + const contentBytes = await this.operations.read(record.localPath); + const contentHash = await hash(contentBytes); + + // For a user-driven rename the user's intent is `event.originalPath` + // — that's the rename target. For a content-only edit the user is + // agnostic to the path; sending one would be wrong if a remote + // rename processed first, because the server would interpret the + // user's (now-stale) path as a rename back. So content-only PUTs + // omit the path and the server keeps the doc at its current + // server-known location. + const renameTarget = event.isUserRename + ? event.originalPath + : undefined; + + const hashChanged = contentHash !== record.remoteHash; + const pathChanged = + renameTarget !== undefined && + record.remoteRelativePath !== renameTarget; + + if (!hashChanged && !pathChanged) { + this.logger.debug( + `File hash of ${record.localPath} matches last synced version; no need to sync` + ); + return; } - this.database.setHasInitialSyncCompleted(true); + const response = await this.sendUpdate({ + record, + relativePath: renameTarget, + contentBytes + }); + + if (response.isDeleted) { + await this.processRemoteDelete(record.localPath, { + ...response, + contentSize: 0, + isNewFile: false + }); + return; + } + + // Read `record.localPath` live via a fresh queue lookup: the + // queue's enqueue rename branch mutates the same record object + // in place across our await on `sendUpdate`, and a displaced-doc + // cleanup can null it out. The fresh lookup also re-widens the + // type back to `string | undefined` (the earlier guard narrowed + // it pre-await). The reconciler handles any further path + // placement after we write. + const livePath = + this.queue.getDocumentByDocumentId(documentId)?.localPath; + let remoteHash = contentHash; + if (response.type === "MergingUpdate") { + const responseBytes = base64ToBytes(response.contentBase64); + if (livePath !== undefined) { + await this.operations.write( + livePath, + contentBytes, + responseBytes + ); + } + remoteHash = await hash(responseBytes); + await this.updateCache( + response.vaultUpdateId, + responseBytes, + livePath ?? response.relativePath + ); + } else { + await this.updateCache( + response.vaultUpdateId, + contentBytes, + livePath ?? response.relativePath + ); + } + + await this.queue.upsertRecord({ + documentId: response.documentId, + parentVersionId: response.vaultUpdateId, + remoteRelativePath: response.relativePath, + remoteHash, + // localPath is owned by the watcher and the reconciler. Pass + // the value we observed pre-await purely as a hint for the + // placement-pending → placed transition; `upsertRecord` ignores + // it when an existing localPath is already set, so a watcher + // rename that landed during the HTTP roundtrip is preserved. + localPath: livePath + }); + this.queue.lastSeenUpdateId = response.vaultUpdateId; + + this.history.addHistoryEntry({ + status: SyncStatus.SUCCESS, + details: { + type: SyncType.UPDATE, + relativePath: livePath ?? response.relativePath + }, + message: + response.type === "MergingUpdate" + ? "Updated file and merged with remote changes" + : "Successfully updated file on the server", + author: response.userId, + timestamp: new Date(response.updatedDate) + }); + } + + private async processRemoteChange( + event: Extract + ): Promise { + const { remoteVersion } = event; + const trackedRecord = this.queue.getDocumentByDocumentId( + remoteVersion.documentId + ); + + if (remoteVersion.isDeleted) { + if (trackedRecord === undefined) { + // The doc isn't tracked locally — either we never had + // it (joined the vault after the delete) or a previous + // delete already cleaned it up. Just advance + // `lastSeenUpdateId` so we don't replay this on the + // next reconnect. + this.queue.lastSeenUpdateId = remoteVersion.vaultUpdateId; + return; + } + return this.processRemoteDelete( + trackedRecord.localPath, + remoteVersion + ); + } + + if ( + (trackedRecord?.parentVersionId ?? 0) >= remoteVersion.vaultUpdateId + ) { + this.queue.lastSeenUpdateId = remoteVersion.vaultUpdateId; + this.logger.debug( + `Document ${remoteVersion.relativePath} is already up-to-date or has newer local changes; skipping remote update` + ); + return; + } + + // Server-side delete is in flight: our HTTP DELETE has been acked + // but the WebSocket receipt that would `removeDocumentById` hasn't + // arrived yet. Any remote update we apply here would resurrect the + // doc — either by writing the pre-delete bytes to disk + // (`processRemoteUpdate` with localPath set) or by stashing them + // for the Reconciler (`processRemoteUpdate` with localPath + // undefined; reconciler is also gated, but stashing leaves + // `pendingPlacementContent` lingering which a same-docId + // re-creation could later misuse). Advance the watermark and + // discard; the eventual delete-receipt will clean up the record. + if ( + trackedRecord !== undefined && + this.queue.hasPendingServerDelete(trackedRecord.documentId) + ) { + this.queue.lastSeenUpdateId = remoteVersion.vaultUpdateId; + this.logger.debug( + `Discarding remote update for ${remoteVersion.documentId}: ` + + `local HTTP DELETE has been acked; awaiting WS receipt` + ); + return; + } + + if (trackedRecord !== undefined) { + // The doc is tracked, but the disk slot can be stale. One + // concrete race: a remote create quick-writes a file, a + // watcher rename/delete lands before the record is fully + // settled, and the record is left claiming a path that no + // longer exists. If no queued local operation owns that + // disappearance, clear the localPath and let + // processRemoteUpdate stash/place the active server version. + if (trackedRecord.localPath !== undefined) { + const fileExists = await this.operations.exists( + trackedRecord.localPath + ); + if ( + !fileExists && + !this.queue.hasPendingLocalEventsForDocumentId( + remoteVersion.documentId + ) + ) { + this.logger.debug( + `Remote update for ${remoteVersion.documentId}: ` + + `local file at ${trackedRecord.localPath} is missing; ` + + `clearing localPath for placement` + ); + await this.queue.setLocalPath( + trackedRecord.documentId, + undefined + ); + } + } + return this.processRemoteUpdate(trackedRecord, remoteVersion); + } + + if (!remoteVersion.isNewFile) { + this.queue.lastSeenUpdateId = remoteVersion.vaultUpdateId; + this.logger.debug( + `Ignoring stale RemoteChange for untracked, non-new document ${remoteVersion.documentId}` + ); + return; + } + + return this.processRemoteCreateForNewDocument(remoteVersion); + } + + private async processRemoteDelete( + localPath: RelativePath | undefined, + remoteVersion: DocumentVersionWithoutContent + ): Promise { + if (localPath !== undefined) { + // Verify the record still owns this disk slot before deleting. + // A same-path recreate (LocalCreate at this path resolving + // after we sent the server-delete for this doc) installs a + // new doc into byLocalPath but doesn't clear the old record's + // stale `localPath` field. When the WS broadcast for the old + // doc's deletion arrives, naively deleting at `localPath` + // would clobber the new doc's file. Skip the disk delete + // when the slot now belongs to a different doc; the queue + // record cleanup below still runs. + const currentOwner = this.queue.byLocalPath.get(localPath); + if ( + currentOwner === undefined || + currentOwner.documentId === remoteVersion.documentId + ) { + await this.operations.delete(localPath); + } else { + this.logger.debug( + `Skipping disk delete for ${remoteVersion.documentId} at ${localPath}: ` + + `slot is now owned by ${currentOwner.documentId}` + ); + } + } + await this.queue.removeDocumentById(remoteVersion.documentId); + + this.queue.lastSeenUpdateId = remoteVersion.vaultUpdateId; + + this.history.addHistoryEntry({ + status: SyncStatus.SUCCESS, + details: { + type: SyncType.DELETE, + relativePath: localPath ?? remoteVersion.relativePath + }, + message: + "Successfully deleted file which had been deleted remotely", + author: remoteVersion.userId, + timestamp: new Date(remoteVersion.updatedDate) + }); + } + + private async processRemoteUpdate( + record: DocumentRecord, + remoteVersion: DocumentVersionWithoutContent + ): Promise { + if ( + this.queue.hasPendingLocalEventsForDocumentId( + remoteVersion.documentId + ) + ) { + // The user has queued local edits for this doc. Apply them + // first — they'll round-trip to the server, get merged + // there, and broadcast back. If we processed this remote + // update now, `FileOperations.write` would receive + // `expected = current = the disk content (which already + // includes the user's pending edits)`, so the 3-way merge + // baseline collapses to "no local change vs base" and + // returns `theirs`, silently dropping the user's bytes. + // Re-enqueueing (rather than just deferring with a flag) + // is correct because by the time the queued local events + // drain, this remote update may be stale: our + // `parentVersionId` advances past `remoteVersion.vaultUpdateId`, + // and the next pass's standard "stale" check at the top of + // `processRemoteChange` will discard it. + // + // Broader concern (out of scope here): the 3-way merge + // baseline in `FileOperations.write` is the most-recent + // disk read at every callsite, not the previous server + // version. That's correct for the post-server-merge writes + // in `processCreate` / `processLocalUpdate` (we're + // applying the server's merged result to our potentially + // newer disk state), but fundamentally wrong as a base for + // a true 3-way merge. The defer gate above sidesteps the + // only call pattern where it actually loses data today. + void this.syncRemotelyUpdatedFile({ document: remoteVersion }); + return; + } + + const remoteContent = await this.syncService.getDocumentVersionContent({ + documentId: remoteVersion.documentId, + vaultUpdateId: remoteVersion.vaultUpdateId + }); + + // `record.localPath` may be undefined — the record was created on + // a previous remote-create whose target slot was occupied at + // receive time. In that case stash the bytes for the reconciler + // to write when it places the file; we still update the wire + // fields so the catch-up doesn't replay this version. + // + // The slot may also have been shadowed: the record still claims + // `localPath = P`, but `byLocalPath[P]` now points at a different + // doc (a same-path recreate installed a new owner without + // clearing this record's stale field — same race shape as the + // processRemoteDelete fix above). Writing to a shadowed slot + // would clobber the new owner's bytes. Clear the stale claim now + // so the reconciler treats this record as placement-pending; the + // closing `upsertRecord` no longer touches an existing record's + // localPath, so the clear has to happen explicitly here. + const claimedPath = record.localPath; + const livePath = + claimedPath !== undefined && + this.queue.byLocalPath.get(claimedPath)?.documentId === + record.documentId + ? claimedPath + : undefined; + if (claimedPath !== undefined && livePath === undefined) { + this.logger.debug( + `Remote update for ${record.documentId} at claimed ${claimedPath} ` + + `but slot is shadowed; clearing stale claim and deferring to reconciler` + ); + await this.queue.setLocalPath(record.documentId, undefined); + } + if (livePath !== undefined) { + const currentContent = await this.operations.read(livePath); + // Re-check the entry-time gate immediately before the disk + // mutation. The `await`s on `getDocumentVersionContent` and + // `read` open a TOCTOU window during which a LocalUpdate + // for this doc could have been enqueued by the watcher. If + // we proceeded, `operations.write` would receive + // `expected = current = disk-content-already-with-user-bytes`, + // collapsing the 3-way merge baseline and silently + // overwriting the user's pending edits with `theirs`. + // Re-enqueueing the RemoteChange is the same fix shape as + // the entry-time gate above; the next pass either applies + // it or discards it as stale via the standard check at the + // top of `processRemoteChange`. + if ( + this.queue.hasPendingLocalEventsForDocumentId( + remoteVersion.documentId + ) + ) { + void this.syncRemotelyUpdatedFile({ document: remoteVersion }); + return; + } + // Re-check shadowing as well: the same TOCTOU window + // (between `getDocumentVersionContent` and `read`, plus + // `read` itself) could see a same-path recreate steal the + // slot. If we lost ownership, fall through to the + // pendingPlacementContent stash by re-entering the + // RemoteChange — the next pass observes the updated + // byLocalPath and routes correctly. + if ( + this.queue.byLocalPath.get(livePath)?.documentId !== + record.documentId + ) { + void this.syncRemotelyUpdatedFile({ document: remoteVersion }); + return; + } + await this.operations.write( + livePath, + currentContent, + remoteContent + ); + await this.updateCache( + remoteVersion.vaultUpdateId, + remoteContent, + livePath + ); + } else { + this.pendingPlacementContent.set( + remoteVersion.documentId, + remoteContent + ); + await this.updateCache( + remoteVersion.vaultUpdateId, + remoteContent, + remoteVersion.relativePath + ); + } + + await this.queue.upsertRecord({ + documentId: record.documentId, + parentVersionId: remoteVersion.vaultUpdateId, + remoteRelativePath: remoteVersion.relativePath, + remoteHash: await hash(remoteContent), + localPath: livePath + }); + this.queue.lastSeenUpdateId = remoteVersion.vaultUpdateId; + + this.history.addHistoryEntry({ + status: SyncStatus.SUCCESS, + details: { + type: SyncType.UPDATE, + relativePath: livePath ?? remoteVersion.relativePath + }, + message: "Successfully applied remote update", + author: remoteVersion.userId, + timestamp: new Date(remoteVersion.updatedDate) + }); + } + + private async processRemoteCreateForNewDocument( + remoteVersion: DocumentVersionWithoutContent + ): Promise { + // Quick-write optimization: if the target slot is free right now + // (no disk file, no tracked record), fetch and write inline. The + // catch-up replay leans on this — without it, a freshly-joined + // client would upsert every doc with `localPath = undefined` + // and rely on the reconciler to fetch each one back. + // + // If the slot is occupied, defer: leave `localPath = undefined` + // and let the reconciler place once the slot frees. Per the + // design, no buffering at receive time — the reconciler will + // fetch on demand. + const target = remoteVersion.relativePath; + const slotFree = await this.canPlaceRemoteCreateAt(target); + + let localPath: RelativePath | undefined = undefined; + let remoteHash: string | undefined = undefined; + if (slotFree) { + const remoteContent = + await this.syncService.getDocumentVersionContent({ + documentId: remoteVersion.documentId, + vaultUpdateId: remoteVersion.vaultUpdateId + }); + if (!(await this.canPlaceRemoteCreateAt(target))) { + this.logger.debug( + `Quick-write for ${remoteVersion.documentId} at ${target} ` + + `became blocked while fetching content; deferring to reconciler` + ); + } else { + try { + remoteHash = await hash(remoteContent); + await this.queue.upsertRecord({ + documentId: remoteVersion.documentId, + parentVersionId: remoteVersion.vaultUpdateId, + remoteRelativePath: remoteVersion.relativePath, + remoteHash, + localPath: target + }); + const result = await this.operations.create( + target, + remoteContent + ); + const liveRecord = this.queue.getDocumentByDocumentId( + remoteVersion.documentId + ); + localPath = + liveRecord === undefined + ? result.actualPath + : liveRecord.localPath; + await this.updateCache( + remoteVersion.vaultUpdateId, + remoteContent, + localPath ?? remoteVersion.relativePath + ); + } catch (e) { + await this.queue.setLocalPath( + remoteVersion.documentId, + undefined + ); + if (!(e instanceof FileAlreadyExistsError)) { + throw e; + } + // TOCTOU: the slot was free at the pre-check but + // something landed there between then and now. Fall + // through to the no-localPath branch and let the + // reconciler retry placement once the slot frees. + this.logger.debug( + `Quick-write for ${remoteVersion.documentId} at ${target} ` + + `lost a TOCTOU race; deferring to reconciler` + ); + localPath = undefined; + } + } + } + + if ( + this.queue.getDocumentByDocumentId(remoteVersion.documentId) === + undefined + ) { + await this.queue.upsertRecord({ + documentId: remoteVersion.documentId, + parentVersionId: remoteVersion.vaultUpdateId, + remoteRelativePath: remoteVersion.relativePath, + // `remoteHash` is undefined when we deferred fetching content. + // Consumers (`processLocalUpdate`'s fast-skip, + // `findMatchingFile`'s offline-rename detection) treat + // undefined as "no comparison possible" and fall through to a + // real upload / no-match. The hash gets populated the next + // time we observe a real version (a remote update, or a + // local edit that triggers an upload). + remoteHash, + localPath + }); + } + + this.queue.lastSeenUpdateId = remoteVersion.vaultUpdateId; + + if (localPath !== undefined) { + this.history.addHistoryEntry({ + status: SyncStatus.SUCCESS, + details: { + type: SyncType.CREATE, + relativePath: localPath + }, + message: + "Successfully downloaded remote file which hadn't existed locally", + author: remoteVersion.userId, + timestamp: new Date(remoteVersion.updatedDate) + }); + } + } + + private async canPlaceRemoteCreateAt( + target: RelativePath + ): Promise { + return ( + !this.queue.hasPendingCreateForPath(target) && + !(await this.operations.exists(target)) && + this.queue.getRecordByLocalPath(target) === undefined + ); + } + + private async sendUpdate({ + record, + relativePath, + contentBytes + }: { + record: DocumentRecord; + // `undefined` for content-only edits; the server keeps the doc's + // current path. A string is sent only on a user-driven rename. + relativePath: RelativePath | undefined; + contentBytes: Uint8Array; + }): Promise { + const isText = + !isBinary(contentBytes) && + isFileTypeMergable( + relativePath ?? record.remoteRelativePath, + (await this.serverConfig.getConfig()).mergeableFileExtensions + ); + + const cachedVersion = this.contentCache.get(record.parentVersionId); + + if (isText && cachedVersion !== undefined) { + return this.syncService.putText({ + documentId: record.documentId, + parentVersionId: record.parentVersionId, + relativePath, + content: diff( + new TextDecoder().decode(cachedVersion), + new TextDecoder().decode(contentBytes) + ) + }); + } + + return this.syncService.putBinary({ + documentId: record.documentId, + parentVersionId: record.parentVersionId, + relativePath, + contentBytes + }); + } + + private async updateCache( + updateId: VaultUpdateId, + contentBytes: Uint8Array, + filePath: RelativePath + ): Promise { + if ( + isFileTypeMergable( + filePath, + (await this.serverConfig.getConfig()).mergeableFileExtensions + ) && + !isBinary(contentBytes) + ) { + this.contentCache.put(updateId, contentBytes); + } + } + + private notifyRemainingOperationsChanged(): void { + const currentCount = this.queue.pendingUpdateCount; + if (this.previousRemainingOperationsCount !== currentCount) { + this.previousRemainingOperationsCount = currentCount; + this.onRemainingOperationsCountChanged.trigger(currentCount); + } } } diff --git a/frontend/sync-client/src/sync-operations/types.ts b/frontend/sync-client/src/sync-operations/types.ts new file mode 100644 index 00000000..80a64cd7 --- /dev/null +++ b/frontend/sync-client/src/sync-operations/types.ts @@ -0,0 +1,74 @@ +import type { DocumentVersionWithoutContent } from "../services/types/DocumentVersionWithoutContent"; + +export type VaultUpdateId = number; +export type DocumentId = string; +export type RelativePath = string; + +export interface DocumentRecord { + documentId: DocumentId; + parentVersionId: VaultUpdateId; + // Hash of the last server version this client has observed for the doc. + // `undefined` means we have a record but haven't actually seen content + // yet — typically a remote-create whose target slot was occupied at + // receive time, where we deliberately defer the fetch to the reconciler. + // Consumers should treat undefined as "no comparison possible" (the + // fast-skip in `processLocalUpdate` falls through to a real upload). + remoteHash: string | undefined; + remoteRelativePath: RelativePath; + // Where the doc's file currently lives on disk. `undefined` means the doc + // has no local file yet — happens for a remote create whose + // `remoteRelativePath` slot was occupied at receive time. The reconciler + // will place the file once the slot frees, fetching content from the + // server on demand. + localPath: RelativePath | undefined; +} + +export interface StoredSyncState { + schemaVersion: number; + documents: DocumentRecord[] | undefined; + lastSeenUpdateId: VaultUpdateId | undefined; +} + +export enum SyncEventType { + LocalCreate = "local-create", + LocalUpdate = "local-update", // includes both content and path changes + LocalDelete = "local-delete", + RemoteChange = "remote-change" // includes every type of create/update/delete coming from the server +} + +export type FileSyncEvent = + | { type: SyncEventType.LocalCreate; path: RelativePath } + | { + type: SyncEventType.LocalUpdate; + path: RelativePath; + oldPath?: RelativePath; // oldPath is undefined for content changes + } + | { type: SyncEventType.LocalDelete; path: RelativePath } + | { + type: SyncEventType.RemoteChange; + remoteVersion: DocumentVersionWithoutContent; + }; + +export type SyncEvent = + | { + type: SyncEventType.LocalCreate; + path: RelativePath; // current path on disk; mutated in place by `updatePendingCreatePath` when the user renames mid-flight + isProcessing: boolean; // true once the wire loop has started this create; deletes after that must wait for the server ack + resolvers: PromiseWithResolvers; + } + | { + type: SyncEventType.LocalUpdate; + documentId: DocumentId | Promise; // if it's a promise, the promise is fulfilled once the document's create event is processed + path: RelativePath; // current path on disk + originalPath: RelativePath; // original path on disk when the event was queued + isUserRename: boolean; // true iff this event was queued because the user renamed the file + } + | { + type: SyncEventType.LocalDelete; + documentId: DocumentId | Promise; // if it's a promise, the promise is fulfilled once the document's create event is processed + path: RelativePath; // only used for showing on the UI + } + | { + type: SyncEventType.RemoteChange; + remoteVersion: DocumentVersionWithoutContent; + }; diff --git a/frontend/sync-client/src/sync-operations/unrestricted-syncer.ts b/frontend/sync-client/src/sync-operations/unrestricted-syncer.ts deleted file mode 100644 index e3964d30..00000000 --- a/frontend/sync-client/src/sync-operations/unrestricted-syncer.ts +++ /dev/null @@ -1,596 +0,0 @@ -import type { - Database, - DocumentRecord, - RelativePath -} from "../persistence/database"; - -import { diff } from "reconcile-text"; -import type { SyncService } from "../services/sync-service"; -import type { Logger } from "../tracing/logger"; -import type { - CommonHistoryEntry, - SyncCreateDetails, - SyncDeleteDetails, - SyncDetails, - SyncHistory, - SyncMovedDetails, - SyncUpdateDetails -} from "../tracing/sync-history"; -import { SyncStatus, SyncType } from "../tracing/sync-history"; -import { EMPTY_HASH, hash } from "../utils/hash"; - -import { base64ToBytes } from "byte-base64"; -import type { Settings } from "../persistence/settings"; -import type { FileOperations } from "../file-operations/file-operations"; -import { createPromise } from "../utils/create-promise"; -import { FileNotFoundError } from "../file-operations/file-not-found-error"; -import { SyncResetError } from "../services/sync-reset-error"; -import { globsToRegexes } from "../utils/globs-to-regexes"; -import type { DocumentVersion } from "../services/types/DocumentVersion"; -import type { DocumentUpdateResponse } from "../services/types/DocumentUpdateResponse"; -import type { DocumentVersionWithoutContent } from "../services/types/DocumentVersionWithoutContent"; -import type { FixedSizeDocumentCache } from "../utils/data-structures/fix-sized-cache"; -import { isFileTypeMergable } from "../utils/is-file-type-mergable"; -import { isBinary } from "../utils/is-binary"; -import type { ServerConfig } from "../services/server-config"; - -export class UnrestrictedSyncer { - private ignorePatterns: RegExp[]; - - public constructor( - private readonly logger: Logger, - private readonly database: Database, - private readonly settings: Settings, - private readonly syncService: SyncService, - private readonly operations: FileOperations, - private readonly history: SyncHistory, - private readonly contentCache: FixedSizeDocumentCache, - private readonly serverConfig: ServerConfig - ) { - this.ignorePatterns = globsToRegexes( - this.settings.getSettings().ignorePatterns, - this.logger - ); - - this.settings.onSettingsChanged.add((newSettings) => { - this.ignorePatterns = globsToRegexes( - newSettings.ignorePatterns, - this.logger - ); - }); - } - - public async unrestrictedSyncLocallyCreatedFile( - document: DocumentRecord - ): Promise { - const updateDetails: SyncCreateDetails = { - type: SyncType.CREATE, - relativePath: document.relativePath - }; - - return this.executeSync(updateDetails, async () => { - const originalRelativePath = document.relativePath; - if (document.isDeleted) { - this.logger.debug( - `Document ${originalRelativePath} has been already deleted, no need to create it` - ); - return; - } - - const contentBytes = - await this.operations.read(originalRelativePath); // this can throw FileNotFoundError - const contentHash = hash(contentBytes); - - const response = await this.syncService.create({ - documentId: document.documentId, - relativePath: originalRelativePath, - contentBytes - }); - - // In case a document with the same name (but different ID) had existed remotely that we haven't known about - if (response.relativePath != originalRelativePath) { - this.logger.debug( - `Document ${originalRelativePath} has been created remotely at a different path: ${response.relativePath}, moving it locally` - ); - await this.operations.move( - document.relativePath, - response.relativePath - ); // this can throw FileNotFoundError - } - - this.database.updateDocumentMetadata( - { - parentVersionId: response.vaultUpdateId, - hash: contentHash, - remoteRelativePath: response.relativePath - }, - document - ); - - this.database.addSeenUpdateId(response.vaultUpdateId); - await this.updateCache( - response.vaultUpdateId, - contentBytes, - response.relativePath - ); - - this.history.addHistoryEntry({ - status: SyncStatus.SUCCESS, - details: updateDetails, - message: `Successfully uploaded locally created file` - }); - }); - } - - public async unrestrictedSyncLocallyDeletedFile( - document: DocumentRecord - ): Promise { - const updateDetails: SyncDeleteDetails = { - type: SyncType.DELETE, - relativePath: document.relativePath - }; - - await this.executeSync(updateDetails, async () => { - const response = await this.syncService.delete({ - documentId: document.documentId, - relativePath: document.relativePath - }); - - this.database.updateDocumentMetadata( - { - parentVersionId: response.vaultUpdateId, - hash: EMPTY_HASH, - remoteRelativePath: document.relativePath - }, - document - ); - - this.database.addSeenUpdateId(response.vaultUpdateId); - - this.history.addHistoryEntry({ - status: SyncStatus.SUCCESS, - details: updateDetails, - message: `Successfully deleted locally deleted file on the server`, - author: response.userId - }); - }); - } - - public async unrestrictedSyncLocallyUpdatedFile({ - oldPath, - document, - // We use the same code path for both local and remote updates. We need to force the update - // if there are no local changes but we know that the remote version is newer. - force = false - }: { - oldPath?: RelativePath; - force?: boolean; - document: DocumentRecord; - }): Promise { - const updateDetails: SyncUpdateDetails | SyncMovedDetails = - oldPath !== undefined - ? { - type: SyncType.MOVE, - relativePath: document.relativePath, - movedFrom: oldPath - } - : { - type: SyncType.UPDATE, - relativePath: document.relativePath - }; - - await this.executeSync(updateDetails, async () => { - const originalRelativePath = document.relativePath; - - if (document.isDeleted || document.metadata === undefined) { - this.logger.debug( - `Document ${document.relativePath} has been already deleted, no need to update it` - ); - return; - } - - const contentBytes = await this.operations.read( - document.relativePath - ); // this can throw FileNotFoundError - let contentHash = hash(contentBytes); - - const areThereLocalChanges = !( - document.metadata.hash === contentHash && oldPath === undefined - ); - - let response: DocumentVersion | DocumentUpdateResponse | undefined = - undefined; - - if (areThereLocalChanges) { - const isText = - !isBinary(contentBytes) && - isFileTypeMergable( - document.relativePath, - (await this.serverConfig.getConfig()) - .mergeableFileExtensions - ); - const cachedVersion = this.contentCache.get( - document.metadata.parentVersionId - ); - - response = - isText && cachedVersion !== undefined - ? await this.syncService.putText({ - documentId: document.documentId, - parentVersionId: - document.metadata.parentVersionId, - relativePath: document.relativePath, - content: diff( - new TextDecoder().decode(cachedVersion), - new TextDecoder().decode(contentBytes) - ) - }) - : await this.syncService.putBinary({ - documentId: document.documentId, - parentVersionId: - document.metadata.parentVersionId, - relativePath: document.relativePath, - contentBytes - }); - } else { - if (!force) { - this.logger.debug( - `File hash of ${document.relativePath} matches with last synced version and the path hasn't changed; no need to sync` - ); - return; - } - - response = await this.syncService.get({ - documentId: document.documentId - }); - } - - // `document` is mutable and reflects the latest state in the local database - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (document.isDeleted) { - this.logger.info( - `Document ${document.relativePath} has been deleted before we could finish updating it` - ); - this.database.addSeenUpdateId(response.vaultUpdateId); - return; - } - - if ( - // `Syncer` creates fake local document metadata for all remote docs with invalid hashes. The parent IDs will likely match - // the latest versions so we still need to update the local versions to turn the fakes into real metadata. - document.metadata.parentVersionId > response.vaultUpdateId - ) { - this.logger.debug( - `Document ${document.relativePath} is already more up to date than the fetched version` - ); - this.database.addSeenUpdateId(response.vaultUpdateId); // in case the previous `vaultUpdateId` update hasn't made it through - return; - } - - if (response.isDeleted) { - return this.applyRemoteDeleteLocally(document, response); - } - - let actualPath = document.relativePath; - - if (response.relativePath != originalRelativePath) { - actualPath = response.relativePath; - // Make sure to update the remote relative path to avoid uploading - // the file as a result of this filesystem event. - document.metadata.remoteRelativePath = response.relativePath; - await this.operations.move( - document.relativePath, - response.relativePath - ); // this can throw FileNotFoundError - } - - if (!("type" in response) || response.type === "MergingUpdate") { - const responseBytes = base64ToBytes(response.contentBase64); - contentHash = hash(responseBytes); - - this.database.updateDocumentMetadata( - { - parentVersionId: response.vaultUpdateId, - hash: contentHash, - remoteRelativePath: response.relativePath - }, - document - ); - await this.operations.write( - actualPath, - contentBytes, - responseBytes - ); - await this.updateCache( - response.vaultUpdateId, - responseBytes, - actualPath - ); - - if (!force) { - this.history.addHistoryEntry({ - status: SyncStatus.SUCCESS, - details: updateDetails, - message: `The file we updated had been updated remotely, so we downloaded the merged version` - }); - } - } else { - this.database.updateDocumentMetadata( - { - parentVersionId: response.vaultUpdateId, - hash: contentHash, - remoteRelativePath: response.relativePath - }, - document - ); - await this.updateCache( - response.vaultUpdateId, - contentBytes, - actualPath - ); - } - - this.database.addSeenUpdateId(response.vaultUpdateId); - - const actualUpdateDetails: SyncUpdateDetails | SyncMovedDetails = - oldPath !== undefined || - response.relativePath != originalRelativePath - ? { - type: SyncType.MOVE, - relativePath: response.relativePath, - movedFrom: originalRelativePath - } - : { - type: SyncType.UPDATE, - relativePath: response.relativePath - }; - - if (areThereLocalChanges) { - this.history.addHistoryEntry({ - status: SyncStatus.SUCCESS, - details: actualUpdateDetails, - message: `Successfully uploaded locally updated file to the server`, - author: response.userId - }); - } else { - this.history.addHistoryEntry({ - status: SyncStatus.SUCCESS, - details: actualUpdateDetails, - message: `Successfully downloaded remotely updated file from the server`, - author: response.userId, - timestamp: new Date(response.updatedDate) - }); - } - }); - } - - public async unrestrictedSyncRemotelyUpdatedFile( - remoteVersion: DocumentVersionWithoutContent, - document?: DocumentRecord - ): Promise { - const updateDetails: SyncCreateDetails = { - type: SyncType.CREATE, - relativePath: remoteVersion.relativePath - }; - - await this.executeSync(updateDetails, async () => { - if (document?.metadata !== undefined) { - // If the file exists locally, let's pretend the user has updated it - // and deal with remote update/deletion within `unrestrictedSyncLocallyUpdatedFile` - if ( - document.metadata.parentVersionId >= - remoteVersion.vaultUpdateId - ) { - this.logger.debug( - `Document ${remoteVersion.relativePath} is already at least as up to date as the fetched version` - ); - - return; - } - - return this.unrestrictedSyncLocallyUpdatedFile({ - document, - force: true - }); - } else if (remoteVersion.isDeleted) { - // Either the document hasn't made it to us before and therefore we don't need to delete it, - // or we already have it, in which case the preceeding if would've dealt with it - this.logger.debug( - `Document ${remoteVersion.relativePath} has been deleted remotely, no need to sync` - ); - return; - } - - // Don't download oversized files - const historyEntryForSkippedOversizedFile = - this.getHistoryEntryForSkippedOversizedFile( - remoteVersion.contentSize, - remoteVersion.relativePath - ); - if (historyEntryForSkippedOversizedFile !== undefined) { - this.history.addHistoryEntry( - historyEntryForSkippedOversizedFile - ); - return; - } - - const contentBytes = - await this.syncService.getDocumentVersionContent({ - documentId: remoteVersion.documentId, - vaultUpdateId: remoteVersion.vaultUpdateId - }); - - // We're trying to create an entirely new document that didn't exist locally - document = this.database.getDocumentByDocumentId( - remoteVersion.documentId - ); - // It can happen that a concurrent sync operation has already created the document, so we can bail here - if (document !== undefined) { - this.logger.debug( - `Document ${remoteVersion.relativePath} has already been created locally, no need to create it again` - ); - return; - } - - await this.operations.ensureClearPath(remoteVersion.relativePath); - - const [promise, resolve] = createPromise(); - this.database.updateDocumentMetadata( - { - parentVersionId: remoteVersion.vaultUpdateId, - hash: hash(contentBytes), - remoteRelativePath: remoteVersion.relativePath - }, - this.database.createNewPendingDocument( - remoteVersion.documentId, - remoteVersion.relativePath, - promise - ) - ); - - await this.operations.create( - remoteVersion.relativePath, - contentBytes - ); - await this.updateCache( - remoteVersion.vaultUpdateId, - contentBytes, - remoteVersion.relativePath - ); - - resolve(); - this.database.removeDocumentPromise(promise); - - this.history.addHistoryEntry({ - status: SyncStatus.SUCCESS, - details: updateDetails, - message: `Successfully downloaded remote file which hadn't existed locally`, - author: remoteVersion.userId, - timestamp: new Date(remoteVersion.updatedDate) - }); - }); - } - - public async executeSync( - details: SyncDetails, - fn: () => Promise - ): Promise { - for (const pattern of this.ignorePatterns) { - if (pattern.test(details.relativePath)) { - this.logger.debug( - `File '${details.relativePath}' is ignored by the ignore pattern: ${pattern}` - ); - return; // bail without SKIPPED status because we were told to ignore this file and we shouldn't clutter up the history - } - } - - try { - // Only check the size of files which already exist locally. - if (await this.operations.exists(details.relativePath)) { - const sizeInBytes = await this.operations.getFileSize( - details.relativePath - ); - const historyEntryForSkippedOversizedFile = - this.getHistoryEntryForSkippedOversizedFile( - sizeInBytes, - details.relativePath - ); - if (historyEntryForSkippedOversizedFile !== undefined) { - this.history.addHistoryEntry( - historyEntryForSkippedOversizedFile - ); - return; - } - } - - return await fn(); - } catch (e) { - if (e instanceof FileNotFoundError) { - // A subsequent sync operation must have been creating to deal with this - this.logger.info( - `Skiping file '${details.relativePath}' because it no longer exists when trying to ${details.type.toLocaleLowerCase()} it` - ); - return; - } - if (e instanceof SyncResetError) { - this.logger.info( - `Interrupting sync operation because of a reset` - ); - return; - } else { - this.history.addHistoryEntry({ - status: SyncStatus.ERROR, - details, - message: `Failed to sync file '${details.relativePath}' because of ${e} when trying to ${details.type.toLocaleLowerCase()} it` - }); - throw e; - } - } - } - - private getHistoryEntryForSkippedOversizedFile( - sizeInBytes: number, - relativePath: RelativePath - ): CommonHistoryEntry | undefined { - const sizeInMB = Math.round(sizeInBytes / 1024 / 1024); - const { maxFileSizeMB } = this.settings.getSettings(); - if (sizeInMB > maxFileSizeMB) { - return { - status: SyncStatus.SKIPPED, - details: { - type: SyncType.SKIPPED, - relativePath - }, - message: `File size of ${sizeInMB} MB exceeds the maximum file size limit of ${ - maxFileSizeMB - } MB` - }; - } - } - - private async updateCache( - updateId: number, - contentBytes: Uint8Array, - filePath: RelativePath - ): Promise { - if ( - isFileTypeMergable( - filePath, - (await this.serverConfig.getConfig()).mergeableFileExtensions - ) && - !isBinary(contentBytes) - ) { - this.contentCache.put(updateId, contentBytes); - } - } - - private async applyRemoteDeleteLocally( - document: DocumentRecord, - response: DocumentVersion | DocumentUpdateResponse - ): Promise { - this.history.addHistoryEntry({ - status: SyncStatus.SUCCESS, - details: { - type: SyncType.DELETE, - relativePath: document.relativePath - }, - message: "File has been deleted remotely, so we deleted it locally", - author: response.userId, - timestamp: new Date(response.updatedDate) - }); - - this.database.delete(document.relativePath); - this.database.updateDocumentMetadata( - { - parentVersionId: response.vaultUpdateId, - hash: EMPTY_HASH, - remoteRelativePath: response.relativePath - }, - document - ); - - await this.operations.delete(document.relativePath); - - this.database.addSeenUpdateId(response.vaultUpdateId); - } -} diff --git a/frontend/sync-client/src/tracing/sync-history.ts b/frontend/sync-client/src/tracing/sync-history.ts index 31f77283..c0d32032 100644 --- a/frontend/sync-client/src/tracing/sync-history.ts +++ b/frontend/sync-client/src/tracing/sync-history.ts @@ -2,7 +2,7 @@ import { MAX_HISTORY_ENTRY_COUNT, TIMEOUT_FOR_MERGING_HISTORY_ENTRIES_IN_SECONDS } from "../consts"; -import type { RelativePath } from "../persistence/database"; +import type { RelativePath } from "../sync-operations/types"; import type { Logger } from "./logger"; import { removeFromArray } from "../utils/remove-from-array"; import { EventListeners } from "../utils/data-structures/event-listeners"; @@ -28,7 +28,7 @@ export interface SyncDeleteDetails { relativePath: RelativePath; } -export interface SyncSkippedDetails { +interface SyncSkippedDetails { type: SyncType.SKIPPED; relativePath: RelativePath; } @@ -40,12 +40,15 @@ export type SyncDetails = | SyncMovedDetails | SyncSkippedDetails; -export interface CommonHistoryEntry { +export interface HistoryEntry { status: SyncStatus; message: string; details: SyncDetails; + timestamp: Date; + // `author` is the server-side user id and only exists for entries that + // round-tripped through the server. Local-only entries (e.g. SKIPPED) + // legitimately have no author. author?: string; - timestamp?: Date; } export enum SyncType { @@ -62,8 +65,6 @@ export enum SyncStatus { SKIPPED = "SKIPPED" } -export type HistoryEntry = CommonHistoryEntry & { timestamp: Date }; - export interface HistoryStats { success: number; error: number; @@ -88,30 +89,25 @@ export class SyncHistory { } /** - * Insert the entry at the beginning of the history list. If the entry - * already in the list, it will get moved to the beginning and updated. - * - * If the entry list is too long, the oldest entry will be removed. - */ - public addHistoryEntry(entry: CommonHistoryEntry): void { - const historyEntry = { - ...entry, - timestamp: entry.timestamp ?? new Date() - }; - - const candidate = this.findSimilarRecentUpdateEntry(historyEntry); + * Insert the entry at the beginning of the history list. If the entry + * already in the list, it will get moved to the beginning and updated. + * + * If the entry list is too long, the oldest entry will be removed. + */ + public addHistoryEntry(entry: HistoryEntry): void { + const candidate = this.findSimilarRecentUpdateEntry(entry); if (candidate !== undefined) { removeFromArray(this._entries, candidate); } // Insert the entry at the beginning - this._entries.unshift(historyEntry); + this._entries.unshift(entry); if (this._entries.length > MAX_HISTORY_ENTRY_COUNT) { this._entries.pop(); } - this.updateSuccessCount(historyEntry); + this.updateSuccessCount(entry); } public reset(): void { diff --git a/frontend/sync-client/tsconfig.json b/frontend/sync-client/tsconfig.json index 92caf072..98870f32 100644 --- a/frontend/sync-client/tsconfig.json +++ b/frontend/sync-client/tsconfig.json @@ -12,7 +12,5 @@ "declaration": true, "declarationDir": "./dist/types" }, - "exclude": [ - "./dist" - ] + "exclude": ["./dist"] } diff --git a/frontend/sync-client/webpack.config.js b/frontend/sync-client/webpack.config.js index b7c3a3fd..413bfeba 100644 --- a/frontend/sync-client/webpack.config.js +++ b/frontend/sync-client/webpack.config.js @@ -49,11 +49,6 @@ module.exports = [ type: "umd" }, globalObject: "this" - }, - resolve: { - fallback: { - ws: false // Exclude `ws` from the browser bundle - } } }), merge(common, { @@ -62,10 +57,6 @@ module.exports = [ path: path.resolve(__dirname, "dist"), filename: "sync-client.node.js", libraryTarget: "commonjs2" - }, - externals: { - bufferutil: "bufferutil", - "utf-8-validate": "utf-8-validate" // required for ws: https://github.com/websockets/ws/issues/2245#issuecomment-2250318733 } }) ]; From 4482e0155f73e3b53f93ccc3377f8402b6142c17 Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Fri, 8 May 2026 21:53:33 +0100 Subject: [PATCH 11/17] Migrate to forgejo & reformat (#189) - Migrate to forgejo - Bump Rust & Node - Reformat project - Small script cleanup Reviewed-on: https://home.schmelczer.dev/git/git/andras/vault-link/pulls/189 Co-authored-by: Andras Schmelczer Co-committed-by: Andras Schmelczer --- .forgejo/workflows/check.yml | 35 + .forgejo/workflows/deploy-docs.yml | 38 + .forgejo/workflows/e2e.yml | 71 + .forgejo/workflows/publish-cli-docker.yml | 51 + .forgejo/workflows/publish-plugin.yml | 71 + .forgejo/workflows/publish-server-docker.yml | 51 + .github/workflows/check.yml | 4 +- .github/workflows/deploy-docs.yml | 13 +- .github/workflows/e2e.yml | 6 +- .github/workflows/publish-plugin.yml | 4 +- .gitignore | 9 +- .vscode/settings.json | 4 +- CLAUDE.md | 195 +- README.md | 8 +- docs/.cspell.json | 7 +- docs/architecture/data-flow.md | 58 +- docs/architecture/index.md | 2 +- docs/config/authentication.md | 6 +- docs/guide/server-setup.md | 2 +- docs/package-lock.json | 5960 +++++++++--------- package-lock.json | 6 + rustfmt.toml | 11 + scripts/bump-version.sh | 3 +- scripts/check.sh | 14 +- scripts/clean-up.sh | 2 +- scripts/e2e.sh | 72 +- scripts/update-api-types.sh | 10 +- scripts/utils/check-node.sh | 6 +- scripts/utils/wait-for-server.sh | 4 +- 29 files changed, 3571 insertions(+), 3152 deletions(-) create mode 100644 .forgejo/workflows/check.yml create mode 100644 .forgejo/workflows/deploy-docs.yml create mode 100644 .forgejo/workflows/e2e.yml create mode 100644 .forgejo/workflows/publish-cli-docker.yml create mode 100644 .forgejo/workflows/publish-plugin.yml create mode 100644 .forgejo/workflows/publish-server-docker.yml create mode 100644 package-lock.json create mode 100644 rustfmt.toml diff --git a/.forgejo/workflows/check.yml b/.forgejo/workflows/check.yml new file mode 100644 index 00000000..40e01dea --- /dev/null +++ b/.forgejo/workflows/check.yml @@ -0,0 +1,35 @@ +name: Check + +on: + push: + branches: ["main"] + pull_request: + branches: ["main"] + workflow_dispatch: + +env: + CARGO_TERM_COLOR: always + RUSTFLAGS: "-Dwarnings" + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Node.js environment + uses: actions/setup-node@v4 + with: + node-version: "25.x" + + - name: Setup Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: "1.92.0" + components: clippy, rustfmt + + - name: Lint & test + run: scripts/check.sh diff --git a/.forgejo/workflows/deploy-docs.yml b/.forgejo/workflows/deploy-docs.yml new file mode 100644 index 00000000..c49d0379 --- /dev/null +++ b/.forgejo/workflows/deploy-docs.yml @@ -0,0 +1,38 @@ +name: Deploy Documentation + +on: + push: + branches: + - main + paths: + - "docs/**" + - ".forgejo/workflows/deploy-docs.yml" + workflow_dispatch: + +concurrency: + group: pages + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Node.js environment + uses: actions/setup-node@v4 + with: + node-version: "25.x" + + - name: Build docs + run: scripts/build-docs.sh + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: docs + path: docs/.vitepress/dist diff --git a/.forgejo/workflows/e2e.yml b/.forgejo/workflows/e2e.yml new file mode 100644 index 00000000..eb8d1e54 --- /dev/null +++ b/.forgejo/workflows/e2e.yml @@ -0,0 +1,71 @@ +name: E2E tests + +on: + push: + branches: ["main"] + pull_request: + branches: ["main"] + schedule: + - cron: "0 * * * *" + workflow_dispatch: + +concurrency: + group: e2e-tests + cancel-in-progress: false + +env: + RUSTFLAGS: "-Dwarnings" + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Node.js environment + uses: actions/setup-node@v4 + with: + node-version: "25.x" + + - name: Setup Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: "1.92.0" + components: clippy, rustfmt + + - name: Setup rust + run: | + which sqlx || cargo install sqlx-cli + cd sync-server + sqlx database create --database-url sqlite://db.sqlite3 + sqlx migrate run --source src/app_state/database/migrations --database-url sqlite://db.sqlite3 + + - name: E2E tests + run: | + cd sync-server + cargo run config-e2e.yml --color never & + SERVER_PID=$! + cd .. + + scripts/e2e.sh 8 + EXIT_CODE=$? + + kill $SERVER_PID 2>/dev/null || true + wait $SERVER_PID 2>/dev/null || true + + exit $EXIT_CODE + + - name: Upload e2e logs + if: always() + uses: actions/upload-artifact@v4 + with: + name: e2e-logs + path: logs/ + retention-days: 30 + + - name: Cleanup + if: always() + run: scripts/clean-up.sh diff --git a/.forgejo/workflows/publish-cli-docker.yml b/.forgejo/workflows/publish-cli-docker.yml new file mode 100644 index 00000000..265283ab --- /dev/null +++ b/.forgejo/workflows/publish-cli-docker.yml @@ -0,0 +1,51 @@ +name: Publish CLI + +on: + push: + branches: ["main"] + tags: ["*"] + pull_request: + branches: ["main"] + +jobs: + publish-docker: + runs-on: ubuntu-docker + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Extract registry hostname + id: registry + run: echo "host=$(echo '${{ github.server_url }}' | sed 's|https\?://||')" >> "$GITHUB_OUTPUT" + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log into container registry + uses: docker/login-action@v3 + with: + registry: ${{ steps.registry.outputs.host }} + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract Docker metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ steps.registry.outputs.host }}/${{ github.repository }}-cli + + - name: Build and push Docker image + id: build-and-push + uses: docker/build-push-action@v5 + with: + context: frontend + file: frontend/local-client-cli/Dockerfile + platforms: linux/amd64 + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=registry,ref=${{ steps.registry.outputs.host }}/${{ github.repository }}-cli:buildcache + cache-to: type=registry,ref=${{ steps.registry.outputs.host }}/${{ github.repository }}-cli:buildcache,mode=max diff --git a/.forgejo/workflows/publish-plugin.yml b/.forgejo/workflows/publish-plugin.yml new file mode 100644 index 00000000..25a652aa --- /dev/null +++ b/.forgejo/workflows/publish-plugin.yml @@ -0,0 +1,71 @@ +name: Publish Obsidian plugin + +on: + push: + tags: ["*"] + +env: + CARGO_TERM_COLOR: always + +jobs: + publish-plugin: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Node.js environment + uses: actions/setup-node@v4 + with: + node-version: "25.x" + + - name: Build plugin + run: | + cd frontend + npm ci + npm run build + + - name: Setup Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: "1.92.0" + components: clippy, rustfmt + + - name: Install cross-compilation tools + run: | + apt update + apt install -y gcc-aarch64-linux-gnu musl-tools gcc-mingw-w64-x86-64 jq + + - name: Build Linux and Windows binaries + run: ./scripts/build-sync-server-binaries.sh + + - name: Create release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SERVER_URL: ${{ github.server_url }} + REPO: ${{ github.repository }} + run: | + tag="${GITHUB_REF#refs/tags/}" + + mkdir -p release + cp frontend/obsidian-plugin/dist/* release/ + cp sync-server/artifacts/sync-server-* release/ + + # Create draft release via Forgejo API + RELEASE_ID=$(curl -s -X POST \ + "${SERVER_URL}/api/v1/repos/${REPO}/releases" \ + -H "Authorization: token ${GITHUB_TOKEN}" \ + -H "Content-Type: application/json" \ + -d "{\"tag_name\": \"${tag}\", \"name\": \"${tag}\", \"draft\": true}" \ + | jq -r '.id') + + # Upload release assets + for file in release/*; do + filename=$(basename "$file") + curl -s -X POST \ + "${SERVER_URL}/api/v1/repos/${REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \ + -H "Authorization: token ${GITHUB_TOKEN}" \ + -F "attachment=@${file}" + done diff --git a/.forgejo/workflows/publish-server-docker.yml b/.forgejo/workflows/publish-server-docker.yml new file mode 100644 index 00000000..23852e56 --- /dev/null +++ b/.forgejo/workflows/publish-server-docker.yml @@ -0,0 +1,51 @@ +name: Publish server Docker image + +on: + push: + branches: ["main"] + tags: ["*"] + pull_request: + branches: ["main"] + +jobs: + publish-docker: + runs-on: ubuntu-docker + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Extract registry hostname + id: registry + run: echo "host=$(echo '${{ github.server_url }}' | sed 's|https\?://||')" >> "$GITHUB_OUTPUT" + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log into container registry + if: github.ref_type == 'tag' + uses: docker/login-action@v3 + with: + registry: ${{ steps.registry.outputs.host }} + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract Docker metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ steps.registry.outputs.host }}/${{ github.repository }} + + - name: Build and push Docker image + id: build-and-push + uses: docker/build-push-action@v5 + with: + context: sync-server + platforms: linux/amd64,linux/arm64 + push: ${{ github.ref_type == 'tag' }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=registry,ref=${{ steps.registry.outputs.host }}/${{ github.repository }}:buildcache + cache-to: type=registry,ref=${{ steps.registry.outputs.host }}/${{ github.repository }}:buildcache,mode=max diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 9aa71fb4..fc1b1c99 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -23,13 +23,13 @@ jobs: - name: Setup Node.js environment uses: actions/setup-node@v4.2.0 with: - node-version: "22.x" + node-version: "25.x" check-latest: true - name: Setup Rust toolchain uses: dtolnay/rust-toolchain@stable with: - toolchain: "1.89.0" + toolchain: "1.92.0" components: clippy, rustfmt - name: Lint & test diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index b6d369cc..bb25e463 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -5,8 +5,8 @@ on: branches: - main paths: - - 'docs/**' - - '.github/workflows/deploy-docs.yml' + - "docs/**" + - ".github/workflows/deploy-docs.yml" workflow_dispatch: permissions: @@ -28,12 +28,11 @@ jobs: with: fetch-depth: 0 - - name: Setup Node - uses: actions/setup-node@v4 + - name: Setup Node.js environment + uses: actions/setup-node@v4.2.0 with: - node-version: 22 - cache: npm - cache-dependency-path: docs/package-lock.json + node-version: "25.x" + check-latest: true - name: Setup Pages uses: actions/configure-pages@v4 diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 7d0a2a0f..98dbfc1f 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -6,7 +6,7 @@ on: pull_request: branches: ["main"] schedule: - - cron: '0 * * * *' + - cron: "0 * * * *" workflow_dispatch: concurrency: @@ -28,13 +28,13 @@ jobs: - name: Setup Node.js environment uses: actions/setup-node@v4.2.0 with: - node-version: "22.x" + node-version: "25.x" check-latest: true - name: Setup Rust toolchain uses: dtolnay/rust-toolchain@stable with: - toolchain: "1.89.0" + toolchain: "1.92.0" components: clippy, rustfmt - name: Setup rust diff --git a/.github/workflows/publish-plugin.yml b/.github/workflows/publish-plugin.yml index 92dd199b..452bc601 100644 --- a/.github/workflows/publish-plugin.yml +++ b/.github/workflows/publish-plugin.yml @@ -19,7 +19,7 @@ jobs: - name: Setup Node.js environment uses: actions/setup-node@v4.2.0 with: - node-version: "22.x" + node-version: "25.x" check-latest: true - name: Build plugin @@ -31,7 +31,7 @@ jobs: - name: Setup Rust toolchain uses: dtolnay/rust-toolchain@stable with: - toolchain: "1.89.0" + toolchain: "1.92.0" components: clippy, rustfmt - name: Install cross-compilation tools diff --git a/.gitignore b/.gitignore index a1c1ac4f..967b2b65 100644 --- a/.gitignore +++ b/.gitignore @@ -7,15 +7,18 @@ node_modules # Frontend build folders frontend/*/dist -sync-server/db.sqlite3* -sync-server/databases - # Rust build folders sync-server/target sync-server/artifacts sync-server/bindings/*.ts +# build folders +sync-server/db.sqlite3* +**/databases + *.log *.sqlx target + +.task diff --git a/.vscode/settings.json b/.vscode/settings.json index 88d395f5..98187650 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -5,6 +5,6 @@ "**/dist": true, "**/node_modules": true, "**/.sqlx": true, - "**/target": true, - }, + "**/target": true + } } diff --git a/CLAUDE.md b/CLAUDE.md index c77b091b..39161e39 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,109 +2,154 @@ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. -## Project Overview +## Project shape -VaultLink is a self-hosted Obsidian plugin for real-time collaborative file syncing. The project consists of a Rust-based sync server and a TypeScript frontend with three main components: an Obsidian plugin, a sync client library, and a test client. +VaultLink is a self-hosted Obsidian file-sync system. Two halves of one repo: -## Architecture +- `sync-server/` — Rust (axum + sqlx/SQLite). Source of truth for vault state, broadcasts changes via WebSocket. +- `frontend/` — npm workspaces. The sync engine (`sync-client`) is consumed by an Obsidian plugin, a standalone CLI, a fuzz E2E harness, a scripted determinism harness, and a history UI. -### Core Components +The HTTP/WS API types are generated from Rust (`ts-rs`) and mirrored into the TS workspaces. **Never hand-edit files in `frontend/sync-client/src/services/types/` or `frontend/history-ui/src/lib/types/`** — run `scripts/update-api-types.sh` after changing anything Serde-derived in the server. -- **sync-server/**: Rust-based WebSocket server with SQLite database for document versioning and real-time synchronization -- **frontend/sync-client/**: TypeScript library providing core sync functionality, WebSocket management, and file operations -- **frontend/obsidian-plugin/**: Obsidian plugin that integrates the sync client with Obsidian's API -- **frontend/test-client/**: CLI testing tool for the sync functionality +### Frontend workspaces -### Key Technologies +- `sync-client` — the sync engine; published to consumers via `dist/`. All other TS workspaces depend on it via `file:../sync-client`. +- `obsidian-plugin` — Obsidian plugin built from `sync-client`. +- `local-client-cli` — same engine wrapped as a standalone CLI. +- `history-ui` — vault-history web UI. +- `test-client` — fuzz E2E harness (random ops across N processes). +- `deterministic-tests` — scripted multi-client tests with an in-memory FS, run against a real server. -- **Backend**: Rust with Axum framework, SQLite with SQLx, WebSockets for real-time sync -- **Frontend**: TypeScript, Webpack for bundling, Jest for testing -- **Sync Algorithm**: Uses reconcile-text library for operational transformation +## Common commands -## Development Commands +Pre-push hygiene (formats, lints, runs tests, requires clean git state): -### Server Development -```bash -cd sync-server -cargo run config-e2e.yml # Start development server -cargo test --verbose # Run Rust tests -cargo clippy --all-targets --all-features # Lint Rust code -cargo clippy --all-targets --all-features --fix --allow-dirty --allow-staged # Auto-fix clippy warnings -cargo fmt --all -- --check # Check Rust formatting -cargo fmt --all # Auto-format Rust code -cargo machete --with-metadata # Detect unused dependencies +```sh +scripts/check.sh --fix ``` -### Frontend Development -```bash +Run the fuzz E2E (N parallel processes): + +```sh +scripts/e2e.sh 12 +# Logs land in logs/log_.log. Clean with scripts/clean-up.sh +``` + +Run deterministic tests (require a release-built server in `sync-server/target/release/sync_server` — they spawn it themselves): + +```sh +cd sync-server && cargo build --release && cd .. cd frontend -npm run dev # Start development mode (watches sync-client and obsidian-plugin) -npm run build # Build all workspaces -npm run test # Run all tests -npm run lint # Lint and format TypeScript code +npm run build -w sync-client -w deterministic-tests +node deterministic-tests/dist/cli.js # all +node deterministic-tests/dist/cli.js --filter=rename # subset +node deterministic-tests/dist/cli.js --filter=… -j 4 # cap parallelism ``` -### Database Setup (Development) -```bash +Run a single sync-client unit test by file: + +```sh +cd frontend/sync-client && npx tsx --test 'src/**/sync-event-queue.test.ts' +``` + +Server: dev runs from `sync-server/` against `config-e2e.yml`: + +```sh +cd sync-server +cargo run config-e2e.yml # dev +cargo build --release # used by both e2e harnesses +cargo test # unit + ts-rs binding export tests +``` + +Frontend dev (sync-client + obsidian-plugin watch in parallel): + +```sh +cd frontend && npm install && npm run dev +``` + +Regenerate TS bindings from Rust types (touches `frontend/{sync-client,history-ui}/src/.../types/`): + +```sh +scripts/update-api-types.sh +``` + +## SQLite / sqlx + +The server uses `sqlx::query!` macros that need a prepared `.sqlx` cache to compile offline. Touching any SQL means regenerating it: + +```sh cd sync-server sqlx database create --database-url sqlite://db.sqlite3 sqlx migrate run --source src/app_state/database/migrations --database-url sqlite://db.sqlite3 cargo sqlx prepare --workspace ``` -### Initial Setup -```bash -# Install required cargo tools -cargo install sqlx-cli cargo-machete cargo-edit +New migrations: `sqlx migrate add --source src/app_state/database/migrations `. + +## Sync engine architecture + +Read `frontend/sync-client/src/sync-operations/` to follow the sync engine; the rest of `sync-client` is plumbing (filesystem ops, persistence, services, telemetry). + +The engine is **two independent loops with separate invariants**: + +- **Wire loop** (`syncer.ts`) — drains the single-consumer FIFO queue. HTTP and WS handlers update record fields (`remoteRelativePath`, `parentVersionId`, `remoteHash`) and write content to the file at `record.localPath`. They never move files for path placement. +- **Path reconciler** (`reconciler.ts`) — runs after every drained event. Best-effort pass that moves files to make `localPath === remoteRelativePath`. The move graph is topologically sorted; cycles are resolved by reading every file in the cycle into memory and writing each back to its new slot (no tmp files). Records with pending local events are skipped on each pass — the reconciler operates only on settled records. Failures (slot occupied by an untracked file, etc.) are silent skips; the next pass retries. + +**`SyncEventQueue`** (`sync-event-queue.ts`) holds: + +- `byDocId: Map` — primary record store. +- `byLocalPath: Map` — derived index for path lookups, maintained at every mutation point. +- `events: SyncEvent[]` — pending wire ops in FIFO drain order. + +```ts +DocumentRecord = { + documentId, + parentVersionId, + remoteHash?, + remoteRelativePath, + localPath: RelativePath | undefined +} ``` -### Scripts -- `scripts/check.sh`: Full CI check (builds, lints, tests both server and frontend) -- `scripts/check.sh --fix`: Same as above but auto-fixes linting and formatting issues -- `scripts/e2e.sh`: End-to-end testing -- `scripts/clean-up.sh`: Clean logs and database files -- `scripts/bump-version.sh patch`: Publish new version -- `scripts/update-api-types.sh`: Update TypeScript bindings from Rust types +`localPath === undefined` means the doc has no local file yet — typically a remote create whose target slot was occupied at receive time; the reconciler will fetch and place when the slot frees (the bytes wait in `pendingPlacementContent`). -## Code Structure +Local FS events from the watcher update `localPath` synchronously at enqueue time via `setLocalPath` / `upsertRecord`. The wire loop never updates it for path placement; only the reconciler does. A user rename onto a tracked slot enqueues a `LocalDelete` for the displaced doc (the OS rename clobbered its content) and clears that doc's `localPath`. -### Workspace Configuration -The frontend uses npm workspaces with four packages: -- `sync-client`: Core synchronization logic -- `obsidian-plugin`: Obsidian-specific integration -- `test-client`: Testing utilities -- `local-client-cli`: Standalone CLI for VaultLink sync client +**Pending creates** use a `Promise` chain to serialize dependent ops (`LocalUpdate`, `LocalDelete`) behind the still-in-flight `LocalCreate`. `resolveCreate` resolves the promise once the server returns a docId, and `replacePendingDocumentId` swaps the resolved id across already-queued events. `findLatestCreateForPath` is the lookup the watcher uses to attach dependents; `updatePendingCreatePath` rewrites a pending create's `event.path` in place when the user renames the file before its create has acked. -### Type Generation -Rust structs generate TypeScript types via ts-rs crate, stored in `sync-server/bindings/` and used by frontend packages. +**Watermark.** `lastSeenUpdateId` uses a `MinCovered` (a contiguous-prefix tracker over a stream of integers): we only advance the published min when the next consecutive id has been processed, so out-of-order RemoteChange ids don't fool the WebSocket handshake into requesting a too-recent catch-up. -### Key Files -- `sync-server/src/`: Rust server implementation with WebSocket handlers -- `frontend/sync-client/src/sync-client.ts`: Main sync client entry point -- `frontend/obsidian-plugin/src/vault-link-plugin.ts`: Main Obsidian plugin class -- `frontend/sync-client/src/services/sync-service.ts`: Core synchronization logic +**Server catch-up.** The server's WS handshake replays events newer than the client's `last_seen_vault_update_id` from the `latest_document_versions` view (one row per doc, the latest). On those replayed rows `is_new_file` means _new to this client_ (`creation_vault_update_id > last_seen_vault_update_id`), not "this row is the doc's first version" — necessary because the catch-up only carries the latest version; if a doc was created and updated past the watermark, the client never sees its create otherwise. -## Testing +## Edge-case patterns the sync engine has to survive -### Running Tests -- Server: `cargo test --verbose` -- Frontend: `npm run test` (runs Jest across all workspaces) -- E2E: `scripts/e2e.sh` +The two-loop split defuses most of the old race catalogue (slot-collision stashes, conflict-uuid divergence, `MoveOnConflict.NEW`/`EXISTING` policy choices) by separating wire transport from path placement. What's left: -### Test Structure -- Rust: Unit tests alongside source files -- TypeScript: `.test.ts` files using Jest -- E2E: Uses test-client to simulate multiple concurrent users +**Pending-create docId is a `Promise`, not a string, until the create acks.** Any `LocalUpdate` / `LocalDelete` queued behind a still-in-flight `LocalCreate` carries the create's `resolvers.promise` as its `documentId`. `replacePendingDocumentId` swaps the resolved id across queued events when the create resolves; `===` comparisons against the resolved string elsewhere will silently fail until that swap runs. Anything that walks `events[]` looking for a docId match must either run after the swap or be tolerant of `Promise`-typed ids. -## Code Style +**`processCreate` reads `event.path` live, not `event.originalPath`.** The watcher rewrites `event.path` in place via `updatePendingCreatePath` when the user renames a pending-create file. `originalPath` was removed from `LocalCreate` events specifically because reading it would send the stale pre-rename path to the server. -### Rust -- Uses extensive Clippy lints (see Cargo.toml) -- Follows pedantic linting rules -- Forbids unsafe code -- Uses cargo fmt with default settings +**`record.localPath` mutates in place across awaits.** When the watcher renames a doc while a drain handler is awaiting an HTTP roundtrip, the queue mutates the in-flight event's record so subsequent reads see the new path. Snapshotting `record.localPath` into a local at function entry and using it after an `await` reads/writes a now-vacated slot. Read `record.localPath` live; only snapshot for the deliberate "did it change while I was awaiting" comparison. -### TypeScript -- Prettier configuration: 4-space tabs, trailing commas removed, LF line endings -- ESLint with unused imports plugin -- Consistent across all three frontend packages +**Reconciler-defer is the wire-loop's contract with the reconciler.** The reconciler skips records where `hasPendingLocalEventsForDocumentId` returns true. Wire-loop handlers can therefore freely write `remoteRelativePath` to whatever the server returned — even if it disagrees with `localPath` — knowing the reconciler won't move the file out from under a queued user rename. + +**Watermark advancement is load-bearing both ways.** Branches that _skip_ a remote event without advancing `lastSeenUpdateId` create permanent gaps that re-deliver forever. Branches that _advance_ without applying the content lose data: the server has no further event to re-deliver, the catch-up only carries the latest version, and any state in between is gone. Don't advance unless the event was actually applied (or deliberately discarded after weighing both halves). + +**`isNewFile` semantics differ between catch-up and real-time.** On WS handshake replay it means _new to this client_ (`creation_vault_update_id > last_seen_vault_update_id`); on real-time broadcasts it means _this version is the create_ (`creation_vault_update_id == vault_update_id`). A handler that decides based on one interpretation will be wrong on the other channel; reasoning about fetch-and-treat-as-new vs. ignore needs to know which channel delivered the event. + +**Pause / disable-sync mid-flight** is the one race the new model doesn't structurally fix. An HTTP that committed server-side but whose response was discarded leaves the server holding a doc the client has no record of. Resume → offline scan → server-side dedupe handles it (the server merges the duplicate create into the existing doc), but if the merge produces a deconflict, the client picks up an extra file. Out of scope for the two-loop split. + +**Cycle reconciliation uses in-memory content swap.** When the move graph contains a cycle, the reconciler reads every file in the cycle into memory and writes each back to its new slot, with no tmp files. A write-ahead marker at `.vaultlink/swap-.json` lists each leg; on startup the reconciler reads the marker, hashes each `from` to determine which legs ran, and replays the rest. The `.vaultlink/**` glob is hard-coded as an internal ignore pattern so swap markers don't get sync'd. + +## Two complementary E2E harnesses + +- **`test-client` (fuzz):** random ops across N parallel processes for many minutes. Used by `scripts/e2e.sh`. Catches bugs nobody thought to write a test for, but reproductions are noisy. +- **`deterministic-tests`:** scripted scenarios with an in-memory FS pinned to a real server. Used to _capture_ a fuzz-discovered bug as a minimal repro before fixing it. See `frontend/deterministic-tests/README.md` for the step grammar (`pause-server`, `pause-websocket`, `barrier`, `assert-consistent`, etc.). + +When a fuzz failure surfaces, the workflow is: root-cause from logs → write a deterministic test that fails on the bug → fix → confirm both the deterministic test and `e2e.sh` pass. + +## Style + +- TS: 4-space indent, no tabs, LF, prettier (`trailingComma: "none"`). YAML/MD use 2-space indent. +- Rust: `rustfmt.toml` enforces 4-space spaces, LF. +- Lint: ESLint for TS, Clippy for Rust, `cargo machete` for unused deps. All wired into `scripts/check.sh`. diff --git a/README.md b/README.md index f5da9b61..74c6ee97 100644 --- a/README.md +++ b/README.md @@ -8,12 +8,12 @@ ## Develop -### Install [nvm](https://github.com/nvm-sh/nvm) +### Set up Node.JS 25 with [nvm](https://github.com/nvm-sh/nvm) - `curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash` -- `nvm install 22` -- `nvm use 22` -- Optionally set the system-wide default: `nvm alias default 22` +- `nvm install 25` +- `nvm use 25` +- Optionally, set the system-wide default: `nvm alias default 25` ### Set up Rust diff --git a/docs/.cspell.json b/docs/.cspell.json index 4967ec16..1177e1e1 100644 --- a/docs/.cspell.json +++ b/docs/.cspell.json @@ -2,12 +2,7 @@ "version": "0.2", "language": "en-GB", "dictionaries": ["en-gb"], - "ignorePaths": [ - "node_modules", - ".vitepress/dist", - ".vitepress/cache", - "package-lock.json" - ], + "ignorePaths": ["node_modules", ".vitepress/dist", ".vitepress/cache", "package-lock.json"], "words": [ "VaultLink", "Obsidian", diff --git a/docs/architecture/data-flow.md b/docs/architecture/data-flow.md index 832c5624..167be524 100644 --- a/docs/architecture/data-flow.md +++ b/docs/architecture/data-flow.md @@ -361,11 +361,11 @@ VALUES (?, ?, ?); ```json { - "type": "upload_file", - "path": "notes/example.md", - "content": "File content here...", - "base_version": 10, - "timestamp": "2024-01-01T12:00:00Z" + "type": "upload_file", + "path": "notes/example.md", + "content": "File content here...", + "base_version": 10, + "timestamp": "2024-01-01T12:00:00Z" } ``` @@ -373,8 +373,8 @@ VALUES (?, ?, ?); ```json { - "type": "download_file", - "path": "notes/example.md" + "type": "download_file", + "path": "notes/example.md" } ``` @@ -382,8 +382,8 @@ VALUES (?, ?, ?); ```json { - "type": "delete_file", - "path": "notes/old.md" + "type": "delete_file", + "path": "notes/old.md" } ``` @@ -391,8 +391,8 @@ VALUES (?, ?, ?); ```json { - "type": "list_files", - "since_version": 0 + "type": "list_files", + "since_version": 0 } ``` @@ -402,11 +402,11 @@ VALUES (?, ?, ?); ```json { - "type": "file_updated", - "path": "notes/example.md", - "version": 11, - "size": 1024, - "hash": "abc123..." + "type": "file_updated", + "path": "notes/example.md", + "version": 11, + "size": 1024, + "hash": "abc123..." } ``` @@ -414,10 +414,10 @@ VALUES (?, ?, ?); ```json { - "type": "file_content", - "path": "notes/example.md", - "content": "Updated content...", - "version": 11 + "type": "file_content", + "path": "notes/example.md", + "content": "Updated content...", + "version": 11 } ``` @@ -425,9 +425,9 @@ VALUES (?, ?, ?); ```json { - "type": "file_deleted", - "path": "notes/old.md", - "version": 12 + "type": "file_deleted", + "path": "notes/old.md", + "version": 12 } ``` @@ -435,9 +435,9 @@ VALUES (?, ?, ?); ```json { - "type": "sync_complete", - "total_files": 150, - "current_version": 200 + "type": "sync_complete", + "total_files": 150, + "current_version": 200 } ``` @@ -445,9 +445,9 @@ VALUES (?, ?, ?); ```json { - "type": "error", - "message": "File too large", - "code": "FILE_TOO_LARGE" + "type": "error", + "message": "File too large", + "code": "FILE_TOO_LARGE" } ``` diff --git a/docs/architecture/index.md b/docs/architecture/index.md index f5eca5e3..bebb6c49 100644 --- a/docs/architecture/index.md +++ b/docs/architecture/index.md @@ -53,7 +53,7 @@ Central authority for synchronisation. Rust + Axum framework. **Technology**: -- **Language**: Rust 1.89+ +- **Language**: Rust 1.92+ - **Framework**: Axum (async web framework) - **Database**: SQLite with SQLx - **Protocol**: WebSockets for real-time communication diff --git a/docs/config/authentication.md b/docs/config/authentication.md index 11425b5b..74977be7 100644 --- a/docs/config/authentication.md +++ b/docs/config/authentication.md @@ -243,9 +243,9 @@ users: 2. Client sends authentication message: ```json { - "type": "auth", - "token": "user-token", - "vault": "vault-name" + "type": "auth", + "token": "user-token", + "vault": "vault-name" } ``` 3. Server validates: diff --git a/docs/guide/server-setup.md b/docs/guide/server-setup.md index 7754da54..1848db26 100644 --- a/docs/guide/server-setup.md +++ b/docs/guide/server-setup.md @@ -75,7 +75,7 @@ chmod +x sync_server-linux-x86_64 ### Build from Source -Requirements: Rust 1.89.0+, SQLite development headers, SQLx CLI +Requirements: Rust 1.92.0+, SQLite development headers, SQLx CLI ```bash # Clone the repository diff --git a/docs/package-lock.json b/docs/package-lock.json index dcd4f3b0..d078bbe6 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -1,2989 +1,2989 @@ { - "name": "docs", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { "name": "docs", "version": "1.0.0", - "license": "ISC", - "devDependencies": { - "@cspell/dict-en-gb": "^5.0.19", - "cspell": "^9.3.2", - "prettier": "^3.6.2", - "vitepress": "^1.6.4", - "vue": "^3.5.24" - } - }, - "node_modules/@algolia/abtesting": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@algolia/abtesting/-/abtesting-1.10.0.tgz", - "integrity": "sha512-mQT3jwuTgX8QMoqbIR7mPlWkqQqBPQaPabQzm37xg2txMlaMogK/4hCiiESGdg39MlHZOVHeV+0VJuE7f5UK8A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/autocomplete-core": { - "version": "1.17.7", - "resolved": "https://registry.npmjs.org/@algolia/autocomplete-core/-/autocomplete-core-1.17.7.tgz", - "integrity": "sha512-BjiPOW6ks90UKl7TwMv7oNQMnzU+t/wk9mgIDi6b1tXpUek7MW0lbNOUHpvam9pe3lVCf4xPFT+lK7s+e+fs7Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/autocomplete-plugin-algolia-insights": "1.17.7", - "@algolia/autocomplete-shared": "1.17.7" - } - }, - "node_modules/@algolia/autocomplete-plugin-algolia-insights": { - "version": "1.17.7", - "resolved": "https://registry.npmjs.org/@algolia/autocomplete-plugin-algolia-insights/-/autocomplete-plugin-algolia-insights-1.17.7.tgz", - "integrity": "sha512-Jca5Ude6yUOuyzjnz57og7Et3aXjbwCSDf/8onLHSQgw1qW3ALl9mrMWaXb5FmPVkV3EtkD2F/+NkT6VHyPu9A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/autocomplete-shared": "1.17.7" - }, - "peerDependencies": { - "search-insights": ">= 1 < 3" - } - }, - "node_modules/@algolia/autocomplete-preset-algolia": { - "version": "1.17.7", - "resolved": "https://registry.npmjs.org/@algolia/autocomplete-preset-algolia/-/autocomplete-preset-algolia-1.17.7.tgz", - "integrity": "sha512-ggOQ950+nwbWROq2MOCIL71RE0DdQZsceqrg32UqnhDz8FlO9rL8ONHNsI2R1MH0tkgVIDKI/D0sMiUchsFdWA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/autocomplete-shared": "1.17.7" - }, - "peerDependencies": { - "@algolia/client-search": ">= 4.9.1 < 6", - "algoliasearch": ">= 4.9.1 < 6" - } - }, - "node_modules/@algolia/autocomplete-shared": { - "version": "1.17.7", - "resolved": "https://registry.npmjs.org/@algolia/autocomplete-shared/-/autocomplete-shared-1.17.7.tgz", - "integrity": "sha512-o/1Vurr42U/qskRSuhBH+VKxMvkkUVTLU6WZQr+L5lGZZLYWyhdzWjW0iGXY7EkwRTjBqvN2EsR81yCTGV/kmg==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "@algolia/client-search": ">= 4.9.1 < 6", - "algoliasearch": ">= 4.9.1 < 6" - } - }, - "node_modules/@algolia/client-abtesting": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/client-abtesting/-/client-abtesting-5.44.0.tgz", - "integrity": "sha512-KY5CcrWhRTUo/lV7KcyjrZkPOOF9bjgWpMj9z98VA+sXzVpZtkuskBLCKsWYFp2sbwchZFTd3wJM48H0IGgF7g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/client-analytics": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-5.44.0.tgz", - "integrity": "sha512-LKOCE8S4ewI9bN3ot9RZoYASPi8b78E918/DVPW3HHjCMUe6i+NjbNG6KotU4RpP6AhRWZjjswbOkWelUO+OoA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/client-common": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/client-common/-/client-common-5.44.0.tgz", - "integrity": "sha512-1yyJm4OYC2cztbS28XYVWwLXdwpLsMG4LoZLOltVglQ2+hc/i9q9fUDZyjRa2Bqt4DmkIfezagfMrokhyH4uxQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/client-insights": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/client-insights/-/client-insights-5.44.0.tgz", - "integrity": "sha512-wVQWK6jYYsbEOjIMI+e5voLGPUIbXrvDj392IckXaCPvQ6vCMTXakQqOYCd+znQdL76S+3wHDo77HZWiAYKrtA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/client-personalization": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-5.44.0.tgz", - "integrity": "sha512-lkgRjOjOkqmIkebHjHpU9rLJcJNUDMm+eVSW/KJQYLjGqykEZxal+nYJJTBbLceEU2roByP/+27ZmgIwCdf0iA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/client-query-suggestions": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/client-query-suggestions/-/client-query-suggestions-5.44.0.tgz", - "integrity": "sha512-sYfhgwKu6NDVmZHL1WEKVLsOx/jUXCY4BHKLUOcYa8k4COCs6USGgz6IjFkUf+niwq8NCECMmTC4o/fVQOalsA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/client-search": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/client-search/-/client-search-5.44.0.tgz", - "integrity": "sha512-/FRKUM1G4xn3vV8+9xH1WJ9XknU8rkBGlefruq9jDhYUAvYozKimhrmC2pRqw/RyHhPivmgZCRuC8jHP8piz4Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/ingestion": { - "version": "1.44.0", - "resolved": "https://registry.npmjs.org/@algolia/ingestion/-/ingestion-1.44.0.tgz", - "integrity": "sha512-5+S5ynwMmpTpCLXGjTDpeIa81J+R4BLH0lAojOhmeGSeGEHQTqacl/4sbPyDTcidvnWhaqtyf8m42ue6lvISAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/monitoring": { - "version": "1.44.0", - "resolved": "https://registry.npmjs.org/@algolia/monitoring/-/monitoring-1.44.0.tgz", - "integrity": "sha512-xhaTN8pXJjR6zkrecg4Cc9YZaQK2LKm2R+LkbAq+AYGBCWJxtSGlNwftozZzkUyq4AXWoyoc0x2SyBtq5LRtqQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/recommend": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/recommend/-/recommend-5.44.0.tgz", - "integrity": "sha512-GNcite/uOIS7wgRU1MT7SdNIupGSW+vbK9igIzMePvD2Dl8dy0O3urKPKIbTuZQqiVH1Cb84y5cgLvwNrdCj/Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/requester-browser-xhr": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-5.44.0.tgz", - "integrity": "sha512-YZHBk72Cd7pcuNHzbhNzF/FbbYszlc7JhZlDyQAchnX5S7tcemSS96F39Sy8t4O4WQLpFvUf1MTNedlitWdOsQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/requester-fetch": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/requester-fetch/-/requester-fetch-5.44.0.tgz", - "integrity": "sha512-B9WHl+wQ7uf46t9cq+vVM/ypVbOeuldVDq9OtKsX2ApL2g/htx6ImB9ugDOOJmB5+fE31/XPTuCcYz/j03+idA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@algolia/requester-node-http": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-5.44.0.tgz", - "integrity": "sha512-MULm0qeAIk4cdzZ/ehJnl1o7uB5NMokg83/3MKhPq0Pk7+I0uELGNbzIfAkvkKKEYcHALemKdArtySF9eKzh/A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/client-common": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/@babel/helper-string-parser": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", - "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-identifier": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", - "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/parser": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.28.5.tgz", - "integrity": "sha512-KKBU1VGYR7ORr3At5HAtUQ+TV3SzRCXmA/8OdDZiLDBIZxVyzXuztPjfLd3BV1PRAQGCMWWSHYhL0F8d5uHBDQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.28.5" - }, - "bin": { - "parser": "bin/babel-parser.js" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/types": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.5.tgz", - "integrity": "sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-string-parser": "^7.27.1", - "@babel/helper-validator-identifier": "^7.28.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@cspell/cspell-bundled-dicts": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/cspell-bundled-dicts/-/cspell-bundled-dicts-9.3.2.tgz", - "integrity": "sha512-OmKzq/0FATHU671GKMzBrTyLdm25Wnziva7h4ylumVn1wnwWsXGef5bgXD7iuApqfqH9SzxsU0NtTB8m8vwEHQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/dict-ada": "^4.1.1", - "@cspell/dict-al": "^1.1.1", - "@cspell/dict-aws": "^4.0.16", - "@cspell/dict-bash": "^4.2.2", - "@cspell/dict-companies": "^3.2.7", - "@cspell/dict-cpp": "^6.0.14", - "@cspell/dict-cryptocurrencies": "^5.0.5", - "@cspell/dict-csharp": "^4.0.7", - "@cspell/dict-css": "^4.0.18", - "@cspell/dict-dart": "^2.3.1", - "@cspell/dict-data-science": "^2.0.11", - "@cspell/dict-django": "^4.1.5", - "@cspell/dict-docker": "^1.1.16", - "@cspell/dict-dotnet": "^5.0.10", - "@cspell/dict-elixir": "^4.0.8", - "@cspell/dict-en_us": "^4.4.24", - "@cspell/dict-en-common-misspellings": "^2.1.8", - "@cspell/dict-en-gb-mit": "^3.1.14", - "@cspell/dict-filetypes": "^3.0.14", - "@cspell/dict-flutter": "^1.1.1", - "@cspell/dict-fonts": "^4.0.5", - "@cspell/dict-fsharp": "^1.1.1", - "@cspell/dict-fullstack": "^3.2.7", - "@cspell/dict-gaming-terms": "^1.1.2", - "@cspell/dict-git": "^3.0.7", - "@cspell/dict-golang": "^6.0.24", - "@cspell/dict-google": "^1.0.9", - "@cspell/dict-haskell": "^4.0.6", - "@cspell/dict-html": "^4.0.12", - "@cspell/dict-html-symbol-entities": "^4.0.4", - "@cspell/dict-java": "^5.0.12", - "@cspell/dict-julia": "^1.1.1", - "@cspell/dict-k8s": "^1.0.12", - "@cspell/dict-kotlin": "^1.1.1", - "@cspell/dict-latex": "^4.0.4", - "@cspell/dict-lorem-ipsum": "^4.0.5", - "@cspell/dict-lua": "^4.0.8", - "@cspell/dict-makefile": "^1.0.5", - "@cspell/dict-markdown": "^2.0.12", - "@cspell/dict-monkeyc": "^1.0.11", - "@cspell/dict-node": "^5.0.8", - "@cspell/dict-npm": "^5.2.22", - "@cspell/dict-php": "^4.1.0", - "@cspell/dict-powershell": "^5.0.15", - "@cspell/dict-public-licenses": "^2.0.15", - "@cspell/dict-python": "^4.2.21", - "@cspell/dict-r": "^2.1.1", - "@cspell/dict-ruby": "^5.0.9", - "@cspell/dict-rust": "^4.0.12", - "@cspell/dict-scala": "^5.0.8", - "@cspell/dict-shell": "^1.1.2", - "@cspell/dict-software-terms": "^5.1.13", - "@cspell/dict-sql": "^2.2.1", - "@cspell/dict-svelte": "^1.0.7", - "@cspell/dict-swift": "^2.0.6", - "@cspell/dict-terraform": "^1.1.3", - "@cspell/dict-typescript": "^3.2.3", - "@cspell/dict-vue": "^3.0.5", - "@cspell/dict-zig": "^1.0.0" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/cspell-json-reporter": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/cspell-json-reporter/-/cspell-json-reporter-9.3.2.tgz", - "integrity": "sha512-YRgpeHN9uY8kUlIw9q+8zJ0tRTAJMbfBTGzCq9Puah09NeMWlRMFPUkXVrkdic6NA7etboZ+zEdoZwRO9EmhiA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/cspell-types": "9.3.2" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/cspell-pipe": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/cspell-pipe/-/cspell-pipe-9.3.2.tgz", - "integrity": "sha512-REF7ibG79WLEynIMUss/IRDCdYEb1nlE1rj/gt2CbPFzLa6t5MRwW2lajEvXS6/WgbMtsTVHAWi3ALqJzCwxng==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/cspell-resolver": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/cspell-resolver/-/cspell-resolver-9.3.2.tgz", - "integrity": "sha512-jLN2Aa/vxm8+IBvTd884SwPEfjxnDwIEPBT3hmqgLlKuUHQ3FMG27lsM4Ik9L2KWBXMgV/wGz4BaxfhKI41Ttw==", - "dev": true, - "license": "MIT", - "dependencies": { - "global-directory": "^4.0.1" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/cspell-service-bus": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/cspell-service-bus/-/cspell-service-bus-9.3.2.tgz", - "integrity": "sha512-/rB8LazM0JzKL+AvZa5fEpLutmwy5QFMpzw8HJd+rDGkzb5r79hURWSRo84QArgaskUqA9XlOHSieDE9pt+WAA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/cspell-types": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/cspell-types/-/cspell-types-9.3.2.tgz", - "integrity": "sha512-l4H8bMAmdzCbXHO8y1JZiAKszrPEiuLFKWrbhCacHF0iP+PIc/yuQp7cO70m0p70vArRfih6kgGyHFaCy47CfA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/dict-ada": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-ada/-/dict-ada-4.1.1.tgz", - "integrity": "sha512-E+0YW9RhZod/9Qy2gxfNZiHJjCYFlCdI69br1eviQQWB8yOTJX0JHXLs79kOYhSW0kINPVUdvddEBe6Lu6CjGQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-al": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-al/-/dict-al-1.1.1.tgz", - "integrity": "sha512-sD8GCaZetgQL4+MaJLXqbzWcRjfKVp8x+px3HuCaaiATAAtvjwUQ5/Iubiqwfd1boIh2Y1/3EgM3TLQ7Q8e0wQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-aws": { - "version": "4.0.16", - "resolved": "https://registry.npmjs.org/@cspell/dict-aws/-/dict-aws-4.0.16.tgz", - "integrity": "sha512-a681zShZbtTo947NvTYGLer95ZDQw1ROKvIFydak1e0OlfFCsNdtcYTupn0nbbYs53c9AO7G2DU8AcNEAnwXPA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-bash": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/@cspell/dict-bash/-/dict-bash-4.2.2.tgz", - "integrity": "sha512-kyWbwtX3TsCf5l49gGQIZkRLaB/P8g73GDRm41Zu8Mv51kjl2H7Au0TsEvHv7jzcsRLS6aUYaZv6Zsvk1fOz+Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/dict-shell": "1.1.2" - } - }, - "node_modules/@cspell/dict-companies": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/@cspell/dict-companies/-/dict-companies-3.2.7.tgz", - "integrity": "sha512-fEyr3LmpFKTaD0LcRhB4lfW1AmULYBqzg4gWAV0dQCv06l+TsA+JQ+3pZJbUcoaZirtgsgT3dL3RUjmGPhUH0A==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-cpp": { - "version": "6.0.14", - "resolved": "https://registry.npmjs.org/@cspell/dict-cpp/-/dict-cpp-6.0.14.tgz", - "integrity": "sha512-dkmpSwvVfVdtoZ4mW/CK2Ep1v8mJlp6uiKpMNbSMOdJl4kq28nQS4vKNIX3B2bJa0Ha5iHHu+1mNjiLeO3g7Xg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-cryptocurrencies": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/@cspell/dict-cryptocurrencies/-/dict-cryptocurrencies-5.0.5.tgz", - "integrity": "sha512-R68hYYF/rtlE6T/dsObStzN5QZw+0aQBinAXuWCVqwdS7YZo0X33vGMfChkHaiCo3Z2+bkegqHlqxZF4TD3rUA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-csharp": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/@cspell/dict-csharp/-/dict-csharp-4.0.7.tgz", - "integrity": "sha512-H16Hpu8O/1/lgijFt2lOk4/nnldFtQ4t8QHbyqphqZZVE5aS4J/zD/WvduqnLY21aKhZS6jo/xF5PX9jyqPKUA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-css": { - "version": "4.0.18", - "resolved": "https://registry.npmjs.org/@cspell/dict-css/-/dict-css-4.0.18.tgz", - "integrity": "sha512-EF77RqROHL+4LhMGW5NTeKqfUd/e4OOv6EDFQ/UQQiFyWuqkEKyEz0NDILxOFxWUEVdjT2GQ2cC7t12B6pESwg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-dart": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-dart/-/dict-dart-2.3.1.tgz", - "integrity": "sha512-xoiGnULEcWdodXI6EwVyqpZmpOoh8RA2Xk9BNdR7DLamV/QMvEYn8KJ7NlRiTSauJKPNkHHQ5EVHRM6sTS7jdg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-data-science": { - "version": "2.0.12", - "resolved": "https://registry.npmjs.org/@cspell/dict-data-science/-/dict-data-science-2.0.12.tgz", - "integrity": "sha512-vI/mg6cI28IkFcpeINS7cm5M9HWemmXSTnxJiu3nmc4VAGx35SXIEyuLGBcsVzySvDablFYf4hsEpmg1XpVsUQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-django": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/@cspell/dict-django/-/dict-django-4.1.5.tgz", - "integrity": "sha512-AvTWu99doU3T8ifoMYOMLW2CXKvyKLukPh1auOPwFGHzueWYvBBN+OxF8wF7XwjTBMMeRleVdLh3aWCDEX/ZWg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-docker": { - "version": "1.1.16", - "resolved": "https://registry.npmjs.org/@cspell/dict-docker/-/dict-docker-1.1.16.tgz", - "integrity": "sha512-UiVQ5RmCg6j0qGIxrBnai3pIB+aYKL3zaJGvXk1O/ertTKJif9RZikKXCEgqhaCYMweM4fuLqWSVmw3hU164Iw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-dotnet": { - "version": "5.0.10", - "resolved": "https://registry.npmjs.org/@cspell/dict-dotnet/-/dict-dotnet-5.0.10.tgz", - "integrity": "sha512-ooar8BP/RBNP1gzYfJPStKEmpWy4uv/7JCq6FOnJLeD1yyfG3d/LFMVMwiJo+XWz025cxtkM3wuaikBWzCqkmg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-elixir": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/@cspell/dict-elixir/-/dict-elixir-4.0.8.tgz", - "integrity": "sha512-CyfphrbMyl4Ms55Vzuj+mNmd693HjBFr9hvU+B2YbFEZprE5AG+EXLYTMRWrXbpds4AuZcvN3deM2XVB80BN/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-en_us": { - "version": "4.4.24", - "resolved": "https://registry.npmjs.org/@cspell/dict-en_us/-/dict-en_us-4.4.24.tgz", - "integrity": "sha512-JE+/H2YicHJTneRmgH4GSI21rS+1yGZVl1jfOQgl8iHLC+yTTMtCvueNDMK94CgJACzYAoCsQB70MqiFJJfjLQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-en-common-misspellings": { - "version": "2.1.8", - "resolved": "https://registry.npmjs.org/@cspell/dict-en-common-misspellings/-/dict-en-common-misspellings-2.1.8.tgz", - "integrity": "sha512-vDsjRFPQGuAADAiitf82z9Mz3DcqKZi6V5hPAEIFkLLKjFVBcjUsSq59SfL59ElIFb76MtBO0BLifdEbBj+DoQ==", - "dev": true, - "license": "CC BY-SA 4.0" - }, - "node_modules/@cspell/dict-en-gb": { - "version": "5.0.19", - "resolved": "https://registry.npmjs.org/@cspell/dict-en-gb/-/dict-en-gb-5.0.19.tgz", - "integrity": "sha512-/p+p/9q8XTzsE0GxbZZKcC1rTLYmCpilYw8aC9Q1xJbve8YqZnpxk8IxRyaHwfy1TeKMQNs6heZZRtzPag0rCw==", - "dev": true, - "license": "LGPL-3.0" - }, - "node_modules/@cspell/dict-en-gb-mit": { - "version": "3.1.14", - "resolved": "https://registry.npmjs.org/@cspell/dict-en-gb-mit/-/dict-en-gb-mit-3.1.14.tgz", - "integrity": "sha512-b+vEerlHP6rnNf30tmTJb7JZnOq4WAslYUvexOz/L3gDna9YJN3bAnwRJ3At3bdcOcMG7PTv3Pi+C73IR22lNg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-filetypes": { - "version": "3.0.14", - "resolved": "https://registry.npmjs.org/@cspell/dict-filetypes/-/dict-filetypes-3.0.14.tgz", - "integrity": "sha512-KSXaSMYYNMLLdHEnju1DyRRH3eQWPRYRnOXpuHUdOh2jC44VgQoxyMU7oB3NAhDhZKBPCihabzECsAGFbdKfEA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-flutter": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-flutter/-/dict-flutter-1.1.1.tgz", - "integrity": "sha512-UlOzRcH2tNbFhZmHJN48Za/2/MEdRHl2BMkCWZBYs+30b91mWvBfzaN4IJQU7dUZtowKayVIF9FzvLZtZokc5A==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-fonts": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/@cspell/dict-fonts/-/dict-fonts-4.0.5.tgz", - "integrity": "sha512-BbpkX10DUX/xzHs6lb7yzDf/LPjwYIBJHJlUXSBXDtK/1HaeS+Wqol4Mlm2+NAgZ7ikIE5DQMViTgBUY3ezNoQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-fsharp": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-fsharp/-/dict-fsharp-1.1.1.tgz", - "integrity": "sha512-imhs0u87wEA4/cYjgzS0tAyaJpwG7vwtC8UyMFbwpmtw+/bgss+osNfyqhYRyS/ehVCWL17Ewx2UPkexjKyaBA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-fullstack": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/@cspell/dict-fullstack/-/dict-fullstack-3.2.7.tgz", - "integrity": "sha512-IxEk2YAwAJKYCUEgEeOg3QvTL4XLlyArJElFuMQevU1dPgHgzWElFevN5lsTFnvMFA1riYsVinqJJX0BanCFEg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-gaming-terms": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@cspell/dict-gaming-terms/-/dict-gaming-terms-1.1.2.tgz", - "integrity": "sha512-9XnOvaoTBscq0xuD6KTEIkk9hhdfBkkvJAIsvw3JMcnp1214OCGW8+kako5RqQ2vTZR3Tnf3pc57o7VgkM0q1Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-git": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/@cspell/dict-git/-/dict-git-3.0.7.tgz", - "integrity": "sha512-odOwVKgfxCQfiSb+nblQZc4ErXmnWEnv8XwkaI4sNJ7cNmojnvogYVeMqkXPjvfrgEcizEEA4URRD2Ms5PDk1w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-golang": { - "version": "6.0.24", - "resolved": "https://registry.npmjs.org/@cspell/dict-golang/-/dict-golang-6.0.24.tgz", - "integrity": "sha512-rY7PlC3MsHozmjrZWi0HQPUl0BVCV0+mwK0rnMT7pOIXqOe4tWCYMULDIsEk4F0gbIxb5badd2dkCPDYjLnDgA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-google": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@cspell/dict-google/-/dict-google-1.0.9.tgz", - "integrity": "sha512-biL65POqialY0i4g6crj7pR6JnBkbsPovB2WDYkj3H4TuC/QXv7Pu5pdPxeUJA6TSCHI7T5twsO4VSVyRxD9CA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-haskell": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/@cspell/dict-haskell/-/dict-haskell-4.0.6.tgz", - "integrity": "sha512-ib8SA5qgftExpYNjWhpYIgvDsZ/0wvKKxSP+kuSkkak520iPvTJumEpIE+qPcmJQo4NzdKMN8nEfaeci4OcFAQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-html": { - "version": "4.0.12", - "resolved": "https://registry.npmjs.org/@cspell/dict-html/-/dict-html-4.0.12.tgz", - "integrity": "sha512-JFffQ1dDVEyJq6tCDWv0r/RqkdSnV43P2F/3jJ9rwLgdsOIXwQbXrz6QDlvQLVvNSnORH9KjDtenFTGDyzfCaA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-html-symbol-entities": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@cspell/dict-html-symbol-entities/-/dict-html-symbol-entities-4.0.4.tgz", - "integrity": "sha512-afea+0rGPDeOV9gdO06UW183Qg6wRhWVkgCFwiO3bDupAoyXRuvupbb5nUyqSTsLXIKL8u8uXQlJ9pkz07oVXw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-java": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/@cspell/dict-java/-/dict-java-5.0.12.tgz", - "integrity": "sha512-qPSNhTcl7LGJ5Qp6VN71H8zqvRQK04S08T67knMq9hTA8U7G1sTKzLmBaDOFhq17vNX/+rT+rbRYp+B5Nwza1A==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-julia": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-julia/-/dict-julia-1.1.1.tgz", - "integrity": "sha512-WylJR9TQ2cgwd5BWEOfdO3zvDB+L7kYFm0I9u0s9jKHWQ6yKmfKeMjU9oXxTBxIufhCXm92SKwwVNAC7gjv+yA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-k8s": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/@cspell/dict-k8s/-/dict-k8s-1.0.12.tgz", - "integrity": "sha512-2LcllTWgaTfYC7DmkMPOn9GsBWsA4DZdlun4po8s2ysTP7CPEnZc1ZfK6pZ2eI4TsZemlUQQ+NZxMe9/QutQxg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-kotlin": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-kotlin/-/dict-kotlin-1.1.1.tgz", - "integrity": "sha512-J3NzzfgmxRvEeOe3qUXnSJQCd38i/dpF9/t3quuWh6gXM+krsAXP75dY1CzDmS8mrJAlBdVBeAW5eAZTD8g86Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-latex": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@cspell/dict-latex/-/dict-latex-4.0.4.tgz", - "integrity": "sha512-YdTQhnTINEEm/LZgTzr9Voz4mzdOXH7YX+bSFs3hnkUHCUUtX/mhKgf1CFvZ0YNM2afjhQcmLaR9bDQVyYBvpA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-lorem-ipsum": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/@cspell/dict-lorem-ipsum/-/dict-lorem-ipsum-4.0.5.tgz", - "integrity": "sha512-9a4TJYRcPWPBKkQAJ/whCu4uCAEgv/O2xAaZEI0n4y1/l18Yyx8pBKoIX5QuVXjjmKEkK7hi5SxyIsH7pFEK9Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-lua": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/@cspell/dict-lua/-/dict-lua-4.0.8.tgz", - "integrity": "sha512-N4PkgNDMu9JVsRu7JBS/3E/dvfItRgk9w5ga2dKq+JupP2Y3lojNaAVFhXISh4Y0a6qXDn2clA6nvnavQ/jjLA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-makefile": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/@cspell/dict-makefile/-/dict-makefile-1.0.5.tgz", - "integrity": "sha512-4vrVt7bGiK8Rx98tfRbYo42Xo2IstJkAF4tLLDMNQLkQ86msDlYSKG1ZCk8Abg+EdNcFAjNhXIiNO+w4KflGAQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-markdown": { - "version": "2.0.12", - "resolved": "https://registry.npmjs.org/@cspell/dict-markdown/-/dict-markdown-2.0.12.tgz", - "integrity": "sha512-ufwoliPijAgWkD/ivAMC+A9QD895xKiJRF/fwwknQb7kt7NozTLKFAOBtXGPJAB4UjhGBpYEJVo2elQ0FCAH9A==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "@cspell/dict-css": "^4.0.18", - "@cspell/dict-html": "^4.0.12", - "@cspell/dict-html-symbol-entities": "^4.0.4", - "@cspell/dict-typescript": "^3.2.3" - } - }, - "node_modules/@cspell/dict-monkeyc": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@cspell/dict-monkeyc/-/dict-monkeyc-1.0.11.tgz", - "integrity": "sha512-7Q1Ncu0urALI6dPTrEbSTd//UK0qjRBeaxhnm8uY5fgYNFYAG+u4gtnTIo59S6Bw5P++4H3DiIDYoQdY/lha8w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-node": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/@cspell/dict-node/-/dict-node-5.0.8.tgz", - "integrity": "sha512-AirZcN2i84ynev3p2/1NCPEhnNsHKMz9zciTngGoqpdItUb2bDt1nJBjwlsrFI78GZRph/VaqTVFwYikmncpXg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-npm": { - "version": "5.2.23", - "resolved": "https://registry.npmjs.org/@cspell/dict-npm/-/dict-npm-5.2.23.tgz", - "integrity": "sha512-cnlPGzhNkbXFLFURfjzwML2LjHMofqJkemR7lLo9Jwa9IptvzeTn4nOtJMSGfkxNrZPf/IvQ7rH5hamsUQLQ3A==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-php": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@cspell/dict-php/-/dict-php-4.1.0.tgz", - "integrity": "sha512-dTDeabyOj7eFvn2Q4Za3uVXM2+SzeFMqX8ly2P0XTo4AzbCmI2hulFD/QIADwWmwiRrInbbf8cxwFHNIYrXl4w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-powershell": { - "version": "5.0.15", - "resolved": "https://registry.npmjs.org/@cspell/dict-powershell/-/dict-powershell-5.0.15.tgz", - "integrity": "sha512-l4S5PAcvCFcVDMJShrYD0X6Huv9dcsQPlsVsBGbH38wvuN7gS7+GxZFAjTNxDmTY1wrNi1cCatSg6Pu2BW4rgg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-public-licenses": { - "version": "2.0.15", - "resolved": "https://registry.npmjs.org/@cspell/dict-public-licenses/-/dict-public-licenses-2.0.15.tgz", - "integrity": "sha512-cJEOs901H13Pfy0fl4dCD1U+xpWIMaEPq8MeYU83FfDZvellAuSo4GqWCripfIqlhns/L6+UZEIJSOZnjgy7Wg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-python": { - "version": "4.2.22", - "resolved": "https://registry.npmjs.org/@cspell/dict-python/-/dict-python-4.2.22.tgz", - "integrity": "sha512-rgF7DuleVK2lkzlw33jjEfxS2a0CU5kwAhOqf5B6XkuaPbqZ/0g0LBCdwglAGccYu7sBuvxRS8Yubk+ytSAFTg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/dict-data-science": "^2.0.12" - } - }, - "node_modules/@cspell/dict-r": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-r/-/dict-r-2.1.1.tgz", - "integrity": "sha512-71Ka+yKfG4ZHEMEmDxc6+blFkeTTvgKbKAbwiwQAuKl3zpqs1Y0vUtwW2N4b3LgmSPhV3ODVY0y4m5ofqDuKMw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-ruby": { - "version": "5.0.9", - "resolved": "https://registry.npmjs.org/@cspell/dict-ruby/-/dict-ruby-5.0.9.tgz", - "integrity": "sha512-H2vMcERMcANvQshAdrVx0XoWaNX8zmmiQN11dZZTQAZaNJ0xatdJoSqY8C8uhEMW89bfgpN+NQgGuDXW2vmXEw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-rust": { - "version": "4.0.12", - "resolved": "https://registry.npmjs.org/@cspell/dict-rust/-/dict-rust-4.0.12.tgz", - "integrity": "sha512-z2QiH+q9UlNhobBJArvILRxV8Jz0pKIK7gqu4TgmEYyjiu1TvnGZ1tbYHeu9w3I/wOP6UMDoCBTty5AlYfW0mw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-scala": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/@cspell/dict-scala/-/dict-scala-5.0.8.tgz", - "integrity": "sha512-YdftVmumv8IZq9zu1gn2U7A4bfM2yj9Vaupydotyjuc+EEZZSqAafTpvW/jKLWji2TgybM1L2IhmV0s/Iv9BTw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-shell": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@cspell/dict-shell/-/dict-shell-1.1.2.tgz", - "integrity": "sha512-WqOUvnwcHK1X61wAfwyXq04cn7KYyskg90j4lLg3sGGKMW9Sq13hs91pqrjC44Q+lQLgCobrTkMDw9Wyl9nRFA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-software-terms": { - "version": "5.1.14", - "resolved": "https://registry.npmjs.org/@cspell/dict-software-terms/-/dict-software-terms-5.1.14.tgz", - "integrity": "sha512-Eu9h090hxHJiqzVFS0WxOZbYXnmb7F1RFIUEg4Nru+D/78bXVDH4b8BiKGVFNRljaieNQRAHaryzdaKJRCH6ZA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-sql": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/@cspell/dict-sql/-/dict-sql-2.2.1.tgz", - "integrity": "sha512-qDHF8MpAYCf4pWU8NKbnVGzkoxMNrFqBHyG/dgrlic5EQiKANCLELYtGlX5auIMDLmTf1inA0eNtv74tyRJ/vg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-svelte": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/@cspell/dict-svelte/-/dict-svelte-1.0.7.tgz", - "integrity": "sha512-hGZsGqP0WdzKkdpeVLBivRuSNzOTvN036EBmpOwxH+FTY2DuUH7ecW+cSaMwOgmq5JFSdTcbTNFlNC8HN8lhaQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-swift": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@cspell/dict-swift/-/dict-swift-2.0.6.tgz", - "integrity": "sha512-PnpNbrIbex2aqU1kMgwEKvCzgbkHtj3dlFLPMqW1vSniop7YxaDTtvTUO4zA++ugYAEL+UK8vYrBwDPTjjvSnA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-terraform": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@cspell/dict-terraform/-/dict-terraform-1.1.3.tgz", - "integrity": "sha512-gr6wxCydwSFyyBKhBA2xkENXtVFToheqYYGFvlMZXWjviynXmh+NK/JTvTCk/VHk3+lzbO9EEQKee6VjrAUSbA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-typescript": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/@cspell/dict-typescript/-/dict-typescript-3.2.3.tgz", - "integrity": "sha512-zXh1wYsNljQZfWWdSPYwQhpwiuW0KPW1dSd8idjMRvSD0aSvWWHoWlrMsmZeRl4qM4QCEAjua8+cjflm41cQBg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-vue": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/@cspell/dict-vue/-/dict-vue-3.0.5.tgz", - "integrity": "sha512-Mqutb8jbM+kIcywuPQCCaK5qQHTdaByoEO2J9LKFy3sqAdiBogNkrplqUK0HyyRFgCfbJUgjz3N85iCMcWH0JA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dict-zig": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@cspell/dict-zig/-/dict-zig-1.0.0.tgz", - "integrity": "sha512-XibBIxBlVosU06+M6uHWkFeT0/pW5WajDRYdXG2CgHnq85b0TI/Ks0FuBJykmsgi2CAD3Qtx8UHFEtl/DSFnAQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspell/dynamic-import": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/dynamic-import/-/dynamic-import-9.3.2.tgz", - "integrity": "sha512-au7FyuIHUNI2r9sO3pUBKVTeD/v7c9x/nPUStaAK1bG4rdKt4w+/jUY2IaldAraW5w29z528BboXbiV87SM1kw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/url": "9.3.2", - "import-meta-resolve": "^4.2.0" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/filetypes": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/filetypes/-/filetypes-9.3.2.tgz", - "integrity": "sha512-0bUxQlmJPRHZrRQD7adbc4lFizO8tGD/6+1cBgU3kV3+NVrpr12y4jU8twCSChhYibZyPr7bnvhkM3cQgb8RzA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/strong-weak-map": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/strong-weak-map/-/strong-weak-map-9.3.2.tgz", - "integrity": "sha512-pFcmOTWCoFMRETb9PCkCmaiZiLb5i2qOZmGH/p/tFEH8kIYhMGfhaulnXwKwS+Ke6PKceQd2YL98bGmo8hL4aQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/@cspell/url": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/@cspell/url/-/url-9.3.2.tgz", - "integrity": "sha512-TobUlZl7Z7VehhNOMNAg1ABuGizieseftlG94OZJ934JptOhK8TC/1o2ldKrbDH50jyt6E7rPTMV2BW/vWuTzQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/@docsearch/css": { - "version": "3.8.2", - "resolved": "https://registry.npmjs.org/@docsearch/css/-/css-3.8.2.tgz", - "integrity": "sha512-y05ayQFyUmCXze79+56v/4HpycYF3uFqB78pLPrSV5ZKAlDuIAAJNhaRi8tTdRNXh05yxX/TyNnzD6LwSM89vQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@docsearch/js": { - "version": "3.8.2", - "resolved": "https://registry.npmjs.org/@docsearch/js/-/js-3.8.2.tgz", - "integrity": "sha512-Q5wY66qHn0SwA7Taa0aDbHiJvaFJLOJyHmooQ7y8hlwwQLQ/5WwCcoX0g7ii04Qi2DJlHsd0XXzJ8Ypw9+9YmQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@docsearch/react": "3.8.2", - "preact": "^10.0.0" - } - }, - "node_modules/@docsearch/react": { - "version": "3.8.2", - "resolved": "https://registry.npmjs.org/@docsearch/react/-/react-3.8.2.tgz", - "integrity": "sha512-xCRrJQlTt8N9GU0DG4ptwHRkfnSnD/YpdeaXe02iKfqs97TkZJv60yE+1eq/tjPcVnTW8dP5qLP7itifFVV5eg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/autocomplete-core": "1.17.7", - "@algolia/autocomplete-preset-algolia": "1.17.7", - "@docsearch/css": "3.8.2", - "algoliasearch": "^5.14.2" - }, - "peerDependencies": { - "@types/react": ">= 16.8.0 < 19.0.0", - "react": ">= 16.8.0 < 19.0.0", - "react-dom": ">= 16.8.0 < 19.0.0", - "search-insights": ">= 1 < 3" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "docs", + "version": "1.0.0", + "license": "ISC", + "devDependencies": { + "@cspell/dict-en-gb": "^5.0.19", + "cspell": "^9.3.2", + "prettier": "^3.6.2", + "vitepress": "^1.6.4", + "vue": "^3.5.24" + } }, - "react": { - "optional": true + "node_modules/@algolia/abtesting": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@algolia/abtesting/-/abtesting-1.10.0.tgz", + "integrity": "sha512-mQT3jwuTgX8QMoqbIR7mPlWkqQqBPQaPabQzm37xg2txMlaMogK/4hCiiESGdg39MlHZOVHeV+0VJuE7f5UK8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } }, - "react-dom": { - "optional": true + "node_modules/@algolia/autocomplete-core": { + "version": "1.17.7", + "resolved": "https://registry.npmjs.org/@algolia/autocomplete-core/-/autocomplete-core-1.17.7.tgz", + "integrity": "sha512-BjiPOW6ks90UKl7TwMv7oNQMnzU+t/wk9mgIDi6b1tXpUek7MW0lbNOUHpvam9pe3lVCf4xPFT+lK7s+e+fs7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/autocomplete-plugin-algolia-insights": "1.17.7", + "@algolia/autocomplete-shared": "1.17.7" + } }, - "search-insights": { - "optional": true + "node_modules/@algolia/autocomplete-plugin-algolia-insights": { + "version": "1.17.7", + "resolved": "https://registry.npmjs.org/@algolia/autocomplete-plugin-algolia-insights/-/autocomplete-plugin-algolia-insights-1.17.7.tgz", + "integrity": "sha512-Jca5Ude6yUOuyzjnz57og7Et3aXjbwCSDf/8onLHSQgw1qW3ALl9mrMWaXb5FmPVkV3EtkD2F/+NkT6VHyPu9A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/autocomplete-shared": "1.17.7" + }, + "peerDependencies": { + "search-insights": ">= 1 < 3" + } + }, + "node_modules/@algolia/autocomplete-preset-algolia": { + "version": "1.17.7", + "resolved": "https://registry.npmjs.org/@algolia/autocomplete-preset-algolia/-/autocomplete-preset-algolia-1.17.7.tgz", + "integrity": "sha512-ggOQ950+nwbWROq2MOCIL71RE0DdQZsceqrg32UqnhDz8FlO9rL8ONHNsI2R1MH0tkgVIDKI/D0sMiUchsFdWA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/autocomplete-shared": "1.17.7" + }, + "peerDependencies": { + "@algolia/client-search": ">= 4.9.1 < 6", + "algoliasearch": ">= 4.9.1 < 6" + } + }, + "node_modules/@algolia/autocomplete-shared": { + "version": "1.17.7", + "resolved": "https://registry.npmjs.org/@algolia/autocomplete-shared/-/autocomplete-shared-1.17.7.tgz", + "integrity": "sha512-o/1Vurr42U/qskRSuhBH+VKxMvkkUVTLU6WZQr+L5lGZZLYWyhdzWjW0iGXY7EkwRTjBqvN2EsR81yCTGV/kmg==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@algolia/client-search": ">= 4.9.1 < 6", + "algoliasearch": ">= 4.9.1 < 6" + } + }, + "node_modules/@algolia/client-abtesting": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/client-abtesting/-/client-abtesting-5.44.0.tgz", + "integrity": "sha512-KY5CcrWhRTUo/lV7KcyjrZkPOOF9bjgWpMj9z98VA+sXzVpZtkuskBLCKsWYFp2sbwchZFTd3wJM48H0IGgF7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/client-analytics": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-5.44.0.tgz", + "integrity": "sha512-LKOCE8S4ewI9bN3ot9RZoYASPi8b78E918/DVPW3HHjCMUe6i+NjbNG6KotU4RpP6AhRWZjjswbOkWelUO+OoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/client-common": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/client-common/-/client-common-5.44.0.tgz", + "integrity": "sha512-1yyJm4OYC2cztbS28XYVWwLXdwpLsMG4LoZLOltVglQ2+hc/i9q9fUDZyjRa2Bqt4DmkIfezagfMrokhyH4uxQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/client-insights": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/client-insights/-/client-insights-5.44.0.tgz", + "integrity": "sha512-wVQWK6jYYsbEOjIMI+e5voLGPUIbXrvDj392IckXaCPvQ6vCMTXakQqOYCd+znQdL76S+3wHDo77HZWiAYKrtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/client-personalization": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-5.44.0.tgz", + "integrity": "sha512-lkgRjOjOkqmIkebHjHpU9rLJcJNUDMm+eVSW/KJQYLjGqykEZxal+nYJJTBbLceEU2roByP/+27ZmgIwCdf0iA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/client-query-suggestions": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/client-query-suggestions/-/client-query-suggestions-5.44.0.tgz", + "integrity": "sha512-sYfhgwKu6NDVmZHL1WEKVLsOx/jUXCY4BHKLUOcYa8k4COCs6USGgz6IjFkUf+niwq8NCECMmTC4o/fVQOalsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/client-search": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/client-search/-/client-search-5.44.0.tgz", + "integrity": "sha512-/FRKUM1G4xn3vV8+9xH1WJ9XknU8rkBGlefruq9jDhYUAvYozKimhrmC2pRqw/RyHhPivmgZCRuC8jHP8piz4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/ingestion": { + "version": "1.44.0", + "resolved": "https://registry.npmjs.org/@algolia/ingestion/-/ingestion-1.44.0.tgz", + "integrity": "sha512-5+S5ynwMmpTpCLXGjTDpeIa81J+R4BLH0lAojOhmeGSeGEHQTqacl/4sbPyDTcidvnWhaqtyf8m42ue6lvISAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/monitoring": { + "version": "1.44.0", + "resolved": "https://registry.npmjs.org/@algolia/monitoring/-/monitoring-1.44.0.tgz", + "integrity": "sha512-xhaTN8pXJjR6zkrecg4Cc9YZaQK2LKm2R+LkbAq+AYGBCWJxtSGlNwftozZzkUyq4AXWoyoc0x2SyBtq5LRtqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/recommend": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/recommend/-/recommend-5.44.0.tgz", + "integrity": "sha512-GNcite/uOIS7wgRU1MT7SdNIupGSW+vbK9igIzMePvD2Dl8dy0O3urKPKIbTuZQqiVH1Cb84y5cgLvwNrdCj/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/requester-browser-xhr": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-5.44.0.tgz", + "integrity": "sha512-YZHBk72Cd7pcuNHzbhNzF/FbbYszlc7JhZlDyQAchnX5S7tcemSS96F39Sy8t4O4WQLpFvUf1MTNedlitWdOsQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/requester-fetch": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-fetch/-/requester-fetch-5.44.0.tgz", + "integrity": "sha512-B9WHl+wQ7uf46t9cq+vVM/ypVbOeuldVDq9OtKsX2ApL2g/htx6ImB9ugDOOJmB5+fE31/XPTuCcYz/j03+idA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@algolia/requester-node-http": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-5.44.0.tgz", + "integrity": "sha512-MULm0qeAIk4cdzZ/ehJnl1o7uB5NMokg83/3MKhPq0Pk7+I0uELGNbzIfAkvkKKEYcHALemKdArtySF9eKzh/A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/client-common": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.28.5.tgz", + "integrity": "sha512-KKBU1VGYR7ORr3At5HAtUQ+TV3SzRCXmA/8OdDZiLDBIZxVyzXuztPjfLd3BV1PRAQGCMWWSHYhL0F8d5uHBDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.5" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.5.tgz", + "integrity": "sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@cspell/cspell-bundled-dicts": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/cspell-bundled-dicts/-/cspell-bundled-dicts-9.3.2.tgz", + "integrity": "sha512-OmKzq/0FATHU671GKMzBrTyLdm25Wnziva7h4ylumVn1wnwWsXGef5bgXD7iuApqfqH9SzxsU0NtTB8m8vwEHQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/dict-ada": "^4.1.1", + "@cspell/dict-al": "^1.1.1", + "@cspell/dict-aws": "^4.0.16", + "@cspell/dict-bash": "^4.2.2", + "@cspell/dict-companies": "^3.2.7", + "@cspell/dict-cpp": "^6.0.14", + "@cspell/dict-cryptocurrencies": "^5.0.5", + "@cspell/dict-csharp": "^4.0.7", + "@cspell/dict-css": "^4.0.18", + "@cspell/dict-dart": "^2.3.1", + "@cspell/dict-data-science": "^2.0.11", + "@cspell/dict-django": "^4.1.5", + "@cspell/dict-docker": "^1.1.16", + "@cspell/dict-dotnet": "^5.0.10", + "@cspell/dict-elixir": "^4.0.8", + "@cspell/dict-en_us": "^4.4.24", + "@cspell/dict-en-common-misspellings": "^2.1.8", + "@cspell/dict-en-gb-mit": "^3.1.14", + "@cspell/dict-filetypes": "^3.0.14", + "@cspell/dict-flutter": "^1.1.1", + "@cspell/dict-fonts": "^4.0.5", + "@cspell/dict-fsharp": "^1.1.1", + "@cspell/dict-fullstack": "^3.2.7", + "@cspell/dict-gaming-terms": "^1.1.2", + "@cspell/dict-git": "^3.0.7", + "@cspell/dict-golang": "^6.0.24", + "@cspell/dict-google": "^1.0.9", + "@cspell/dict-haskell": "^4.0.6", + "@cspell/dict-html": "^4.0.12", + "@cspell/dict-html-symbol-entities": "^4.0.4", + "@cspell/dict-java": "^5.0.12", + "@cspell/dict-julia": "^1.1.1", + "@cspell/dict-k8s": "^1.0.12", + "@cspell/dict-kotlin": "^1.1.1", + "@cspell/dict-latex": "^4.0.4", + "@cspell/dict-lorem-ipsum": "^4.0.5", + "@cspell/dict-lua": "^4.0.8", + "@cspell/dict-makefile": "^1.0.5", + "@cspell/dict-markdown": "^2.0.12", + "@cspell/dict-monkeyc": "^1.0.11", + "@cspell/dict-node": "^5.0.8", + "@cspell/dict-npm": "^5.2.22", + "@cspell/dict-php": "^4.1.0", + "@cspell/dict-powershell": "^5.0.15", + "@cspell/dict-public-licenses": "^2.0.15", + "@cspell/dict-python": "^4.2.21", + "@cspell/dict-r": "^2.1.1", + "@cspell/dict-ruby": "^5.0.9", + "@cspell/dict-rust": "^4.0.12", + "@cspell/dict-scala": "^5.0.8", + "@cspell/dict-shell": "^1.1.2", + "@cspell/dict-software-terms": "^5.1.13", + "@cspell/dict-sql": "^2.2.1", + "@cspell/dict-svelte": "^1.0.7", + "@cspell/dict-swift": "^2.0.6", + "@cspell/dict-terraform": "^1.1.3", + "@cspell/dict-typescript": "^3.2.3", + "@cspell/dict-vue": "^3.0.5", + "@cspell/dict-zig": "^1.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/cspell-json-reporter": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/cspell-json-reporter/-/cspell-json-reporter-9.3.2.tgz", + "integrity": "sha512-YRgpeHN9uY8kUlIw9q+8zJ0tRTAJMbfBTGzCq9Puah09NeMWlRMFPUkXVrkdic6NA7etboZ+zEdoZwRO9EmhiA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/cspell-types": "9.3.2" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/cspell-pipe": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/cspell-pipe/-/cspell-pipe-9.3.2.tgz", + "integrity": "sha512-REF7ibG79WLEynIMUss/IRDCdYEb1nlE1rj/gt2CbPFzLa6t5MRwW2lajEvXS6/WgbMtsTVHAWi3ALqJzCwxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/cspell-resolver": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/cspell-resolver/-/cspell-resolver-9.3.2.tgz", + "integrity": "sha512-jLN2Aa/vxm8+IBvTd884SwPEfjxnDwIEPBT3hmqgLlKuUHQ3FMG27lsM4Ik9L2KWBXMgV/wGz4BaxfhKI41Ttw==", + "dev": true, + "license": "MIT", + "dependencies": { + "global-directory": "^4.0.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/cspell-service-bus": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/cspell-service-bus/-/cspell-service-bus-9.3.2.tgz", + "integrity": "sha512-/rB8LazM0JzKL+AvZa5fEpLutmwy5QFMpzw8HJd+rDGkzb5r79hURWSRo84QArgaskUqA9XlOHSieDE9pt+WAA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/cspell-types": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/cspell-types/-/cspell-types-9.3.2.tgz", + "integrity": "sha512-l4H8bMAmdzCbXHO8y1JZiAKszrPEiuLFKWrbhCacHF0iP+PIc/yuQp7cO70m0p70vArRfih6kgGyHFaCy47CfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/dict-ada": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-ada/-/dict-ada-4.1.1.tgz", + "integrity": "sha512-E+0YW9RhZod/9Qy2gxfNZiHJjCYFlCdI69br1eviQQWB8yOTJX0JHXLs79kOYhSW0kINPVUdvddEBe6Lu6CjGQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-al": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-al/-/dict-al-1.1.1.tgz", + "integrity": "sha512-sD8GCaZetgQL4+MaJLXqbzWcRjfKVp8x+px3HuCaaiATAAtvjwUQ5/Iubiqwfd1boIh2Y1/3EgM3TLQ7Q8e0wQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-aws": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@cspell/dict-aws/-/dict-aws-4.0.16.tgz", + "integrity": "sha512-a681zShZbtTo947NvTYGLer95ZDQw1ROKvIFydak1e0OlfFCsNdtcYTupn0nbbYs53c9AO7G2DU8AcNEAnwXPA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-bash": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@cspell/dict-bash/-/dict-bash-4.2.2.tgz", + "integrity": "sha512-kyWbwtX3TsCf5l49gGQIZkRLaB/P8g73GDRm41Zu8Mv51kjl2H7Au0TsEvHv7jzcsRLS6aUYaZv6Zsvk1fOz+Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/dict-shell": "1.1.2" + } + }, + "node_modules/@cspell/dict-companies": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@cspell/dict-companies/-/dict-companies-3.2.7.tgz", + "integrity": "sha512-fEyr3LmpFKTaD0LcRhB4lfW1AmULYBqzg4gWAV0dQCv06l+TsA+JQ+3pZJbUcoaZirtgsgT3dL3RUjmGPhUH0A==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-cpp": { + "version": "6.0.14", + "resolved": "https://registry.npmjs.org/@cspell/dict-cpp/-/dict-cpp-6.0.14.tgz", + "integrity": "sha512-dkmpSwvVfVdtoZ4mW/CK2Ep1v8mJlp6uiKpMNbSMOdJl4kq28nQS4vKNIX3B2bJa0Ha5iHHu+1mNjiLeO3g7Xg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-cryptocurrencies": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@cspell/dict-cryptocurrencies/-/dict-cryptocurrencies-5.0.5.tgz", + "integrity": "sha512-R68hYYF/rtlE6T/dsObStzN5QZw+0aQBinAXuWCVqwdS7YZo0X33vGMfChkHaiCo3Z2+bkegqHlqxZF4TD3rUA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-csharp": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/@cspell/dict-csharp/-/dict-csharp-4.0.7.tgz", + "integrity": "sha512-H16Hpu8O/1/lgijFt2lOk4/nnldFtQ4t8QHbyqphqZZVE5aS4J/zD/WvduqnLY21aKhZS6jo/xF5PX9jyqPKUA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-css": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@cspell/dict-css/-/dict-css-4.0.18.tgz", + "integrity": "sha512-EF77RqROHL+4LhMGW5NTeKqfUd/e4OOv6EDFQ/UQQiFyWuqkEKyEz0NDILxOFxWUEVdjT2GQ2cC7t12B6pESwg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-dart": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-dart/-/dict-dart-2.3.1.tgz", + "integrity": "sha512-xoiGnULEcWdodXI6EwVyqpZmpOoh8RA2Xk9BNdR7DLamV/QMvEYn8KJ7NlRiTSauJKPNkHHQ5EVHRM6sTS7jdg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-data-science": { + "version": "2.0.12", + "resolved": "https://registry.npmjs.org/@cspell/dict-data-science/-/dict-data-science-2.0.12.tgz", + "integrity": "sha512-vI/mg6cI28IkFcpeINS7cm5M9HWemmXSTnxJiu3nmc4VAGx35SXIEyuLGBcsVzySvDablFYf4hsEpmg1XpVsUQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-django": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@cspell/dict-django/-/dict-django-4.1.5.tgz", + "integrity": "sha512-AvTWu99doU3T8ifoMYOMLW2CXKvyKLukPh1auOPwFGHzueWYvBBN+OxF8wF7XwjTBMMeRleVdLh3aWCDEX/ZWg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-docker": { + "version": "1.1.16", + "resolved": "https://registry.npmjs.org/@cspell/dict-docker/-/dict-docker-1.1.16.tgz", + "integrity": "sha512-UiVQ5RmCg6j0qGIxrBnai3pIB+aYKL3zaJGvXk1O/ertTKJif9RZikKXCEgqhaCYMweM4fuLqWSVmw3hU164Iw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-dotnet": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/@cspell/dict-dotnet/-/dict-dotnet-5.0.10.tgz", + "integrity": "sha512-ooar8BP/RBNP1gzYfJPStKEmpWy4uv/7JCq6FOnJLeD1yyfG3d/LFMVMwiJo+XWz025cxtkM3wuaikBWzCqkmg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-elixir": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/@cspell/dict-elixir/-/dict-elixir-4.0.8.tgz", + "integrity": "sha512-CyfphrbMyl4Ms55Vzuj+mNmd693HjBFr9hvU+B2YbFEZprE5AG+EXLYTMRWrXbpds4AuZcvN3deM2XVB80BN/Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-en_us": { + "version": "4.4.24", + "resolved": "https://registry.npmjs.org/@cspell/dict-en_us/-/dict-en_us-4.4.24.tgz", + "integrity": "sha512-JE+/H2YicHJTneRmgH4GSI21rS+1yGZVl1jfOQgl8iHLC+yTTMtCvueNDMK94CgJACzYAoCsQB70MqiFJJfjLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-en-common-misspellings": { + "version": "2.1.8", + "resolved": "https://registry.npmjs.org/@cspell/dict-en-common-misspellings/-/dict-en-common-misspellings-2.1.8.tgz", + "integrity": "sha512-vDsjRFPQGuAADAiitf82z9Mz3DcqKZi6V5hPAEIFkLLKjFVBcjUsSq59SfL59ElIFb76MtBO0BLifdEbBj+DoQ==", + "dev": true, + "license": "CC BY-SA 4.0" + }, + "node_modules/@cspell/dict-en-gb": { + "version": "5.0.19", + "resolved": "https://registry.npmjs.org/@cspell/dict-en-gb/-/dict-en-gb-5.0.19.tgz", + "integrity": "sha512-/p+p/9q8XTzsE0GxbZZKcC1rTLYmCpilYw8aC9Q1xJbve8YqZnpxk8IxRyaHwfy1TeKMQNs6heZZRtzPag0rCw==", + "dev": true, + "license": "LGPL-3.0" + }, + "node_modules/@cspell/dict-en-gb-mit": { + "version": "3.1.14", + "resolved": "https://registry.npmjs.org/@cspell/dict-en-gb-mit/-/dict-en-gb-mit-3.1.14.tgz", + "integrity": "sha512-b+vEerlHP6rnNf30tmTJb7JZnOq4WAslYUvexOz/L3gDna9YJN3bAnwRJ3At3bdcOcMG7PTv3Pi+C73IR22lNg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-filetypes": { + "version": "3.0.14", + "resolved": "https://registry.npmjs.org/@cspell/dict-filetypes/-/dict-filetypes-3.0.14.tgz", + "integrity": "sha512-KSXaSMYYNMLLdHEnju1DyRRH3eQWPRYRnOXpuHUdOh2jC44VgQoxyMU7oB3NAhDhZKBPCihabzECsAGFbdKfEA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-flutter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-flutter/-/dict-flutter-1.1.1.tgz", + "integrity": "sha512-UlOzRcH2tNbFhZmHJN48Za/2/MEdRHl2BMkCWZBYs+30b91mWvBfzaN4IJQU7dUZtowKayVIF9FzvLZtZokc5A==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-fonts": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@cspell/dict-fonts/-/dict-fonts-4.0.5.tgz", + "integrity": "sha512-BbpkX10DUX/xzHs6lb7yzDf/LPjwYIBJHJlUXSBXDtK/1HaeS+Wqol4Mlm2+NAgZ7ikIE5DQMViTgBUY3ezNoQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-fsharp": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-fsharp/-/dict-fsharp-1.1.1.tgz", + "integrity": "sha512-imhs0u87wEA4/cYjgzS0tAyaJpwG7vwtC8UyMFbwpmtw+/bgss+osNfyqhYRyS/ehVCWL17Ewx2UPkexjKyaBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-fullstack": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@cspell/dict-fullstack/-/dict-fullstack-3.2.7.tgz", + "integrity": "sha512-IxEk2YAwAJKYCUEgEeOg3QvTL4XLlyArJElFuMQevU1dPgHgzWElFevN5lsTFnvMFA1riYsVinqJJX0BanCFEg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-gaming-terms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@cspell/dict-gaming-terms/-/dict-gaming-terms-1.1.2.tgz", + "integrity": "sha512-9XnOvaoTBscq0xuD6KTEIkk9hhdfBkkvJAIsvw3JMcnp1214OCGW8+kako5RqQ2vTZR3Tnf3pc57o7VgkM0q1Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-git": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/@cspell/dict-git/-/dict-git-3.0.7.tgz", + "integrity": "sha512-odOwVKgfxCQfiSb+nblQZc4ErXmnWEnv8XwkaI4sNJ7cNmojnvogYVeMqkXPjvfrgEcizEEA4URRD2Ms5PDk1w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-golang": { + "version": "6.0.24", + "resolved": "https://registry.npmjs.org/@cspell/dict-golang/-/dict-golang-6.0.24.tgz", + "integrity": "sha512-rY7PlC3MsHozmjrZWi0HQPUl0BVCV0+mwK0rnMT7pOIXqOe4tWCYMULDIsEk4F0gbIxb5badd2dkCPDYjLnDgA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-google": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@cspell/dict-google/-/dict-google-1.0.9.tgz", + "integrity": "sha512-biL65POqialY0i4g6crj7pR6JnBkbsPovB2WDYkj3H4TuC/QXv7Pu5pdPxeUJA6TSCHI7T5twsO4VSVyRxD9CA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-haskell": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@cspell/dict-haskell/-/dict-haskell-4.0.6.tgz", + "integrity": "sha512-ib8SA5qgftExpYNjWhpYIgvDsZ/0wvKKxSP+kuSkkak520iPvTJumEpIE+qPcmJQo4NzdKMN8nEfaeci4OcFAQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-html": { + "version": "4.0.12", + "resolved": "https://registry.npmjs.org/@cspell/dict-html/-/dict-html-4.0.12.tgz", + "integrity": "sha512-JFffQ1dDVEyJq6tCDWv0r/RqkdSnV43P2F/3jJ9rwLgdsOIXwQbXrz6QDlvQLVvNSnORH9KjDtenFTGDyzfCaA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-html-symbol-entities": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@cspell/dict-html-symbol-entities/-/dict-html-symbol-entities-4.0.4.tgz", + "integrity": "sha512-afea+0rGPDeOV9gdO06UW183Qg6wRhWVkgCFwiO3bDupAoyXRuvupbb5nUyqSTsLXIKL8u8uXQlJ9pkz07oVXw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-java": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/@cspell/dict-java/-/dict-java-5.0.12.tgz", + "integrity": "sha512-qPSNhTcl7LGJ5Qp6VN71H8zqvRQK04S08T67knMq9hTA8U7G1sTKzLmBaDOFhq17vNX/+rT+rbRYp+B5Nwza1A==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-julia": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-julia/-/dict-julia-1.1.1.tgz", + "integrity": "sha512-WylJR9TQ2cgwd5BWEOfdO3zvDB+L7kYFm0I9u0s9jKHWQ6yKmfKeMjU9oXxTBxIufhCXm92SKwwVNAC7gjv+yA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-k8s": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/@cspell/dict-k8s/-/dict-k8s-1.0.12.tgz", + "integrity": "sha512-2LcllTWgaTfYC7DmkMPOn9GsBWsA4DZdlun4po8s2ysTP7CPEnZc1ZfK6pZ2eI4TsZemlUQQ+NZxMe9/QutQxg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-kotlin": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-kotlin/-/dict-kotlin-1.1.1.tgz", + "integrity": "sha512-J3NzzfgmxRvEeOe3qUXnSJQCd38i/dpF9/t3quuWh6gXM+krsAXP75dY1CzDmS8mrJAlBdVBeAW5eAZTD8g86Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-latex": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@cspell/dict-latex/-/dict-latex-4.0.4.tgz", + "integrity": "sha512-YdTQhnTINEEm/LZgTzr9Voz4mzdOXH7YX+bSFs3hnkUHCUUtX/mhKgf1CFvZ0YNM2afjhQcmLaR9bDQVyYBvpA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-lorem-ipsum": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@cspell/dict-lorem-ipsum/-/dict-lorem-ipsum-4.0.5.tgz", + "integrity": "sha512-9a4TJYRcPWPBKkQAJ/whCu4uCAEgv/O2xAaZEI0n4y1/l18Yyx8pBKoIX5QuVXjjmKEkK7hi5SxyIsH7pFEK9Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-lua": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/@cspell/dict-lua/-/dict-lua-4.0.8.tgz", + "integrity": "sha512-N4PkgNDMu9JVsRu7JBS/3E/dvfItRgk9w5ga2dKq+JupP2Y3lojNaAVFhXISh4Y0a6qXDn2clA6nvnavQ/jjLA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-makefile": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@cspell/dict-makefile/-/dict-makefile-1.0.5.tgz", + "integrity": "sha512-4vrVt7bGiK8Rx98tfRbYo42Xo2IstJkAF4tLLDMNQLkQ86msDlYSKG1ZCk8Abg+EdNcFAjNhXIiNO+w4KflGAQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-markdown": { + "version": "2.0.12", + "resolved": "https://registry.npmjs.org/@cspell/dict-markdown/-/dict-markdown-2.0.12.tgz", + "integrity": "sha512-ufwoliPijAgWkD/ivAMC+A9QD895xKiJRF/fwwknQb7kt7NozTLKFAOBtXGPJAB4UjhGBpYEJVo2elQ0FCAH9A==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@cspell/dict-css": "^4.0.18", + "@cspell/dict-html": "^4.0.12", + "@cspell/dict-html-symbol-entities": "^4.0.4", + "@cspell/dict-typescript": "^3.2.3" + } + }, + "node_modules/@cspell/dict-monkeyc": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@cspell/dict-monkeyc/-/dict-monkeyc-1.0.11.tgz", + "integrity": "sha512-7Q1Ncu0urALI6dPTrEbSTd//UK0qjRBeaxhnm8uY5fgYNFYAG+u4gtnTIo59S6Bw5P++4H3DiIDYoQdY/lha8w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-node": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/@cspell/dict-node/-/dict-node-5.0.8.tgz", + "integrity": "sha512-AirZcN2i84ynev3p2/1NCPEhnNsHKMz9zciTngGoqpdItUb2bDt1nJBjwlsrFI78GZRph/VaqTVFwYikmncpXg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-npm": { + "version": "5.2.23", + "resolved": "https://registry.npmjs.org/@cspell/dict-npm/-/dict-npm-5.2.23.tgz", + "integrity": "sha512-cnlPGzhNkbXFLFURfjzwML2LjHMofqJkemR7lLo9Jwa9IptvzeTn4nOtJMSGfkxNrZPf/IvQ7rH5hamsUQLQ3A==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-php": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@cspell/dict-php/-/dict-php-4.1.0.tgz", + "integrity": "sha512-dTDeabyOj7eFvn2Q4Za3uVXM2+SzeFMqX8ly2P0XTo4AzbCmI2hulFD/QIADwWmwiRrInbbf8cxwFHNIYrXl4w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-powershell": { + "version": "5.0.15", + "resolved": "https://registry.npmjs.org/@cspell/dict-powershell/-/dict-powershell-5.0.15.tgz", + "integrity": "sha512-l4S5PAcvCFcVDMJShrYD0X6Huv9dcsQPlsVsBGbH38wvuN7gS7+GxZFAjTNxDmTY1wrNi1cCatSg6Pu2BW4rgg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-public-licenses": { + "version": "2.0.15", + "resolved": "https://registry.npmjs.org/@cspell/dict-public-licenses/-/dict-public-licenses-2.0.15.tgz", + "integrity": "sha512-cJEOs901H13Pfy0fl4dCD1U+xpWIMaEPq8MeYU83FfDZvellAuSo4GqWCripfIqlhns/L6+UZEIJSOZnjgy7Wg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-python": { + "version": "4.2.22", + "resolved": "https://registry.npmjs.org/@cspell/dict-python/-/dict-python-4.2.22.tgz", + "integrity": "sha512-rgF7DuleVK2lkzlw33jjEfxS2a0CU5kwAhOqf5B6XkuaPbqZ/0g0LBCdwglAGccYu7sBuvxRS8Yubk+ytSAFTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/dict-data-science": "^2.0.12" + } + }, + "node_modules/@cspell/dict-r": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-r/-/dict-r-2.1.1.tgz", + "integrity": "sha512-71Ka+yKfG4ZHEMEmDxc6+blFkeTTvgKbKAbwiwQAuKl3zpqs1Y0vUtwW2N4b3LgmSPhV3ODVY0y4m5ofqDuKMw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-ruby": { + "version": "5.0.9", + "resolved": "https://registry.npmjs.org/@cspell/dict-ruby/-/dict-ruby-5.0.9.tgz", + "integrity": "sha512-H2vMcERMcANvQshAdrVx0XoWaNX8zmmiQN11dZZTQAZaNJ0xatdJoSqY8C8uhEMW89bfgpN+NQgGuDXW2vmXEw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-rust": { + "version": "4.0.12", + "resolved": "https://registry.npmjs.org/@cspell/dict-rust/-/dict-rust-4.0.12.tgz", + "integrity": "sha512-z2QiH+q9UlNhobBJArvILRxV8Jz0pKIK7gqu4TgmEYyjiu1TvnGZ1tbYHeu9w3I/wOP6UMDoCBTty5AlYfW0mw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-scala": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/@cspell/dict-scala/-/dict-scala-5.0.8.tgz", + "integrity": "sha512-YdftVmumv8IZq9zu1gn2U7A4bfM2yj9Vaupydotyjuc+EEZZSqAafTpvW/jKLWji2TgybM1L2IhmV0s/Iv9BTw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-shell": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@cspell/dict-shell/-/dict-shell-1.1.2.tgz", + "integrity": "sha512-WqOUvnwcHK1X61wAfwyXq04cn7KYyskg90j4lLg3sGGKMW9Sq13hs91pqrjC44Q+lQLgCobrTkMDw9Wyl9nRFA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-software-terms": { + "version": "5.1.14", + "resolved": "https://registry.npmjs.org/@cspell/dict-software-terms/-/dict-software-terms-5.1.14.tgz", + "integrity": "sha512-Eu9h090hxHJiqzVFS0WxOZbYXnmb7F1RFIUEg4Nru+D/78bXVDH4b8BiKGVFNRljaieNQRAHaryzdaKJRCH6ZA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-sql": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@cspell/dict-sql/-/dict-sql-2.2.1.tgz", + "integrity": "sha512-qDHF8MpAYCf4pWU8NKbnVGzkoxMNrFqBHyG/dgrlic5EQiKANCLELYtGlX5auIMDLmTf1inA0eNtv74tyRJ/vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-svelte": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/@cspell/dict-svelte/-/dict-svelte-1.0.7.tgz", + "integrity": "sha512-hGZsGqP0WdzKkdpeVLBivRuSNzOTvN036EBmpOwxH+FTY2DuUH7ecW+cSaMwOgmq5JFSdTcbTNFlNC8HN8lhaQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-swift": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/@cspell/dict-swift/-/dict-swift-2.0.6.tgz", + "integrity": "sha512-PnpNbrIbex2aqU1kMgwEKvCzgbkHtj3dlFLPMqW1vSniop7YxaDTtvTUO4zA++ugYAEL+UK8vYrBwDPTjjvSnA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-terraform": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@cspell/dict-terraform/-/dict-terraform-1.1.3.tgz", + "integrity": "sha512-gr6wxCydwSFyyBKhBA2xkENXtVFToheqYYGFvlMZXWjviynXmh+NK/JTvTCk/VHk3+lzbO9EEQKee6VjrAUSbA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-typescript": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/@cspell/dict-typescript/-/dict-typescript-3.2.3.tgz", + "integrity": "sha512-zXh1wYsNljQZfWWdSPYwQhpwiuW0KPW1dSd8idjMRvSD0aSvWWHoWlrMsmZeRl4qM4QCEAjua8+cjflm41cQBg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-vue": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@cspell/dict-vue/-/dict-vue-3.0.5.tgz", + "integrity": "sha512-Mqutb8jbM+kIcywuPQCCaK5qQHTdaByoEO2J9LKFy3sqAdiBogNkrplqUK0HyyRFgCfbJUgjz3N85iCMcWH0JA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dict-zig": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@cspell/dict-zig/-/dict-zig-1.0.0.tgz", + "integrity": "sha512-XibBIxBlVosU06+M6uHWkFeT0/pW5WajDRYdXG2CgHnq85b0TI/Ks0FuBJykmsgi2CAD3Qtx8UHFEtl/DSFnAQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cspell/dynamic-import": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/dynamic-import/-/dynamic-import-9.3.2.tgz", + "integrity": "sha512-au7FyuIHUNI2r9sO3pUBKVTeD/v7c9x/nPUStaAK1bG4rdKt4w+/jUY2IaldAraW5w29z528BboXbiV87SM1kw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/url": "9.3.2", + "import-meta-resolve": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/filetypes": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/filetypes/-/filetypes-9.3.2.tgz", + "integrity": "sha512-0bUxQlmJPRHZrRQD7adbc4lFizO8tGD/6+1cBgU3kV3+NVrpr12y4jU8twCSChhYibZyPr7bnvhkM3cQgb8RzA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/strong-weak-map": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/strong-weak-map/-/strong-weak-map-9.3.2.tgz", + "integrity": "sha512-pFcmOTWCoFMRETb9PCkCmaiZiLb5i2qOZmGH/p/tFEH8kIYhMGfhaulnXwKwS+Ke6PKceQd2YL98bGmo8hL4aQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/@cspell/url": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@cspell/url/-/url-9.3.2.tgz", + "integrity": "sha512-TobUlZl7Z7VehhNOMNAg1ABuGizieseftlG94OZJ934JptOhK8TC/1o2ldKrbDH50jyt6E7rPTMV2BW/vWuTzQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/@docsearch/css": { + "version": "3.8.2", + "resolved": "https://registry.npmjs.org/@docsearch/css/-/css-3.8.2.tgz", + "integrity": "sha512-y05ayQFyUmCXze79+56v/4HpycYF3uFqB78pLPrSV5ZKAlDuIAAJNhaRi8tTdRNXh05yxX/TyNnzD6LwSM89vQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@docsearch/js": { + "version": "3.8.2", + "resolved": "https://registry.npmjs.org/@docsearch/js/-/js-3.8.2.tgz", + "integrity": "sha512-Q5wY66qHn0SwA7Taa0aDbHiJvaFJLOJyHmooQ7y8hlwwQLQ/5WwCcoX0g7ii04Qi2DJlHsd0XXzJ8Ypw9+9YmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@docsearch/react": "3.8.2", + "preact": "^10.0.0" + } + }, + "node_modules/@docsearch/react": { + "version": "3.8.2", + "resolved": "https://registry.npmjs.org/@docsearch/react/-/react-3.8.2.tgz", + "integrity": "sha512-xCRrJQlTt8N9GU0DG4ptwHRkfnSnD/YpdeaXe02iKfqs97TkZJv60yE+1eq/tjPcVnTW8dP5qLP7itifFVV5eg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/autocomplete-core": "1.17.7", + "@algolia/autocomplete-preset-algolia": "1.17.7", + "@docsearch/css": "3.8.2", + "algoliasearch": "^5.14.2" + }, + "peerDependencies": { + "@types/react": ">= 16.8.0 < 19.0.0", + "react": ">= 16.8.0 < 19.0.0", + "react-dom": ">= 16.8.0 < 19.0.0", + "search-insights": ">= 1 < 3" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + }, + "search-insights": { + "optional": true + } + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", + "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@iconify-json/simple-icons": { + "version": "1.2.59", + "resolved": "https://registry.npmjs.org/@iconify-json/simple-icons/-/simple-icons-1.2.59.tgz", + "integrity": "sha512-fYx/InyQsWFW4wVxWka3CGDJ6m/fXoTqWBSl+oA3FBXO5RhPAb6S3Y5bRgCPnrYevErH8VjAL0TZevIqlN2PhQ==", + "dev": true, + "license": "CC0-1.0", + "dependencies": { + "@iconify/types": "*" + } + }, + "node_modules/@iconify/types": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@iconify/types/-/types-2.0.0.tgz", + "integrity": "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.53.3.tgz", + "integrity": "sha512-3EhFi1FU6YL8HTUJZ51imGJWEX//ajQPfqWLI3BQq4TlvHy4X0MOr5q3D2Zof/ka0d5FNdPwZXm3Yyib/UEd+w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.53.3.tgz", + "integrity": "sha512-eoROhjcc6HbZCJr+tvVT8X4fW3/5g/WkGvvmwz/88sDtSJzO7r/blvoBDgISDiCjDRZmHpwud7h+6Q9JxFwq1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@shikijs/core": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-2.5.0.tgz", + "integrity": "sha512-uu/8RExTKtavlpH7XqnVYBrfBkUc20ngXiX9NSrBhOVZYv/7XQRKUyhtkeflY5QsxC0GbJThCerruZfsUaSldg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/engine-javascript": "2.5.0", + "@shikijs/engine-oniguruma": "2.5.0", + "@shikijs/types": "2.5.0", + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4", + "hast-util-to-html": "^9.0.4" + } + }, + "node_modules/@shikijs/engine-javascript": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-2.5.0.tgz", + "integrity": "sha512-VjnOpnQf8WuCEZtNUdjjwGUbtAVKuZkVQ/5cHy/tojVVRIRtlWMYVjyWhxOmIq05AlSOv72z7hRNRGVBgQOl0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "2.5.0", + "@shikijs/vscode-textmate": "^10.0.2", + "oniguruma-to-es": "^3.1.0" + } + }, + "node_modules/@shikijs/engine-oniguruma": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-2.5.0.tgz", + "integrity": "sha512-pGd1wRATzbo/uatrCIILlAdFVKdxImWJGQ5rFiB5VZi2ve5xj3Ax9jny8QvkaV93btQEwR/rSz5ERFpC5mKNIw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "2.5.0", + "@shikijs/vscode-textmate": "^10.0.2" + } + }, + "node_modules/@shikijs/langs": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-2.5.0.tgz", + "integrity": "sha512-Qfrrt5OsNH5R+5tJ/3uYBBZv3SuGmnRPejV9IlIbFH3HTGLDlkqgHymAlzklVmKBjAaVmkPkyikAV/sQ1wSL+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "2.5.0" + } + }, + "node_modules/@shikijs/themes": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-2.5.0.tgz", + "integrity": "sha512-wGrk+R8tJnO0VMzmUExHR+QdSaPUl/NKs+a4cQQRWyoc3YFbUzuLEi/KWK1hj+8BfHRKm2jNhhJck1dfstJpiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "2.5.0" + } + }, + "node_modules/@shikijs/transformers": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@shikijs/transformers/-/transformers-2.5.0.tgz", + "integrity": "sha512-SI494W5X60CaUwgi8u4q4m4s3YAFSxln3tzNjOSYqq54wlVgz0/NbbXEb3mdLbqMBztcmS7bVTaEd2w0qMmfeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/core": "2.5.0", + "@shikijs/types": "2.5.0" + } + }, + "node_modules/@shikijs/types": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-2.5.0.tgz", + "integrity": "sha512-ygl5yhxki9ZLNuNpPitBWvcy9fsSKKaRuO4BAlMyagszQidxcpLAr0qiW/q43DtSIDxO6hEbtYLiFZNXO/hdGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4" + } + }, + "node_modules/@shikijs/vscode-textmate": { + "version": "10.0.2", + "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz", + "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/hast": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", + "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/linkify-it": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz", + "integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/markdown-it": { + "version": "14.1.2", + "resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-14.1.2.tgz", + "integrity": "sha512-promo4eFwuiW+TfGxhi+0x3czqTYJkG8qB17ZUJiVF10Xm7NLVRSLUsfRTU/6h1e24VvRnXCx+hG7li58lkzog==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/linkify-it": "^5", + "@types/mdurl": "^2" + } + }, + "node_modules/@types/mdast": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", + "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/mdurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-2.0.0.tgz", + "integrity": "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/web-bluetooth": { + "version": "0.0.21", + "resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz", + "integrity": "sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@ungap/structured-clone": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz", + "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==", + "dev": true, + "license": "ISC" + }, + "node_modules/@vitejs/plugin-vue": { + "version": "5.2.4", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-5.2.4.tgz", + "integrity": "sha512-7Yx/SXSOcQq5HiiV3orevHUFn+pmMB4cgbEkDYgnkUWb0WfeQ/wa2yFv6D5ICiCQOVpjA7vYDXrC7AGO8yjDHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "peerDependencies": { + "vite": "^5.0.0 || ^6.0.0", + "vue": "^3.2.25" + } + }, + "node_modules/@vue/compiler-core": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.24.tgz", + "integrity": "sha512-eDl5H57AOpNakGNAkFDH+y7kTqrQpJkZFXhWZQGyx/5Wh7B1uQYvcWkvZi11BDhscPgj8N7XV3oRwiPnx1Vrig==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.28.5", + "@vue/shared": "3.5.24", + "entities": "^4.5.0", + "estree-walker": "^2.0.2", + "source-map-js": "^1.2.1" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.24.tgz", + "integrity": "sha512-1QHGAvs53gXkWdd3ZMGYuvQFXHW4ksKWPG8HP8/2BscrbZ0brw183q2oNWjMrSWImYLHxHrx1ItBQr50I/q2zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/compiler-core": "3.5.24", + "@vue/shared": "3.5.24" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.24.tgz", + "integrity": "sha512-8EG5YPRgmTB+YxYBM3VXy8zHD9SWHUJLIGPhDovo3Z8VOgvP+O7UP5vl0J4BBPWYD9vxtBabzW1EuEZ+Cqs14g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.28.5", + "@vue/compiler-core": "3.5.24", + "@vue/compiler-dom": "3.5.24", + "@vue/compiler-ssr": "3.5.24", + "@vue/shared": "3.5.24", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.21", + "postcss": "^8.5.6", + "source-map-js": "^1.2.1" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.24.tgz", + "integrity": "sha512-trOvMWNBMQ/odMRHW7Ae1CdfYx+7MuiQu62Jtu36gMLXcaoqKvAyh+P73sYG9ll+6jLB6QPovqoKGGZROzkFFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.24", + "@vue/shared": "3.5.24" + } + }, + "node_modules/@vue/devtools-api": { + "version": "7.7.9", + "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-7.7.9.tgz", + "integrity": "sha512-kIE8wvwlcZ6TJTbNeU2HQNtaxLx3a84aotTITUuL/4bzfPxzajGBOoqjMhwZJ8L9qFYDU/lAYMEEm11dnZOD6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/devtools-kit": "^7.7.9" + } + }, + "node_modules/@vue/devtools-kit": { + "version": "7.7.9", + "resolved": "https://registry.npmjs.org/@vue/devtools-kit/-/devtools-kit-7.7.9.tgz", + "integrity": "sha512-PyQ6odHSgiDVd4hnTP+aDk2X4gl2HmLDfiyEnn3/oV+ckFDuswRs4IbBT7vacMuGdwY/XemxBoh302ctbsptuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/devtools-shared": "^7.7.9", + "birpc": "^2.3.0", + "hookable": "^5.5.3", + "mitt": "^3.0.1", + "perfect-debounce": "^1.0.0", + "speakingurl": "^14.0.1", + "superjson": "^2.2.2" + } + }, + "node_modules/@vue/devtools-shared": { + "version": "7.7.9", + "resolved": "https://registry.npmjs.org/@vue/devtools-shared/-/devtools-shared-7.7.9.tgz", + "integrity": "sha512-iWAb0v2WYf0QWmxCGy0seZNDPdO3Sp5+u78ORnyeonS6MT4PC7VPrryX2BpMJrwlDeaZ6BD4vP4XKjK0SZqaeA==", + "dev": true, + "license": "MIT", + "dependencies": { + "rfdc": "^1.4.1" + } + }, + "node_modules/@vue/reactivity": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.24.tgz", + "integrity": "sha512-BM8kBhtlkkbnyl4q+HiF5R5BL0ycDPfihowulm02q3WYp2vxgPcJuZO866qa/0u3idbMntKEtVNuAUp5bw4teg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/shared": "3.5.24" + } + }, + "node_modules/@vue/runtime-core": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.24.tgz", + "integrity": "sha512-RYP/byyKDgNIqfX/gNb2PB55dJmM97jc9wyF3jK7QUInYKypK2exmZMNwnjueWwGceEkP6NChd3D2ZVEp9undQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.24", + "@vue/shared": "3.5.24" + } + }, + "node_modules/@vue/runtime-dom": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.24.tgz", + "integrity": "sha512-Z8ANhr/i0XIluonHVjbUkjvn+CyrxbXRIxR7wn7+X7xlcb7dJsfITZbkVOeJZdP8VZwfrWRsWdShH6pngMxRjw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.24", + "@vue/runtime-core": "3.5.24", + "@vue/shared": "3.5.24", + "csstype": "^3.1.3" + } + }, + "node_modules/@vue/server-renderer": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.24.tgz", + "integrity": "sha512-Yh2j2Y4G/0/4z/xJ1Bad4mxaAk++C2v4kaa8oSYTMJBJ00/ndPuxCnWeot0/7/qafQFLh5pr6xeV6SdMcE/G1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/compiler-ssr": "3.5.24", + "@vue/shared": "3.5.24" + }, + "peerDependencies": { + "vue": "3.5.24" + } + }, + "node_modules/@vue/shared": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.24.tgz", + "integrity": "sha512-9cwHL2EsJBdi8NY22pngYYWzkTDhld6fAD6jlaeloNGciNSJL6bLpbxVgXl96X00Jtc6YWQv96YA/0sxex/k1A==", + "dev": true, + "license": "MIT" + }, + "node_modules/@vueuse/core": { + "version": "12.8.2", + "resolved": "https://registry.npmjs.org/@vueuse/core/-/core-12.8.2.tgz", + "integrity": "sha512-HbvCmZdzAu3VGi/pWYm5Ut+Kd9mn1ZHnn4L5G8kOQTPs/IwIAmJoBrmYk2ckLArgMXZj0AW3n5CAejLUO+PhdQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/web-bluetooth": "^0.0.21", + "@vueuse/metadata": "12.8.2", + "@vueuse/shared": "12.8.2", + "vue": "^3.5.13" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@vueuse/integrations": { + "version": "12.8.2", + "resolved": "https://registry.npmjs.org/@vueuse/integrations/-/integrations-12.8.2.tgz", + "integrity": "sha512-fbGYivgK5uBTRt7p5F3zy6VrETlV9RtZjBqd1/HxGdjdckBgBM4ugP8LHpjolqTj14TXTxSK1ZfgPbHYyGuH7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vueuse/core": "12.8.2", + "@vueuse/shared": "12.8.2", + "vue": "^3.5.13" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "async-validator": "^4", + "axios": "^1", + "change-case": "^5", + "drauu": "^0.4", + "focus-trap": "^7", + "fuse.js": "^7", + "idb-keyval": "^6", + "jwt-decode": "^4", + "nprogress": "^0.2", + "qrcode": "^1.5", + "sortablejs": "^1", + "universal-cookie": "^7" + }, + "peerDependenciesMeta": { + "async-validator": { + "optional": true + }, + "axios": { + "optional": true + }, + "change-case": { + "optional": true + }, + "drauu": { + "optional": true + }, + "focus-trap": { + "optional": true + }, + "fuse.js": { + "optional": true + }, + "idb-keyval": { + "optional": true + }, + "jwt-decode": { + "optional": true + }, + "nprogress": { + "optional": true + }, + "qrcode": { + "optional": true + }, + "sortablejs": { + "optional": true + }, + "universal-cookie": { + "optional": true + } + } + }, + "node_modules/@vueuse/metadata": { + "version": "12.8.2", + "resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-12.8.2.tgz", + "integrity": "sha512-rAyLGEuoBJ/Il5AmFHiziCPdQzRt88VxR+Y/A/QhJ1EWtWqPBBAxTAFaSkviwEuOEZNtW8pvkPgoCZQ+HxqW1A==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@vueuse/shared": { + "version": "12.8.2", + "resolved": "https://registry.npmjs.org/@vueuse/shared/-/shared-12.8.2.tgz", + "integrity": "sha512-dznP38YzxZoNloI0qpEfpkms8knDtaoQ6Y/sfS0L7Yki4zh40LFHEhur0odJC6xTHG5dxWVPiUWBXn+wCG2s5w==", + "dev": true, + "license": "MIT", + "dependencies": { + "vue": "^3.5.13" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/algoliasearch": { + "version": "5.44.0", + "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-5.44.0.tgz", + "integrity": "sha512-f8IpsbdQjzTjr/4mJ/jv5UplrtyMnnciGax6/B0OnLCs2/GJTK13O4Y7Ff1AvJVAaztanH+m5nzPoUq6EAy+aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@algolia/abtesting": "1.10.0", + "@algolia/client-abtesting": "5.44.0", + "@algolia/client-analytics": "5.44.0", + "@algolia/client-common": "5.44.0", + "@algolia/client-insights": "5.44.0", + "@algolia/client-personalization": "5.44.0", + "@algolia/client-query-suggestions": "5.44.0", + "@algolia/client-search": "5.44.0", + "@algolia/ingestion": "1.44.0", + "@algolia/monitoring": "1.44.0", + "@algolia/recommend": "5.44.0", + "@algolia/requester-browser-xhr": "5.44.0", + "@algolia/requester-fetch": "5.44.0", + "@algolia/requester-node-http": "5.44.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/array-timsort": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/array-timsort/-/array-timsort-1.0.3.tgz", + "integrity": "sha512-/+3GRL7dDAGEfM6TseQk/U+mi18TU2Ms9I3UlLdUMhz2hbvGNTKdj9xniwXfUqgYhHxRx0+8UnKkvlNwVU+cWQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/birpc": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/birpc/-/birpc-2.8.0.tgz", + "integrity": "sha512-Bz2a4qD/5GRhiHSwj30c/8kC8QGj12nNDwz3D4ErQ4Xhy35dsSDvF+RA/tWpjyU0pdGtSDiEk6B5fBGE1qNVhw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/ccount": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", + "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk-template": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/chalk-template/-/chalk-template-1.1.2.tgz", + "integrity": "sha512-2bxTP2yUH7AJj/VAXfcA+4IcWGdQ87HwBANLt5XxGTeomo8yG0y95N1um9i5StvhT/Bl0/2cARA5v1PpPXUxUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^5.2.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/chalk/chalk-template?sponsor=1" + } + }, + "node_modules/character-entities-html4": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", + "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-legacy": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", + "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/clear-module": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/clear-module/-/clear-module-4.1.2.tgz", + "integrity": "sha512-LWAxzHqdHsAZlPlEyJ2Poz6AIs384mPeqLVCru2p0BrP9G/kVGuhNyZYClLO6cXlnuJjzC8xtsJIuMjKqLXoAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^2.0.0", + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/comma-separated-tokens": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", + "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/commander": { + "version": "14.0.2", + "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.2.tgz", + "integrity": "sha512-TywoWNNRbhoD0BXs1P3ZEScW8W5iKrnbithIl0YH+uCmBd0QpPOA8yc82DS3BIE5Ma6FnBVUsJ7wVUDz4dvOWQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/comment-json": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/comment-json/-/comment-json-4.4.1.tgz", + "integrity": "sha512-r1To31BQD5060QdkC+Iheai7gHwoSZobzunqkf2/kQ6xIAfJyrKNAFUwdKvkK7Qgu7pVTKQEa7ok7Ed3ycAJgg==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-timsort": "^1.0.3", + "core-util-is": "^1.0.3", + "esprima": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/copy-anything": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-4.0.5.tgz", + "integrity": "sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-what": "^5.2.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/mesqueeb" + } + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/cspell": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell/-/cspell-9.3.2.tgz", + "integrity": "sha512-3xFyVSTYrYa/QJzLfzsCRMkMXqOsytP8E26DuGrVMJQoLPFmbOXNNtnMu4wrtr17QVloxpvutW77U4vb2L/LDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/cspell-json-reporter": "9.3.2", + "@cspell/cspell-pipe": "9.3.2", + "@cspell/cspell-types": "9.3.2", + "@cspell/dynamic-import": "9.3.2", + "@cspell/url": "9.3.2", + "chalk": "^5.6.2", + "chalk-template": "^1.1.2", + "commander": "^14.0.2", + "cspell-config-lib": "9.3.2", + "cspell-dictionary": "9.3.2", + "cspell-gitignore": "9.3.2", + "cspell-glob": "9.3.2", + "cspell-io": "9.3.2", + "cspell-lib": "9.3.2", + "fast-json-stable-stringify": "^2.1.0", + "flatted": "^3.3.3", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15" + }, + "bin": { + "cspell": "bin.mjs", + "cspell-esm": "bin.mjs" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/streetsidesoftware/cspell?sponsor=1" + } + }, + "node_modules/cspell-config-lib": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell-config-lib/-/cspell-config-lib-9.3.2.tgz", + "integrity": "sha512-zXhmA4rqgWQRTVijI+g/mgiep76TvTO4d+P3CHwcqLG57BKVzoW+jkO4qDLC+Neh4b8+CcNWEIr3w16BfuEJAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/cspell-types": "9.3.2", + "comment-json": "^4.4.1", + "smol-toml": "^1.5.2", + "yaml": "^2.8.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cspell-dictionary": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell-dictionary/-/cspell-dictionary-9.3.2.tgz", + "integrity": "sha512-E3YhOhZzZt1a+AEbFV2B3THCyZ576PDg0mDNUDrU1Y65SyIhf4DC6itfPoAb6R3FI/DI218RqWZg/FTT8lJ2gA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/cspell-pipe": "9.3.2", + "@cspell/cspell-types": "9.3.2", + "cspell-trie-lib": "9.3.2", + "fast-equals": "^5.3.3" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cspell-gitignore": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell-gitignore/-/cspell-gitignore-9.3.2.tgz", + "integrity": "sha512-G2bLR+Dfb9GX4Sdm75GfCCa9V/sQYkRbLckuCuVmJxvcDB0xfczAtb6TfAXIziF3oUI6cOB1g+PoNLWBelcK5w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/url": "9.3.2", + "cspell-glob": "9.3.2", + "cspell-io": "9.3.2" + }, + "bin": { + "cspell-gitignore": "bin.mjs" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cspell-glob": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell-glob/-/cspell-glob-9.3.2.tgz", + "integrity": "sha512-TuSupENEKyOCupOUZ3vnPxaTOghxY/rD1JIkb8e5kjzRprYVilO/rYqEk/52iLwJVd+4Npe8fNhR3KhU7u/UUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/url": "9.3.2", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cspell-grammar": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell-grammar/-/cspell-grammar-9.3.2.tgz", + "integrity": "sha512-ysonrFu9vJvF/derDlEjUfmvLeCfNOWPh00t6Yh093AKrJFoWQiyaS/5bEN/uB5/n1sa4k3ItnWvuTp3+YuZsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/cspell-pipe": "9.3.2", + "@cspell/cspell-types": "9.3.2" + }, + "bin": { + "cspell-grammar": "bin.mjs" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cspell-io": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell-io/-/cspell-io-9.3.2.tgz", + "integrity": "sha512-ahoULCp0j12TyXXmIcdO/7x65A/2mzUQO1IkOC65OXEbNT+evt0yswSO5Nr1F6kCHDuEKc46EZWwsYAzj78pMg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/cspell-service-bus": "9.3.2", + "@cspell/url": "9.3.2" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cspell-lib": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell-lib/-/cspell-lib-9.3.2.tgz", + "integrity": "sha512-kdk11kib68zNANNICuOA8h4oA9kENQUAdeX/uvT4+7eHbHHV8WSgjXm4k4o/pRIbg164UJTX/XxKb/65ftn5jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/cspell-bundled-dicts": "9.3.2", + "@cspell/cspell-pipe": "9.3.2", + "@cspell/cspell-resolver": "9.3.2", + "@cspell/cspell-types": "9.3.2", + "@cspell/dynamic-import": "9.3.2", + "@cspell/filetypes": "9.3.2", + "@cspell/strong-weak-map": "9.3.2", + "@cspell/url": "9.3.2", + "clear-module": "^4.1.2", + "cspell-config-lib": "9.3.2", + "cspell-dictionary": "9.3.2", + "cspell-glob": "9.3.2", + "cspell-grammar": "9.3.2", + "cspell-io": "9.3.2", + "cspell-trie-lib": "9.3.2", + "env-paths": "^3.0.0", + "gensequence": "^8.0.8", + "import-fresh": "^3.3.1", + "resolve-from": "^5.0.0", + "vscode-languageserver-textdocument": "^1.0.12", + "vscode-uri": "^3.1.0", + "xdg-basedir": "^5.1.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cspell-trie-lib": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/cspell-trie-lib/-/cspell-trie-lib-9.3.2.tgz", + "integrity": "sha512-1Af7Mq9jIccFQyJl/ZCcqQbtJwuDqpQVkk8xfs/92x4OI6gW1iTVRMtsrh0RTw1HZoR8aQD7tRRCiLPf/D+UiQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspell/cspell-pipe": "9.3.2", + "@cspell/cspell-types": "9.3.2", + "gensequence": "^8.0.8" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/devlop": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", + "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", + "dev": true, + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/emoji-regex-xs": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex-xs/-/emoji-regex-xs-1.0.0.tgz", + "integrity": "sha512-LRlerrMYoIDrT6jgpeZ2YYl/L8EulRTt5hQcYjy5AInh7HWXKimpqx68aknBFpGL2+/IcogTcaydJEgaTmOpDg==", + "dev": true, + "license": "MIT" + }, + "node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/env-paths": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz", + "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/esbuild": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", + "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true, + "license": "BSD-2-Clause", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-equals": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.3.3.tgz", + "integrity": "sha512-/boTcHZeIAQ2r/tL11voclBHDeP9WPxLt+tyAbVSyyXuUFyh0Tne7gJZTqGbxnvj79TjLdCXLOY7UIPhyG5MTw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/flatted": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz", + "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==", + "dev": true, + "license": "ISC" + }, + "node_modules/focus-trap": { + "version": "7.6.6", + "resolved": "https://registry.npmjs.org/focus-trap/-/focus-trap-7.6.6.tgz", + "integrity": "sha512-v/Z8bvMCajtx4mEXmOo7QEsIzlIOqRXTIwgUfsFOF9gEsespdbD0AkPIka1bSXZ8Y8oZ+2IVDQZePkTfEHZl7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "tabbable": "^6.3.0" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensequence": { + "version": "8.0.8", + "resolved": "https://registry.npmjs.org/gensequence/-/gensequence-8.0.8.tgz", + "integrity": "sha512-omMVniXEXpdx/vKxGnPRoO2394Otlze28TyxECbFVyoSpZ9H3EO7lemjcB12OpQJzRW4e5tt/dL1rOxry6aMHg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/global-directory": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/global-directory/-/global-directory-4.0.1.tgz", + "integrity": "sha512-wHTUcDUoZ1H5/0iVqEudYW4/kAlN5cZ3j/bXn0Dpbizl9iaUVeWSHqiOjsgk6OW2bkLclbBjzewBz6weQ1zA2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ini": "4.1.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/hast-util-to-html": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz", + "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "ccount": "^2.0.0", + "comma-separated-tokens": "^2.0.0", + "hast-util-whitespace": "^3.0.0", + "html-void-elements": "^3.0.0", + "mdast-util-to-hast": "^13.0.0", + "property-information": "^7.0.0", + "space-separated-tokens": "^2.0.0", + "stringify-entities": "^4.0.0", + "zwitch": "^2.0.4" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-whitespace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", + "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hookable": { + "version": "5.5.3", + "resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz", + "integrity": "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/html-void-elements": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz", + "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/import-fresh/node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/import-fresh/node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/import-meta-resolve": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/import-meta-resolve/-/import-meta-resolve-4.2.0.tgz", + "integrity": "sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/ini": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ini/-/ini-4.1.1.tgz", + "integrity": "sha512-QQnnxNyfvmHFIsj7gkPcYymR8Jdw/o7mp5ZFihxn6h8Ci6fh3Dx4E1gPjpQEpIuPo9XVNY/ZUwh4BPMjGyL01g==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/is-what": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/is-what/-/is-what-5.5.0.tgz", + "integrity": "sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/mesqueeb" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/mark.js": { + "version": "8.11.1", + "resolved": "https://registry.npmjs.org/mark.js/-/mark.js-8.11.1.tgz", + "integrity": "sha512-1I+1qpDt4idfgLQG+BNWmrqku+7/2bi5nLf4YwF8y8zXvmfiTBY3PV3ZibfrjBueCByROpuBjLLFCajqkgYoLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/mdast-util-to-hast": { + "version": "13.2.1", + "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz", + "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@ungap/structured-clone": "^1.0.0", + "devlop": "^1.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "trim-lines": "^3.0.0", + "unist-util-position": "^5.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-util-character": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", + "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-encode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", + "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-sanitize-uri": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", + "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-symbol": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", + "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-types": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz", + "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/minisearch": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/minisearch/-/minisearch-7.2.0.tgz", + "integrity": "sha512-dqT2XBYUOZOiC5t2HRnwADjhNS2cecp9u+TJRiJ1Qp/f5qjkeT5APcGPjHw+bz89Ms8Jp+cG4AlE+QZ/QnDglg==", + "dev": true, + "license": "MIT" + }, + "node_modules/mitt": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz", + "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/oniguruma-to-es": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-3.1.1.tgz", + "integrity": "sha512-bUH8SDvPkH3ho3dvwJwfonjlQ4R80vjyvrU8YpxuROddv55vAEJrTuCuCVUhhsHbtlD9tGGbaNApGQckXhS8iQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex-xs": "^1.0.0", + "regex": "^6.0.1", + "regex-recursion": "^6.0.2" + } + }, + "node_modules/parent-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-2.0.0.tgz", + "integrity": "sha512-uo0Z9JJeWzv8BG+tRcapBKNJ0dro9cLyczGzulS6EfeyAdeC9sbojtW6XwvYxJkEne9En+J2XEl4zyglVeIwFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/perfect-debounce": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz", + "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.6", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", + "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/preact": { + "version": "10.27.2", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.27.2.tgz", + "integrity": "sha512-5SYSgFKSyhCbk6SrXyMpqjb5+MQBgfvEKE/OC+PujcY34sOpqtr+0AZQtPYx5IA6VxynQ7rUPCtKzyovpj9Bpg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } + }, + "node_modules/prettier": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz", + "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/property-information": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz", + "integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/regex": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/regex/-/regex-6.0.1.tgz", + "integrity": "sha512-uorlqlzAKjKQZ5P+kTJr3eeJGSVroLKoHmquUj4zHWuR+hEyNqlXsSKlYYF5F4NI6nl7tWCs0apKJ0lmfsXAPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "regex-utilities": "^2.3.0" + } + }, + "node_modules/regex-recursion": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz", + "integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==", + "dev": true, + "license": "MIT", + "dependencies": { + "regex-utilities": "^2.3.0" + } + }, + "node_modules/regex-utilities": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz", + "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==", + "dev": true, + "license": "MIT" + }, + "node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/rfdc": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "dev": true, + "license": "MIT" + }, + "node_modules/rollup": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.53.3.tgz", + "integrity": "sha512-w8GmOxZfBmKknvdXU1sdM9NHcoQejwF/4mNgj2JuEEdRaHwwF12K7e9eXn1nLZ07ad+du76mkVsyeb2rKGllsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.53.3", + "@rollup/rollup-android-arm64": "4.53.3", + "@rollup/rollup-darwin-arm64": "4.53.3", + "@rollup/rollup-darwin-x64": "4.53.3", + "@rollup/rollup-freebsd-arm64": "4.53.3", + "@rollup/rollup-freebsd-x64": "4.53.3", + "@rollup/rollup-linux-arm-gnueabihf": "4.53.3", + "@rollup/rollup-linux-arm-musleabihf": "4.53.3", + "@rollup/rollup-linux-arm64-gnu": "4.53.3", + "@rollup/rollup-linux-arm64-musl": "4.53.3", + "@rollup/rollup-linux-loong64-gnu": "4.53.3", + "@rollup/rollup-linux-ppc64-gnu": "4.53.3", + "@rollup/rollup-linux-riscv64-gnu": "4.53.3", + "@rollup/rollup-linux-riscv64-musl": "4.53.3", + "@rollup/rollup-linux-s390x-gnu": "4.53.3", + "@rollup/rollup-linux-x64-gnu": "4.53.3", + "@rollup/rollup-linux-x64-musl": "4.53.3", + "@rollup/rollup-openharmony-arm64": "4.53.3", + "@rollup/rollup-win32-arm64-msvc": "4.53.3", + "@rollup/rollup-win32-ia32-msvc": "4.53.3", + "@rollup/rollup-win32-x64-gnu": "4.53.3", + "@rollup/rollup-win32-x64-msvc": "4.53.3", + "fsevents": "~2.3.2" + } + }, + "node_modules/search-insights": { + "version": "2.17.3", + "resolved": "https://registry.npmjs.org/search-insights/-/search-insights-2.17.3.tgz", + "integrity": "sha512-RQPdCYTa8A68uM2jwxoY842xDhvx3E5LFL1LxvxCNMev4o5mLuokczhzjAgGwUZBAmOKZknArSxLKmXtIi2AxQ==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shiki": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/shiki/-/shiki-2.5.0.tgz", + "integrity": "sha512-mI//trrsaiCIPsja5CNfsyNOqgAZUb6VpJA+340toL42UpzQlXpwRV9nch69X6gaUxrr9kaOOa6e3y3uAkGFxQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/core": "2.5.0", + "@shikijs/engine-javascript": "2.5.0", + "@shikijs/engine-oniguruma": "2.5.0", + "@shikijs/langs": "2.5.0", + "@shikijs/themes": "2.5.0", + "@shikijs/types": "2.5.0", + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4" + } + }, + "node_modules/smol-toml": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.5.2.tgz", + "integrity": "sha512-QlaZEqcAH3/RtNyet1IPIYPsEWAaYyXXv1Krsi+1L/QHppjX4Ifm8MQsBISz9vE8cHicIq3clogsheili5vhaQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">= 18" + }, + "funding": { + "url": "https://github.com/sponsors/cyyynthia" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/space-separated-tokens": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", + "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/speakingurl": { + "version": "14.0.1", + "resolved": "https://registry.npmjs.org/speakingurl/-/speakingurl-14.0.1.tgz", + "integrity": "sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stringify-entities": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", + "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", + "dev": true, + "license": "MIT", + "dependencies": { + "character-entities-html4": "^2.0.0", + "character-entities-legacy": "^3.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/superjson": { + "version": "2.2.5", + "resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.5.tgz", + "integrity": "sha512-zWPTX96LVsA/eVYnqOM2+ofcdPqdS1dAF1LN4TS2/MWuUpfitd9ctTa87wt4xrYnZnkLtS69xpBdSxVBP5Rm6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "copy-anything": "^4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tabbable": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.3.0.tgz", + "integrity": "sha512-EIHvdY5bPLuWForiR/AN2Bxngzpuwn1is4asboytXtpTgsArc+WmSJKVLlhdh71u7jFcryDqB2A8lQvj78MkyQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/trim-lines": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", + "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/unist-util-is": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz", + "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-position": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz", + "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-stringify-position": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", + "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.0.0.tgz", + "integrity": "sha512-MR04uvD+07cwl/yhVuVWAtw+3GOR/knlL55Nd/wAdblk27GCVt3lqpTivy/tkJcZoNPzTwS1Y+KMojlLDhoTzg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit-parents": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", + "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", + "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile-message": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz", + "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vite": { + "version": "5.4.21", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz", + "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/vitepress": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/vitepress/-/vitepress-1.6.4.tgz", + "integrity": "sha512-+2ym1/+0VVrbhNyRoFFesVvBvHAVMZMK0rw60E3X/5349M1GuVdKeazuksqopEdvkKwKGs21Q729jX81/bkBJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@docsearch/css": "3.8.2", + "@docsearch/js": "3.8.2", + "@iconify-json/simple-icons": "^1.2.21", + "@shikijs/core": "^2.1.0", + "@shikijs/transformers": "^2.1.0", + "@shikijs/types": "^2.1.0", + "@types/markdown-it": "^14.1.2", + "@vitejs/plugin-vue": "^5.2.1", + "@vue/devtools-api": "^7.7.0", + "@vue/shared": "^3.5.13", + "@vueuse/core": "^12.4.0", + "@vueuse/integrations": "^12.4.0", + "focus-trap": "^7.6.4", + "mark.js": "8.11.1", + "minisearch": "^7.1.1", + "shiki": "^2.1.0", + "vite": "^5.4.14", + "vue": "^3.5.13" + }, + "bin": { + "vitepress": "bin/vitepress.js" + }, + "peerDependencies": { + "markdown-it-mathjax3": "^4", + "postcss": "^8" + }, + "peerDependenciesMeta": { + "markdown-it-mathjax3": { + "optional": true + }, + "postcss": { + "optional": true + } + } + }, + "node_modules/vscode-languageserver-textdocument": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.12.tgz", + "integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==", + "dev": true, + "license": "MIT" + }, + "node_modules/vscode-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz", + "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/vue": { + "version": "3.5.24", + "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.24.tgz", + "integrity": "sha512-uTHDOpVQTMjcGgrqFPSb8iO2m1DUvo+WbGqoXQz8Y1CeBYQ0FXf2z1gLRaBtHjlRz7zZUBHxjVB5VTLzYkvftg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.24", + "@vue/compiler-sfc": "3.5.24", + "@vue/runtime-dom": "3.5.24", + "@vue/server-renderer": "3.5.24", + "@vue/shared": "3.5.24" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/xdg-basedir": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-5.1.0.tgz", + "integrity": "sha512-GCPAHLvrIH13+c0SuacwvRYj2SxJXQ4kaVTT5xgL3kPrz56XxkF21IGhjSE1+W0aw7gpBWRGXLCPnPby6lSpmQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yaml": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.1.tgz", + "integrity": "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + } + }, + "node_modules/zwitch": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", + "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } } } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", - "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@iconify-json/simple-icons": { - "version": "1.2.59", - "resolved": "https://registry.npmjs.org/@iconify-json/simple-icons/-/simple-icons-1.2.59.tgz", - "integrity": "sha512-fYx/InyQsWFW4wVxWka3CGDJ6m/fXoTqWBSl+oA3FBXO5RhPAb6S3Y5bRgCPnrYevErH8VjAL0TZevIqlN2PhQ==", - "dev": true, - "license": "CC0-1.0", - "dependencies": { - "@iconify/types": "*" - } - }, - "node_modules/@iconify/types": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@iconify/types/-/types-2.0.0.tgz", - "integrity": "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", - "dev": true, - "license": "MIT" - }, - "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.53.3.tgz", - "integrity": "sha512-3EhFi1FU6YL8HTUJZ51imGJWEX//ajQPfqWLI3BQq4TlvHy4X0MOr5q3D2Zof/ka0d5FNdPwZXm3Yyib/UEd+w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.53.3.tgz", - "integrity": "sha512-eoROhjcc6HbZCJr+tvVT8X4fW3/5g/WkGvvmwz/88sDtSJzO7r/blvoBDgISDiCjDRZmHpwud7h+6Q9JxFwq1Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@shikijs/core": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-2.5.0.tgz", - "integrity": "sha512-uu/8RExTKtavlpH7XqnVYBrfBkUc20ngXiX9NSrBhOVZYv/7XQRKUyhtkeflY5QsxC0GbJThCerruZfsUaSldg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/engine-javascript": "2.5.0", - "@shikijs/engine-oniguruma": "2.5.0", - "@shikijs/types": "2.5.0", - "@shikijs/vscode-textmate": "^10.0.2", - "@types/hast": "^3.0.4", - "hast-util-to-html": "^9.0.4" - } - }, - "node_modules/@shikijs/engine-javascript": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-2.5.0.tgz", - "integrity": "sha512-VjnOpnQf8WuCEZtNUdjjwGUbtAVKuZkVQ/5cHy/tojVVRIRtlWMYVjyWhxOmIq05AlSOv72z7hRNRGVBgQOl0w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/types": "2.5.0", - "@shikijs/vscode-textmate": "^10.0.2", - "oniguruma-to-es": "^3.1.0" - } - }, - "node_modules/@shikijs/engine-oniguruma": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-2.5.0.tgz", - "integrity": "sha512-pGd1wRATzbo/uatrCIILlAdFVKdxImWJGQ5rFiB5VZi2ve5xj3Ax9jny8QvkaV93btQEwR/rSz5ERFpC5mKNIw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/types": "2.5.0", - "@shikijs/vscode-textmate": "^10.0.2" - } - }, - "node_modules/@shikijs/langs": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-2.5.0.tgz", - "integrity": "sha512-Qfrrt5OsNH5R+5tJ/3uYBBZv3SuGmnRPejV9IlIbFH3HTGLDlkqgHymAlzklVmKBjAaVmkPkyikAV/sQ1wSL+w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/types": "2.5.0" - } - }, - "node_modules/@shikijs/themes": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-2.5.0.tgz", - "integrity": "sha512-wGrk+R8tJnO0VMzmUExHR+QdSaPUl/NKs+a4cQQRWyoc3YFbUzuLEi/KWK1hj+8BfHRKm2jNhhJck1dfstJpiw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/types": "2.5.0" - } - }, - "node_modules/@shikijs/transformers": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/transformers/-/transformers-2.5.0.tgz", - "integrity": "sha512-SI494W5X60CaUwgi8u4q4m4s3YAFSxln3tzNjOSYqq54wlVgz0/NbbXEb3mdLbqMBztcmS7bVTaEd2w0qMmfeg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/core": "2.5.0", - "@shikijs/types": "2.5.0" - } - }, - "node_modules/@shikijs/types": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-2.5.0.tgz", - "integrity": "sha512-ygl5yhxki9ZLNuNpPitBWvcy9fsSKKaRuO4BAlMyagszQidxcpLAr0qiW/q43DtSIDxO6hEbtYLiFZNXO/hdGw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/vscode-textmate": "^10.0.2", - "@types/hast": "^3.0.4" - } - }, - "node_modules/@shikijs/vscode-textmate": { - "version": "10.0.2", - "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz", - "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/estree": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", - "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/hast": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", - "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "*" - } - }, - "node_modules/@types/linkify-it": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz", - "integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/markdown-it": { - "version": "14.1.2", - "resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-14.1.2.tgz", - "integrity": "sha512-promo4eFwuiW+TfGxhi+0x3czqTYJkG8qB17ZUJiVF10Xm7NLVRSLUsfRTU/6h1e24VvRnXCx+hG7li58lkzog==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/linkify-it": "^5", - "@types/mdurl": "^2" - } - }, - "node_modules/@types/mdast": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", - "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "*" - } - }, - "node_modules/@types/mdurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-2.0.0.tgz", - "integrity": "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/unist": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", - "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/web-bluetooth": { - "version": "0.0.21", - "resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz", - "integrity": "sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@ungap/structured-clone": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz", - "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==", - "dev": true, - "license": "ISC" - }, - "node_modules/@vitejs/plugin-vue": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-5.2.4.tgz", - "integrity": "sha512-7Yx/SXSOcQq5HiiV3orevHUFn+pmMB4cgbEkDYgnkUWb0WfeQ/wa2yFv6D5ICiCQOVpjA7vYDXrC7AGO8yjDHA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.0.0 || >=20.0.0" - }, - "peerDependencies": { - "vite": "^5.0.0 || ^6.0.0", - "vue": "^3.2.25" - } - }, - "node_modules/@vue/compiler-core": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.24.tgz", - "integrity": "sha512-eDl5H57AOpNakGNAkFDH+y7kTqrQpJkZFXhWZQGyx/5Wh7B1uQYvcWkvZi11BDhscPgj8N7XV3oRwiPnx1Vrig==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.28.5", - "@vue/shared": "3.5.24", - "entities": "^4.5.0", - "estree-walker": "^2.0.2", - "source-map-js": "^1.2.1" - } - }, - "node_modules/@vue/compiler-dom": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.24.tgz", - "integrity": "sha512-1QHGAvs53gXkWdd3ZMGYuvQFXHW4ksKWPG8HP8/2BscrbZ0brw183q2oNWjMrSWImYLHxHrx1ItBQr50I/q2zw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/compiler-core": "3.5.24", - "@vue/shared": "3.5.24" - } - }, - "node_modules/@vue/compiler-sfc": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.24.tgz", - "integrity": "sha512-8EG5YPRgmTB+YxYBM3VXy8zHD9SWHUJLIGPhDovo3Z8VOgvP+O7UP5vl0J4BBPWYD9vxtBabzW1EuEZ+Cqs14g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.28.5", - "@vue/compiler-core": "3.5.24", - "@vue/compiler-dom": "3.5.24", - "@vue/compiler-ssr": "3.5.24", - "@vue/shared": "3.5.24", - "estree-walker": "^2.0.2", - "magic-string": "^0.30.21", - "postcss": "^8.5.6", - "source-map-js": "^1.2.1" - } - }, - "node_modules/@vue/compiler-ssr": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.24.tgz", - "integrity": "sha512-trOvMWNBMQ/odMRHW7Ae1CdfYx+7MuiQu62Jtu36gMLXcaoqKvAyh+P73sYG9ll+6jLB6QPovqoKGGZROzkFFg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/compiler-dom": "3.5.24", - "@vue/shared": "3.5.24" - } - }, - "node_modules/@vue/devtools-api": { - "version": "7.7.9", - "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-7.7.9.tgz", - "integrity": "sha512-kIE8wvwlcZ6TJTbNeU2HQNtaxLx3a84aotTITUuL/4bzfPxzajGBOoqjMhwZJ8L9qFYDU/lAYMEEm11dnZOD6g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/devtools-kit": "^7.7.9" - } - }, - "node_modules/@vue/devtools-kit": { - "version": "7.7.9", - "resolved": "https://registry.npmjs.org/@vue/devtools-kit/-/devtools-kit-7.7.9.tgz", - "integrity": "sha512-PyQ6odHSgiDVd4hnTP+aDk2X4gl2HmLDfiyEnn3/oV+ckFDuswRs4IbBT7vacMuGdwY/XemxBoh302ctbsptuA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/devtools-shared": "^7.7.9", - "birpc": "^2.3.0", - "hookable": "^5.5.3", - "mitt": "^3.0.1", - "perfect-debounce": "^1.0.0", - "speakingurl": "^14.0.1", - "superjson": "^2.2.2" - } - }, - "node_modules/@vue/devtools-shared": { - "version": "7.7.9", - "resolved": "https://registry.npmjs.org/@vue/devtools-shared/-/devtools-shared-7.7.9.tgz", - "integrity": "sha512-iWAb0v2WYf0QWmxCGy0seZNDPdO3Sp5+u78ORnyeonS6MT4PC7VPrryX2BpMJrwlDeaZ6BD4vP4XKjK0SZqaeA==", - "dev": true, - "license": "MIT", - "dependencies": { - "rfdc": "^1.4.1" - } - }, - "node_modules/@vue/reactivity": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.24.tgz", - "integrity": "sha512-BM8kBhtlkkbnyl4q+HiF5R5BL0ycDPfihowulm02q3WYp2vxgPcJuZO866qa/0u3idbMntKEtVNuAUp5bw4teg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/shared": "3.5.24" - } - }, - "node_modules/@vue/runtime-core": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.24.tgz", - "integrity": "sha512-RYP/byyKDgNIqfX/gNb2PB55dJmM97jc9wyF3jK7QUInYKypK2exmZMNwnjueWwGceEkP6NChd3D2ZVEp9undQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/reactivity": "3.5.24", - "@vue/shared": "3.5.24" - } - }, - "node_modules/@vue/runtime-dom": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.24.tgz", - "integrity": "sha512-Z8ANhr/i0XIluonHVjbUkjvn+CyrxbXRIxR7wn7+X7xlcb7dJsfITZbkVOeJZdP8VZwfrWRsWdShH6pngMxRjw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/reactivity": "3.5.24", - "@vue/runtime-core": "3.5.24", - "@vue/shared": "3.5.24", - "csstype": "^3.1.3" - } - }, - "node_modules/@vue/server-renderer": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.24.tgz", - "integrity": "sha512-Yh2j2Y4G/0/4z/xJ1Bad4mxaAk++C2v4kaa8oSYTMJBJ00/ndPuxCnWeot0/7/qafQFLh5pr6xeV6SdMcE/G1w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/compiler-ssr": "3.5.24", - "@vue/shared": "3.5.24" - }, - "peerDependencies": { - "vue": "3.5.24" - } - }, - "node_modules/@vue/shared": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.24.tgz", - "integrity": "sha512-9cwHL2EsJBdi8NY22pngYYWzkTDhld6fAD6jlaeloNGciNSJL6bLpbxVgXl96X00Jtc6YWQv96YA/0sxex/k1A==", - "dev": true, - "license": "MIT" - }, - "node_modules/@vueuse/core": { - "version": "12.8.2", - "resolved": "https://registry.npmjs.org/@vueuse/core/-/core-12.8.2.tgz", - "integrity": "sha512-HbvCmZdzAu3VGi/pWYm5Ut+Kd9mn1ZHnn4L5G8kOQTPs/IwIAmJoBrmYk2ckLArgMXZj0AW3n5CAejLUO+PhdQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/web-bluetooth": "^0.0.21", - "@vueuse/metadata": "12.8.2", - "@vueuse/shared": "12.8.2", - "vue": "^3.5.13" - }, - "funding": { - "url": "https://github.com/sponsors/antfu" - } - }, - "node_modules/@vueuse/integrations": { - "version": "12.8.2", - "resolved": "https://registry.npmjs.org/@vueuse/integrations/-/integrations-12.8.2.tgz", - "integrity": "sha512-fbGYivgK5uBTRt7p5F3zy6VrETlV9RtZjBqd1/HxGdjdckBgBM4ugP8LHpjolqTj14TXTxSK1ZfgPbHYyGuH7g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vueuse/core": "12.8.2", - "@vueuse/shared": "12.8.2", - "vue": "^3.5.13" - }, - "funding": { - "url": "https://github.com/sponsors/antfu" - }, - "peerDependencies": { - "async-validator": "^4", - "axios": "^1", - "change-case": "^5", - "drauu": "^0.4", - "focus-trap": "^7", - "fuse.js": "^7", - "idb-keyval": "^6", - "jwt-decode": "^4", - "nprogress": "^0.2", - "qrcode": "^1.5", - "sortablejs": "^1", - "universal-cookie": "^7" - }, - "peerDependenciesMeta": { - "async-validator": { - "optional": true - }, - "axios": { - "optional": true - }, - "change-case": { - "optional": true - }, - "drauu": { - "optional": true - }, - "focus-trap": { - "optional": true - }, - "fuse.js": { - "optional": true - }, - "idb-keyval": { - "optional": true - }, - "jwt-decode": { - "optional": true - }, - "nprogress": { - "optional": true - }, - "qrcode": { - "optional": true - }, - "sortablejs": { - "optional": true - }, - "universal-cookie": { - "optional": true - } - } - }, - "node_modules/@vueuse/metadata": { - "version": "12.8.2", - "resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-12.8.2.tgz", - "integrity": "sha512-rAyLGEuoBJ/Il5AmFHiziCPdQzRt88VxR+Y/A/QhJ1EWtWqPBBAxTAFaSkviwEuOEZNtW8pvkPgoCZQ+HxqW1A==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/antfu" - } - }, - "node_modules/@vueuse/shared": { - "version": "12.8.2", - "resolved": "https://registry.npmjs.org/@vueuse/shared/-/shared-12.8.2.tgz", - "integrity": "sha512-dznP38YzxZoNloI0qpEfpkms8knDtaoQ6Y/sfS0L7Yki4zh40LFHEhur0odJC6xTHG5dxWVPiUWBXn+wCG2s5w==", - "dev": true, - "license": "MIT", - "dependencies": { - "vue": "^3.5.13" - }, - "funding": { - "url": "https://github.com/sponsors/antfu" - } - }, - "node_modules/algoliasearch": { - "version": "5.44.0", - "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-5.44.0.tgz", - "integrity": "sha512-f8IpsbdQjzTjr/4mJ/jv5UplrtyMnnciGax6/B0OnLCs2/GJTK13O4Y7Ff1AvJVAaztanH+m5nzPoUq6EAy+aA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@algolia/abtesting": "1.10.0", - "@algolia/client-abtesting": "5.44.0", - "@algolia/client-analytics": "5.44.0", - "@algolia/client-common": "5.44.0", - "@algolia/client-insights": "5.44.0", - "@algolia/client-personalization": "5.44.0", - "@algolia/client-query-suggestions": "5.44.0", - "@algolia/client-search": "5.44.0", - "@algolia/ingestion": "1.44.0", - "@algolia/monitoring": "1.44.0", - "@algolia/recommend": "5.44.0", - "@algolia/requester-browser-xhr": "5.44.0", - "@algolia/requester-fetch": "5.44.0", - "@algolia/requester-node-http": "5.44.0" - }, - "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/array-timsort": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/array-timsort/-/array-timsort-1.0.3.tgz", - "integrity": "sha512-/+3GRL7dDAGEfM6TseQk/U+mi18TU2Ms9I3UlLdUMhz2hbvGNTKdj9xniwXfUqgYhHxRx0+8UnKkvlNwVU+cWQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/birpc": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/birpc/-/birpc-2.8.0.tgz", - "integrity": "sha512-Bz2a4qD/5GRhiHSwj30c/8kC8QGj12nNDwz3D4ErQ4Xhy35dsSDvF+RA/tWpjyU0pdGtSDiEk6B5fBGE1qNVhw==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/antfu" - } - }, - "node_modules/callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/ccount": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", - "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/chalk": { - "version": "5.6.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", - "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.17.0 || ^14.13 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/chalk-template": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/chalk-template/-/chalk-template-1.1.2.tgz", - "integrity": "sha512-2bxTP2yUH7AJj/VAXfcA+4IcWGdQ87HwBANLt5XxGTeomo8yG0y95N1um9i5StvhT/Bl0/2cARA5v1PpPXUxUA==", - "dev": true, - "license": "MIT", - "dependencies": { - "chalk": "^5.2.0" - }, - "engines": { - "node": ">=14.16" - }, - "funding": { - "url": "https://github.com/chalk/chalk-template?sponsor=1" - } - }, - "node_modules/character-entities-html4": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", - "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/character-entities-legacy": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", - "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/clear-module": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/clear-module/-/clear-module-4.1.2.tgz", - "integrity": "sha512-LWAxzHqdHsAZlPlEyJ2Poz6AIs384mPeqLVCru2p0BrP9G/kVGuhNyZYClLO6cXlnuJjzC8xtsJIuMjKqLXoAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "parent-module": "^2.0.0", - "resolve-from": "^5.0.0" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/comma-separated-tokens": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", - "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/commander": { - "version": "14.0.2", - "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.2.tgz", - "integrity": "sha512-TywoWNNRbhoD0BXs1P3ZEScW8W5iKrnbithIl0YH+uCmBd0QpPOA8yc82DS3BIE5Ma6FnBVUsJ7wVUDz4dvOWQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/comment-json": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/comment-json/-/comment-json-4.4.1.tgz", - "integrity": "sha512-r1To31BQD5060QdkC+Iheai7gHwoSZobzunqkf2/kQ6xIAfJyrKNAFUwdKvkK7Qgu7pVTKQEa7ok7Ed3ycAJgg==", - "dev": true, - "license": "MIT", - "dependencies": { - "array-timsort": "^1.0.3", - "core-util-is": "^1.0.3", - "esprima": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/copy-anything": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-4.0.5.tgz", - "integrity": "sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-what": "^5.2.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/mesqueeb" - } - }, - "node_modules/core-util-is": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", - "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/cspell": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell/-/cspell-9.3.2.tgz", - "integrity": "sha512-3xFyVSTYrYa/QJzLfzsCRMkMXqOsytP8E26DuGrVMJQoLPFmbOXNNtnMu4wrtr17QVloxpvutW77U4vb2L/LDQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/cspell-json-reporter": "9.3.2", - "@cspell/cspell-pipe": "9.3.2", - "@cspell/cspell-types": "9.3.2", - "@cspell/dynamic-import": "9.3.2", - "@cspell/url": "9.3.2", - "chalk": "^5.6.2", - "chalk-template": "^1.1.2", - "commander": "^14.0.2", - "cspell-config-lib": "9.3.2", - "cspell-dictionary": "9.3.2", - "cspell-gitignore": "9.3.2", - "cspell-glob": "9.3.2", - "cspell-io": "9.3.2", - "cspell-lib": "9.3.2", - "fast-json-stable-stringify": "^2.1.0", - "flatted": "^3.3.3", - "semver": "^7.7.3", - "tinyglobby": "^0.2.15" - }, - "bin": { - "cspell": "bin.mjs", - "cspell-esm": "bin.mjs" - }, - "engines": { - "node": ">=20" - }, - "funding": { - "url": "https://github.com/streetsidesoftware/cspell?sponsor=1" - } - }, - "node_modules/cspell-config-lib": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell-config-lib/-/cspell-config-lib-9.3.2.tgz", - "integrity": "sha512-zXhmA4rqgWQRTVijI+g/mgiep76TvTO4d+P3CHwcqLG57BKVzoW+jkO4qDLC+Neh4b8+CcNWEIr3w16BfuEJAA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/cspell-types": "9.3.2", - "comment-json": "^4.4.1", - "smol-toml": "^1.5.2", - "yaml": "^2.8.1" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/cspell-dictionary": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell-dictionary/-/cspell-dictionary-9.3.2.tgz", - "integrity": "sha512-E3YhOhZzZt1a+AEbFV2B3THCyZ576PDg0mDNUDrU1Y65SyIhf4DC6itfPoAb6R3FI/DI218RqWZg/FTT8lJ2gA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/cspell-pipe": "9.3.2", - "@cspell/cspell-types": "9.3.2", - "cspell-trie-lib": "9.3.2", - "fast-equals": "^5.3.3" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/cspell-gitignore": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell-gitignore/-/cspell-gitignore-9.3.2.tgz", - "integrity": "sha512-G2bLR+Dfb9GX4Sdm75GfCCa9V/sQYkRbLckuCuVmJxvcDB0xfczAtb6TfAXIziF3oUI6cOB1g+PoNLWBelcK5w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/url": "9.3.2", - "cspell-glob": "9.3.2", - "cspell-io": "9.3.2" - }, - "bin": { - "cspell-gitignore": "bin.mjs" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/cspell-glob": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell-glob/-/cspell-glob-9.3.2.tgz", - "integrity": "sha512-TuSupENEKyOCupOUZ3vnPxaTOghxY/rD1JIkb8e5kjzRprYVilO/rYqEk/52iLwJVd+4Npe8fNhR3KhU7u/UUg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/url": "9.3.2", - "picomatch": "^4.0.3" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/cspell-grammar": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell-grammar/-/cspell-grammar-9.3.2.tgz", - "integrity": "sha512-ysonrFu9vJvF/derDlEjUfmvLeCfNOWPh00t6Yh093AKrJFoWQiyaS/5bEN/uB5/n1sa4k3ItnWvuTp3+YuZsA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/cspell-pipe": "9.3.2", - "@cspell/cspell-types": "9.3.2" - }, - "bin": { - "cspell-grammar": "bin.mjs" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/cspell-io": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell-io/-/cspell-io-9.3.2.tgz", - "integrity": "sha512-ahoULCp0j12TyXXmIcdO/7x65A/2mzUQO1IkOC65OXEbNT+evt0yswSO5Nr1F6kCHDuEKc46EZWwsYAzj78pMg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/cspell-service-bus": "9.3.2", - "@cspell/url": "9.3.2" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/cspell-lib": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell-lib/-/cspell-lib-9.3.2.tgz", - "integrity": "sha512-kdk11kib68zNANNICuOA8h4oA9kENQUAdeX/uvT4+7eHbHHV8WSgjXm4k4o/pRIbg164UJTX/XxKb/65ftn5jw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/cspell-bundled-dicts": "9.3.2", - "@cspell/cspell-pipe": "9.3.2", - "@cspell/cspell-resolver": "9.3.2", - "@cspell/cspell-types": "9.3.2", - "@cspell/dynamic-import": "9.3.2", - "@cspell/filetypes": "9.3.2", - "@cspell/strong-weak-map": "9.3.2", - "@cspell/url": "9.3.2", - "clear-module": "^4.1.2", - "cspell-config-lib": "9.3.2", - "cspell-dictionary": "9.3.2", - "cspell-glob": "9.3.2", - "cspell-grammar": "9.3.2", - "cspell-io": "9.3.2", - "cspell-trie-lib": "9.3.2", - "env-paths": "^3.0.0", - "gensequence": "^8.0.8", - "import-fresh": "^3.3.1", - "resolve-from": "^5.0.0", - "vscode-languageserver-textdocument": "^1.0.12", - "vscode-uri": "^3.1.0", - "xdg-basedir": "^5.1.0" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/cspell-trie-lib": { - "version": "9.3.2", - "resolved": "https://registry.npmjs.org/cspell-trie-lib/-/cspell-trie-lib-9.3.2.tgz", - "integrity": "sha512-1Af7Mq9jIccFQyJl/ZCcqQbtJwuDqpQVkk8xfs/92x4OI6gW1iTVRMtsrh0RTw1HZoR8aQD7tRRCiLPf/D+UiQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspell/cspell-pipe": "9.3.2", - "@cspell/cspell-types": "9.3.2", - "gensequence": "^8.0.8" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/csstype": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", - "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/dequal": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", - "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/devlop": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", - "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", - "dev": true, - "license": "MIT", - "dependencies": { - "dequal": "^2.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/emoji-regex-xs": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex-xs/-/emoji-regex-xs-1.0.0.tgz", - "integrity": "sha512-LRlerrMYoIDrT6jgpeZ2YYl/L8EulRTt5hQcYjy5AInh7HWXKimpqx68aknBFpGL2+/IcogTcaydJEgaTmOpDg==", - "dev": true, - "license": "MIT" - }, - "node_modules/entities": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", - "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, - "node_modules/env-paths": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz", - "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/esbuild": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", - "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=12" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.21.5", - "@esbuild/android-arm": "0.21.5", - "@esbuild/android-arm64": "0.21.5", - "@esbuild/android-x64": "0.21.5", - "@esbuild/darwin-arm64": "0.21.5", - "@esbuild/darwin-x64": "0.21.5", - "@esbuild/freebsd-arm64": "0.21.5", - "@esbuild/freebsd-x64": "0.21.5", - "@esbuild/linux-arm": "0.21.5", - "@esbuild/linux-arm64": "0.21.5", - "@esbuild/linux-ia32": "0.21.5", - "@esbuild/linux-loong64": "0.21.5", - "@esbuild/linux-mips64el": "0.21.5", - "@esbuild/linux-ppc64": "0.21.5", - "@esbuild/linux-riscv64": "0.21.5", - "@esbuild/linux-s390x": "0.21.5", - "@esbuild/linux-x64": "0.21.5", - "@esbuild/netbsd-x64": "0.21.5", - "@esbuild/openbsd-x64": "0.21.5", - "@esbuild/sunos-x64": "0.21.5", - "@esbuild/win32-arm64": "0.21.5", - "@esbuild/win32-ia32": "0.21.5", - "@esbuild/win32-x64": "0.21.5" - } - }, - "node_modules/esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true, - "license": "BSD-2-Clause", - "bin": { - "esparse": "bin/esparse.js", - "esvalidate": "bin/esvalidate.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/estree-walker": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", - "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-equals": { - "version": "5.3.3", - "resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.3.3.tgz", - "integrity": "sha512-/boTcHZeIAQ2r/tL11voclBHDeP9WPxLt+tyAbVSyyXuUFyh0Tne7gJZTqGbxnvj79TjLdCXLOY7UIPhyG5MTw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/fast-json-stable-stringify": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "dev": true, - "license": "MIT" - }, - "node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "picomatch": "^3 || ^4" - }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } - } - }, - "node_modules/flatted": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz", - "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==", - "dev": true, - "license": "ISC" - }, - "node_modules/focus-trap": { - "version": "7.6.6", - "resolved": "https://registry.npmjs.org/focus-trap/-/focus-trap-7.6.6.tgz", - "integrity": "sha512-v/Z8bvMCajtx4mEXmOo7QEsIzlIOqRXTIwgUfsFOF9gEsespdbD0AkPIka1bSXZ8Y8oZ+2IVDQZePkTfEHZl7Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "tabbable": "^6.3.0" - } - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/gensequence": { - "version": "8.0.8", - "resolved": "https://registry.npmjs.org/gensequence/-/gensequence-8.0.8.tgz", - "integrity": "sha512-omMVniXEXpdx/vKxGnPRoO2394Otlze28TyxECbFVyoSpZ9H3EO7lemjcB12OpQJzRW4e5tt/dL1rOxry6aMHg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/global-directory": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/global-directory/-/global-directory-4.0.1.tgz", - "integrity": "sha512-wHTUcDUoZ1H5/0iVqEudYW4/kAlN5cZ3j/bXn0Dpbizl9iaUVeWSHqiOjsgk6OW2bkLclbBjzewBz6weQ1zA2Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "ini": "4.1.1" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/hast-util-to-html": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz", - "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/hast": "^3.0.0", - "@types/unist": "^3.0.0", - "ccount": "^2.0.0", - "comma-separated-tokens": "^2.0.0", - "hast-util-whitespace": "^3.0.0", - "html-void-elements": "^3.0.0", - "mdast-util-to-hast": "^13.0.0", - "property-information": "^7.0.0", - "space-separated-tokens": "^2.0.0", - "stringify-entities": "^4.0.0", - "zwitch": "^2.0.4" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/hast-util-whitespace": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", - "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/hast": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/hookable": { - "version": "5.5.3", - "resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz", - "integrity": "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/html-void-elements": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz", - "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/import-fresh": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", - "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "parent-module": "^1.0.0", - "resolve-from": "^4.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/import-fresh/node_modules/parent-module": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", - "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", - "dev": true, - "license": "MIT", - "dependencies": { - "callsites": "^3.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/import-fresh/node_modules/resolve-from": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/import-meta-resolve": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/import-meta-resolve/-/import-meta-resolve-4.2.0.tgz", - "integrity": "sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/ini": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/ini/-/ini-4.1.1.tgz", - "integrity": "sha512-QQnnxNyfvmHFIsj7gkPcYymR8Jdw/o7mp5ZFihxn6h8Ci6fh3Dx4E1gPjpQEpIuPo9XVNY/ZUwh4BPMjGyL01g==", - "dev": true, - "license": "ISC", - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/is-what": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/is-what/-/is-what-5.5.0.tgz", - "integrity": "sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/mesqueeb" - } - }, - "node_modules/magic-string": { - "version": "0.30.21", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", - "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.5" - } - }, - "node_modules/mark.js": { - "version": "8.11.1", - "resolved": "https://registry.npmjs.org/mark.js/-/mark.js-8.11.1.tgz", - "integrity": "sha512-1I+1qpDt4idfgLQG+BNWmrqku+7/2bi5nLf4YwF8y8zXvmfiTBY3PV3ZibfrjBueCByROpuBjLLFCajqkgYoLQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/mdast-util-to-hast": { - "version": "13.2.1", - "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz", - "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/hast": "^3.0.0", - "@types/mdast": "^4.0.0", - "@ungap/structured-clone": "^1.0.0", - "devlop": "^1.0.0", - "micromark-util-sanitize-uri": "^2.0.0", - "trim-lines": "^3.0.0", - "unist-util-position": "^5.0.0", - "unist-util-visit": "^5.0.0", - "vfile": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/micromark-util-character": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", - "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==", - "dev": true, - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-util-encode": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", - "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==", - "dev": true, - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT" - }, - "node_modules/micromark-util-sanitize-uri": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", - "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==", - "dev": true, - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-character": "^2.0.0", - "micromark-util-encode": "^2.0.0", - "micromark-util-symbol": "^2.0.0" - } - }, - "node_modules/micromark-util-symbol": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", - "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==", - "dev": true, - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT" - }, - "node_modules/micromark-util-types": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz", - "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==", - "dev": true, - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT" - }, - "node_modules/minisearch": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/minisearch/-/minisearch-7.2.0.tgz", - "integrity": "sha512-dqT2XBYUOZOiC5t2HRnwADjhNS2cecp9u+TJRiJ1Qp/f5qjkeT5APcGPjHw+bz89Ms8Jp+cG4AlE+QZ/QnDglg==", - "dev": true, - "license": "MIT" - }, - "node_modules/mitt": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz", - "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==", - "dev": true, - "license": "MIT" - }, - "node_modules/nanoid": { - "version": "3.3.11", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", - "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/oniguruma-to-es": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-3.1.1.tgz", - "integrity": "sha512-bUH8SDvPkH3ho3dvwJwfonjlQ4R80vjyvrU8YpxuROddv55vAEJrTuCuCVUhhsHbtlD9tGGbaNApGQckXhS8iQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex-xs": "^1.0.0", - "regex": "^6.0.1", - "regex-recursion": "^6.0.2" - } - }, - "node_modules/parent-module": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-2.0.0.tgz", - "integrity": "sha512-uo0Z9JJeWzv8BG+tRcapBKNJ0dro9cLyczGzulS6EfeyAdeC9sbojtW6XwvYxJkEne9En+J2XEl4zyglVeIwFg==", - "dev": true, - "license": "MIT", - "dependencies": { - "callsites": "^3.1.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/perfect-debounce": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz", - "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==", - "dev": true, - "license": "MIT" - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true, - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", - "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/postcss": { - "version": "8.5.6", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", - "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.11", - "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/preact": { - "version": "10.27.2", - "resolved": "https://registry.npmjs.org/preact/-/preact-10.27.2.tgz", - "integrity": "sha512-5SYSgFKSyhCbk6SrXyMpqjb5+MQBgfvEKE/OC+PujcY34sOpqtr+0AZQtPYx5IA6VxynQ7rUPCtKzyovpj9Bpg==", - "dev": true, - "license": "MIT", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/preact" - } - }, - "node_modules/prettier": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz", - "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==", - "dev": true, - "license": "MIT", - "bin": { - "prettier": "bin/prettier.cjs" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/prettier/prettier?sponsor=1" - } - }, - "node_modules/property-information": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz", - "integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/regex": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/regex/-/regex-6.0.1.tgz", - "integrity": "sha512-uorlqlzAKjKQZ5P+kTJr3eeJGSVroLKoHmquUj4zHWuR+hEyNqlXsSKlYYF5F4NI6nl7tWCs0apKJ0lmfsXAPA==", - "dev": true, - "license": "MIT", - "dependencies": { - "regex-utilities": "^2.3.0" - } - }, - "node_modules/regex-recursion": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz", - "integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==", - "dev": true, - "license": "MIT", - "dependencies": { - "regex-utilities": "^2.3.0" - } - }, - "node_modules/regex-utilities": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz", - "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==", - "dev": true, - "license": "MIT" - }, - "node_modules/resolve-from": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/rfdc": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", - "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", - "dev": true, - "license": "MIT" - }, - "node_modules/rollup": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.53.3.tgz", - "integrity": "sha512-w8GmOxZfBmKknvdXU1sdM9NHcoQejwF/4mNgj2JuEEdRaHwwF12K7e9eXn1nLZ07ad+du76mkVsyeb2rKGllsA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "1.0.8" - }, - "bin": { - "rollup": "dist/bin/rollup" - }, - "engines": { - "node": ">=18.0.0", - "npm": ">=8.0.0" - }, - "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.53.3", - "@rollup/rollup-android-arm64": "4.53.3", - "@rollup/rollup-darwin-arm64": "4.53.3", - "@rollup/rollup-darwin-x64": "4.53.3", - "@rollup/rollup-freebsd-arm64": "4.53.3", - "@rollup/rollup-freebsd-x64": "4.53.3", - "@rollup/rollup-linux-arm-gnueabihf": "4.53.3", - "@rollup/rollup-linux-arm-musleabihf": "4.53.3", - "@rollup/rollup-linux-arm64-gnu": "4.53.3", - "@rollup/rollup-linux-arm64-musl": "4.53.3", - "@rollup/rollup-linux-loong64-gnu": "4.53.3", - "@rollup/rollup-linux-ppc64-gnu": "4.53.3", - "@rollup/rollup-linux-riscv64-gnu": "4.53.3", - "@rollup/rollup-linux-riscv64-musl": "4.53.3", - "@rollup/rollup-linux-s390x-gnu": "4.53.3", - "@rollup/rollup-linux-x64-gnu": "4.53.3", - "@rollup/rollup-linux-x64-musl": "4.53.3", - "@rollup/rollup-openharmony-arm64": "4.53.3", - "@rollup/rollup-win32-arm64-msvc": "4.53.3", - "@rollup/rollup-win32-ia32-msvc": "4.53.3", - "@rollup/rollup-win32-x64-gnu": "4.53.3", - "@rollup/rollup-win32-x64-msvc": "4.53.3", - "fsevents": "~2.3.2" - } - }, - "node_modules/search-insights": { - "version": "2.17.3", - "resolved": "https://registry.npmjs.org/search-insights/-/search-insights-2.17.3.tgz", - "integrity": "sha512-RQPdCYTa8A68uM2jwxoY842xDhvx3E5LFL1LxvxCNMev4o5mLuokczhzjAgGwUZBAmOKZknArSxLKmXtIi2AxQ==", - "dev": true, - "license": "MIT", - "peer": true - }, - "node_modules/semver": { - "version": "7.7.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", - "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/shiki": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/shiki/-/shiki-2.5.0.tgz", - "integrity": "sha512-mI//trrsaiCIPsja5CNfsyNOqgAZUb6VpJA+340toL42UpzQlXpwRV9nch69X6gaUxrr9kaOOa6e3y3uAkGFxQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/core": "2.5.0", - "@shikijs/engine-javascript": "2.5.0", - "@shikijs/engine-oniguruma": "2.5.0", - "@shikijs/langs": "2.5.0", - "@shikijs/themes": "2.5.0", - "@shikijs/types": "2.5.0", - "@shikijs/vscode-textmate": "^10.0.2", - "@types/hast": "^3.0.4" - } - }, - "node_modules/smol-toml": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.5.2.tgz", - "integrity": "sha512-QlaZEqcAH3/RtNyet1IPIYPsEWAaYyXXv1Krsi+1L/QHppjX4Ifm8MQsBISz9vE8cHicIq3clogsheili5vhaQ==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">= 18" - }, - "funding": { - "url": "https://github.com/sponsors/cyyynthia" - } - }, - "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/space-separated-tokens": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", - "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/speakingurl": { - "version": "14.0.1", - "resolved": "https://registry.npmjs.org/speakingurl/-/speakingurl-14.0.1.tgz", - "integrity": "sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/stringify-entities": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", - "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", - "dev": true, - "license": "MIT", - "dependencies": { - "character-entities-html4": "^2.0.0", - "character-entities-legacy": "^3.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/superjson": { - "version": "2.2.5", - "resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.5.tgz", - "integrity": "sha512-zWPTX96LVsA/eVYnqOM2+ofcdPqdS1dAF1LN4TS2/MWuUpfitd9ctTa87wt4xrYnZnkLtS69xpBdSxVBP5Rm6w==", - "dev": true, - "license": "MIT", - "dependencies": { - "copy-anything": "^4" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/tabbable": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.3.0.tgz", - "integrity": "sha512-EIHvdY5bPLuWForiR/AN2Bxngzpuwn1is4asboytXtpTgsArc+WmSJKVLlhdh71u7jFcryDqB2A8lQvj78MkyQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/tinyglobby": { - "version": "0.2.15", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", - "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "fdir": "^6.5.0", - "picomatch": "^4.0.3" - }, - "engines": { - "node": ">=12.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/SuperchupuDev" - } - }, - "node_modules/trim-lines": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", - "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/unist-util-is": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz", - "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unist-util-position": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz", - "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unist-util-stringify-position": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", - "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unist-util-visit": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.0.0.tgz", - "integrity": "sha512-MR04uvD+07cwl/yhVuVWAtw+3GOR/knlL55Nd/wAdblk27GCVt3lqpTivy/tkJcZoNPzTwS1Y+KMojlLDhoTzg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "unist-util-is": "^6.0.0", - "unist-util-visit-parents": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unist-util-visit-parents": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", - "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "unist-util-is": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/vfile": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", - "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "vfile-message": "^4.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/vfile-message": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz", - "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "unist-util-stringify-position": "^4.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/vite": { - "version": "5.4.21", - "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz", - "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==", - "dev": true, - "license": "MIT", - "dependencies": { - "esbuild": "^0.21.3", - "postcss": "^8.4.43", - "rollup": "^4.20.0" - }, - "bin": { - "vite": "bin/vite.js" - }, - "engines": { - "node": "^18.0.0 || >=20.0.0" - }, - "funding": { - "url": "https://github.com/vitejs/vite?sponsor=1" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - }, - "peerDependencies": { - "@types/node": "^18.0.0 || >=20.0.0", - "less": "*", - "lightningcss": "^1.21.0", - "sass": "*", - "sass-embedded": "*", - "stylus": "*", - "sugarss": "*", - "terser": "^5.4.0" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "less": { - "optional": true - }, - "lightningcss": { - "optional": true - }, - "sass": { - "optional": true - }, - "sass-embedded": { - "optional": true - }, - "stylus": { - "optional": true - }, - "sugarss": { - "optional": true - }, - "terser": { - "optional": true - } - } - }, - "node_modules/vitepress": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/vitepress/-/vitepress-1.6.4.tgz", - "integrity": "sha512-+2ym1/+0VVrbhNyRoFFesVvBvHAVMZMK0rw60E3X/5349M1GuVdKeazuksqopEdvkKwKGs21Q729jX81/bkBJg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@docsearch/css": "3.8.2", - "@docsearch/js": "3.8.2", - "@iconify-json/simple-icons": "^1.2.21", - "@shikijs/core": "^2.1.0", - "@shikijs/transformers": "^2.1.0", - "@shikijs/types": "^2.1.0", - "@types/markdown-it": "^14.1.2", - "@vitejs/plugin-vue": "^5.2.1", - "@vue/devtools-api": "^7.7.0", - "@vue/shared": "^3.5.13", - "@vueuse/core": "^12.4.0", - "@vueuse/integrations": "^12.4.0", - "focus-trap": "^7.6.4", - "mark.js": "8.11.1", - "minisearch": "^7.1.1", - "shiki": "^2.1.0", - "vite": "^5.4.14", - "vue": "^3.5.13" - }, - "bin": { - "vitepress": "bin/vitepress.js" - }, - "peerDependencies": { - "markdown-it-mathjax3": "^4", - "postcss": "^8" - }, - "peerDependenciesMeta": { - "markdown-it-mathjax3": { - "optional": true - }, - "postcss": { - "optional": true - } - } - }, - "node_modules/vscode-languageserver-textdocument": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.12.tgz", - "integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==", - "dev": true, - "license": "MIT" - }, - "node_modules/vscode-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz", - "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/vue": { - "version": "3.5.24", - "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.24.tgz", - "integrity": "sha512-uTHDOpVQTMjcGgrqFPSb8iO2m1DUvo+WbGqoXQz8Y1CeBYQ0FXf2z1gLRaBtHjlRz7zZUBHxjVB5VTLzYkvftg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/compiler-dom": "3.5.24", - "@vue/compiler-sfc": "3.5.24", - "@vue/runtime-dom": "3.5.24", - "@vue/server-renderer": "3.5.24", - "@vue/shared": "3.5.24" - }, - "peerDependencies": { - "typescript": "*" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/xdg-basedir": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-5.1.0.tgz", - "integrity": "sha512-GCPAHLvrIH13+c0SuacwvRYj2SxJXQ4kaVTT5xgL3kPrz56XxkF21IGhjSE1+W0aw7gpBWRGXLCPnPby6lSpmQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/yaml": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.1.tgz", - "integrity": "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw==", - "dev": true, - "license": "ISC", - "bin": { - "yaml": "bin.mjs" - }, - "engines": { - "node": ">= 14.6" - } - }, - "node_modules/zwitch": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", - "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - } - } } diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..a669e690 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,6 @@ +{ + "name": "vault-link", + "lockfileVersion": 3, + "requires": true, + "packages": {} +} diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 00000000..a9107050 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,11 @@ +# Rustfmt configuration +# This should match the .editorconfig settings + +# Use spaces for indentation (matches .editorconfig indent_style = space) +hard_tabs = false + +# Use 4 spaces for indentation (matches .editorconfig indent_size = 4) +tab_spaces = 4 + +# Use Unix line endings (matches .editorconfig end_of_line = lf) +newline_style = "Unix" diff --git a/scripts/bump-version.sh b/scripts/bump-version.sh index fb953e2a..bea3d982 100755 --- a/scripts/bump-version.sh +++ b/scripts/bump-version.sh @@ -35,7 +35,8 @@ cd .. cp frontend/obsidian-plugin/manifest.json manifest.json # for BRAT, otherwise it wouldn't update -git ls-files | xargs npx eclint fix +# Format all files across the project (frontend and backend) +npx -C frontend prettier --write "**/*.{ts,js,json,md,yml,yaml}" # Commit and tag git add . diff --git a/scripts/check.sh b/scripts/check.sh index 7c3c87e5..2ee0dd62 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -30,8 +30,11 @@ fi which cargo-machete || cargo install cargo-machete cargo machete --with-metadata +cd .. +scripts/update-api-types.sh # this will dirty up the git state if not up-to-date + echo "Running checks in frontend" -cd ../frontend +cd frontend if [[ "$FIX_MODE" == true ]]; then npm install @@ -45,10 +48,11 @@ cd frontend npm run build npm run test npm run lint +cd .. -# Use git ls-files to only check tracked files, respecting .gitignore -# We always run in fix mode and then check with git status -git ls-files | xargs npx eclint fix +# Format all files across the project (frontend and backend) +# Prettier respects .gitignore by default +npx -C frontend prettier --write "**/*.{ts,js,json,md,yml,yaml}" if [[ "$FIX_MODE" == false ]] && [[ $(git status --porcelain) ]]; then git status --porcelain @@ -56,6 +60,4 @@ if [[ "$FIX_MODE" == false ]] && [[ $(git status --porcelain) ]]; then exit 1 fi -cd .. - echo "Success" diff --git a/scripts/clean-up.sh b/scripts/clean-up.sh index 4dfbf4a0..dcf400bb 100755 --- a/scripts/clean-up.sh +++ b/scripts/clean-up.sh @@ -1,4 +1,4 @@ #!/bin/bash -rm -rf sync-server/databases +rm -rf /host/tmp/vaultlink-e2e-databases rm -rf logs diff --git a/scripts/e2e.sh b/scripts/e2e.sh index 6c66e835..7ab8d90c 100755 --- a/scripts/e2e.sh +++ b/scripts/e2e.sh @@ -19,35 +19,51 @@ process_count=$1 mkdir -p logs +# Build and restart the server +echo "Building server..." +cd sync-server +cargo build --release + +# Kill any existing server process +echo "Stopping existing server..." +pkill -f "sync_server" 2>/dev/null || true +sleep 1 + +# Clean databases (uses tmpfs via /dev/shm for zero disk I/O) +echo "Cleaning databases..." +rm -rf /host/tmp/vaultlink-e2e-databases + +# Start the server in the background +echo "Starting server..." +./target/release/sync_server config-e2e.yml & +server_pid=$! +echo "Server started with PID: $server_pid" + +# Ensure server is killed on script exit +cleanup_server() { + if [ -n "$server_pid" ]; then + echo "Stopping server (PID: $server_pid)..." + kill $server_pid 2>/dev/null || true + wait $server_pid 2>/dev/null || true + server_pid="" + fi +} +trap cleanup_server EXIT + +cd .. + cd frontend npm ci npm run build ../scripts/utils/wait-for-server.sh -cd .. -scripts/update-api-types.sh -if [[ $(git status --porcelain) ]]; then - git status --porcelain - echo "Failing CI because the working directory is not clean after generating api types" - exit 1 -fi -cd frontend - pids=() for i in $(seq 1 $process_count); do - # Create a named pipe for this process - pipe="/tmp/vaultlink_pipe_$$_$i" - mkfifo "$pipe" - - # Start the node process writing to the pipe - node test-client/dist/cli.js > "$pipe" 2>&1 & + node test-client/dist/cli.js > "../logs/log_${i}.log" 2>&1 & pid=$! pids+=($pid) - echo "Started process $i with PID: $pid" - - # Read from pipe, prefix with PID - (sed "s/^/[PID $pid] /" < "$pipe" > "../logs/log_${i}.log"; rm "$pipe") & + echo "Started process $i with PID: $pid (log: logs/log_${i}.log)" done cd .. @@ -75,10 +91,25 @@ print_failed_log() { return 1 } -echo "Monitoring $process_count processes" +E2E_TIMEOUT=${2:-3600} +start_time=$(date +%s) +echo "Monitoring $process_count processes (timeout: ${E2E_TIMEOUT}s)" # Monitor processes while true; do + # Script-level timeout to prevent indefinite hangs + current_time=$(date +%s) + elapsed=$((current_time - start_time)) + if [ $elapsed -ge $E2E_TIMEOUT ]; then + echo "E2E timeout reached (${E2E_TIMEOUT}s). Killing remaining processes." + for pid in "${pids[@]}"; do + if [ -n "$pid" ]; then + kill $pid 2>/dev/null || true + fi + done + exit 1 + fi + if print_failed_log; then # Kill remaining processes for pid in "${pids[@]}"; do @@ -99,6 +130,7 @@ while true; do done if $all_done; then + cleanup_server echo "All processes completed successfully" exit 0 fi diff --git a/scripts/update-api-types.sh b/scripts/update-api-types.sh index 4b947ee8..3f4a9e2a 100755 --- a/scripts/update-api-types.sh +++ b/scripts/update-api-types.sh @@ -8,9 +8,15 @@ cd sync-server cargo test export_bindings cd - +# Both target directories contain only generated bindings — wipe and copy +rm -f frontend/sync-client/src/services/types/*.ts +rm -f frontend/history-ui/src/lib/types/*.ts cp -r sync-server/bindings/* frontend/sync-client/src/services/types/ +cp -r sync-server/bindings/* frontend/history-ui/src/lib/types/ cd frontend npm run lint -git ls-files | xargs npx eclint fix -cd - +cd .. + +# Format all files across the project (frontend and backend) +npx -C frontend prettier --write "**/*.{ts,js,json,md,yml,yaml}" diff --git a/scripts/utils/check-node.sh b/scripts/utils/check-node.sh index c9ede47e..d93f2f27 100755 --- a/scripts/utils/check-node.sh +++ b/scripts/utils/check-node.sh @@ -2,8 +2,10 @@ set -e +TARGET_NODE_VERSION=25 + node_version=$(node -v | sed 's/^v\([0-9]*\).*/\1/') -if [ "$node_version" != "22" ]; then - echo "Error: This script requires Node.js version 22, found: $node_version" +if [ "$node_version" != "$TARGET_NODE_VERSION" ]; then + echo "Error: This script requires Node.js version $TARGET_NODE_VERSION, found: $node_version" exit 1 fi diff --git a/scripts/utils/wait-for-server.sh b/scripts/utils/wait-for-server.sh index 7824c405..71103477 100755 --- a/scripts/utils/wait-for-server.sh +++ b/scripts/utils/wait-for-server.sh @@ -2,14 +2,14 @@ set -e -SERVER_URL="http://localhost:3000" +SERVER_URL="http://localhost:3010" MAX_RETRIES=30 RETRY_INTERVAL_IN_SECONDS=5 echo "Waiting for $SERVER_URL to become available..." count=0 while [ $count -lt $MAX_RETRIES ]; do - if curl -s -f -o /dev/null $SERVER_URL; then + if curl -s -o /dev/null $SERVER_URL; then echo "$SERVER_URL is now available!" break fi From 0e3132f96c826eaa26f577f6f5e92c6d074505b3 Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Sat, 9 May 2026 10:15:21 +0100 Subject: [PATCH 12/17] Add deterministic-tests (#190) Reviewed-on: https://home.schmelczer.dev/git/git/andras/vault-link/pulls/190 Co-authored-by: Andras Schmelczer Co-committed-by: Andras Schmelczer --- frontend/deterministic-tests/README.md | 118 +++++ frontend/deterministic-tests/package.json | 23 + frontend/deterministic-tests/src/cli.ts | 243 +++++++++ frontend/deterministic-tests/src/consts.ts | 17 + .../src/deterministic-agent.ts | 483 ++++++++++++++++++ .../src/managed-websocket.ts | 245 +++++++++ .../deterministic-tests/src/parse-args.ts | 43 ++ .../src/prefixed-logger.ts | 28 + .../src/run-with-concurrency.ts | 33 ++ .../deterministic-tests/src/server-control.ts | 296 +++++++++++ .../deterministic-tests/src/server-manager.ts | 71 +++ .../src/test-definition.ts | 49 ++ .../deterministic-tests/src/test-registry.ts | 245 +++++++++ .../deterministic-tests/src/test-runner.ts | 399 +++++++++++++++ ...inary-pending-create-not-displaced.test.ts | 40 ++ .../tests/binary-to-text-transition.test.ts | 97 ++++ ...chup-create-and-update-not-skipped.test.ts | 66 +++ ...sce-update-remote-update-data-loss.test.ts | 59 +++ ...esced-remote-update-watermark-loss.test.ts | 53 ++ ...urrent-delete-during-remote-update.test.ts | 32 ++ ...oncurrent-edit-exact-same-position.test.ts | 49 ++ ...-and-create-at-target-create-first.test.ts | 49 ++ ...-and-create-at-target-rename-first.test.ts | 52 ++ .../concurrent-rename-first-wins.test.ts | 61 +++ .../concurrent-rename-same-target.test.ts | 39 ++ ...concurrent-update-diff-consistency.test.ts | 51 ++ .../src/tests/create-delete-noop.test.ts | 27 + .../create-during-reconciliation.test.ts | 50 ++ .../src/tests/create-merge-delete.test.ts | 37 ++ ...ate-merge-preserves-renamed-update.test.ts | 59 +++ .../create-rename-create-same-path.test.ts | 34 ++ .../create-rename-response-skips-file.test.ts | 36 ++ ...reate-update-coalesce-server-pause.test.ts | 32 ++ ...lete-by-other-client-then-recreate.test.ts | 40 ++ .../delete-during-pending-create.test.ts | 35 ++ .../delete-recreate-concurrent-update.test.ts | 42 ++ .../delete-recreate-different-content.test.ts | 54 ++ .../tests/delete-recreate-same-path.test.ts | 34 ++ ...-create-with-stale-deleting-record.test.ts | 52 ++ .../src/tests/delete-rename-conflict.test.ts | 43 ++ .../displaced-file-not-marked-deleted.test.ts | 38 ++ .../src/tests/double-offline-cycle.test.ts | 77 +++ .../idempotency-after-server-pause.test.ts | 33 ++ .../tests/interrupted-delete-retry.test.ts | 29 ++ ...ocal-edit-lost-during-create-merge.test.ts | 41 ++ ...ocal-rename-survives-remote-rename.test.ts | 80 +++ ...ocal-update-survives-remote-rename.test.ts | 69 +++ ...mc-cross-create-rename-same-target.test.ts | 46 ++ .../mc-delete-then-offline-rename.test.ts | 39 ++ .../mc-multi-delete-offline-rename.test.ts | 49 ++ ...three-client-rename-offline-update.test.ts | 41 ++ ...date-response-survives-user-rename.test.ts | 77 +++ .../move-and-concurrent-remote-update.test.ts | 43 ++ .../src/tests/move-chain-three-files.test.ts | 42 ++ .../move-identical-content-ambiguity.test.ts | 44 ++ .../move-preserves-remote-update.test.ts | 48 ++ .../move-remote-update-reverts-rename.test.ts | 38 ++ .../tests/move-then-delete-stale-path.test.ts | 34 ++ .../src/tests/multi-file-operations.test.ts | 45 ++ .../tests/offline-concurrent-renames.test.ts | 59 +++ ...offline-create-same-path-mergeable.test.ts | 41 ++ .../offline-delete-remote-rename.test.ts | 38 ++ .../offline-delete-vs-remote-update.test.ts | 46 ++ .../tests/offline-edit-remote-rename.test.ts | 49 ++ ...ffline-edit-then-move-same-content.test.ts | 51 ++ .../tests/offline-mixed-operations.test.ts | 57 +++ .../offline-move-then-remote-delete.test.ts | 36 ++ .../src/tests/offline-multiple-edits.test.ts | 40 ++ .../src/tests/offline-rename-and-edit.test.ts | 43 ++ ...line-rename-remote-create-old-path.test.ts | 51 ++ ...ffline-update-both-then-delete-one.test.ts | 75 +++ ...e-both-create-same-path-deconflict.test.ts | 34 ++ ...te-rename-concurrent-create-orphan.test.ts | 41 ++ ...date-while-other-creates-same-path.test.ts | 48 ++ ...online-delete-recreate-rapid-cycle.test.ts | 37 ++ .../online-edit-vs-delete-convergence.test.ts | 31 ++ .../overlapping-edits-same-section.test.ts | 54 ++ ...e-reset-loses-coalesced-local-edit.test.ts | 36 ++ ...delete-does-not-hijack-reused-path.test.ts | 56 ++ .../rapid-create-update-delete-cycle.test.ts | 52 ++ ...pid-edit-delete-online-convergence.test.ts | 48 ++ .../tests/rapid-updates-after-merge.test.ts | 49 ++ ...ently-deleted-cleared-on-reconnect.test.ts | 45 ++ ...e-quick-write-rename-before-record.test.ts | 36 ++ ...collides-with-pending-local-create.test.ts | 76 +++ ...mote-update-resurrects-deleted-doc.test.ts | 59 +++ ...remote-update-survives-user-rename.test.ts | 84 +++ ...rename-chain-during-pending-create.test.ts | 64 +++ .../tests/rename-chain-then-delete.test.ts | 50 ++ .../src/tests/rename-chain.test.ts | 34 ++ .../src/tests/rename-circular.test.ts | 44 ++ .../src/tests/rename-create-conflict.test.ts | 34 ++ ...rwrites-pending-create-then-delete.test.ts | 51 ++ ...ame-pending-create-before-response.test.ts | 42 ++ ...ng-create-onto-pending-delete-path.test.ts | 59 +++ .../src/tests/rename-roundtrip.test.ts | 40 ++ .../src/tests/rename-swap.test.ts | 44 ++ ...name-to-path-of-unconfirmed-delete.test.ts | 44 ++ .../rename-to-pending-path-fallback.test.ts | 43 ++ .../src/tests/rename-update-conflict.test.ts | 42 ++ ...ing-create-reused-path-then-delete.test.ts | 65 +++ ...ears-recently-deleted-resurrection.test.ts | 43 ++ ...ote-quick-write-and-pending-rename.test.ts | 82 +++ ...n-local-create-after-remote-create.test.ts | 121 +++++ ...nding-rename-aliases-second-create.test.ts | 152 ++++++ ...equential-create-duplicate-content.test.ts | 43 ++ .../server-pause-both-clients-create.test.ts | 42 ++ .../server-pause-both-edit-same-file.test.ts | 68 +++ .../server-pause-delete-recreate.test.ts | 38 ++ .../server-pause-rename-edit-resume.test.ts | 50 ++ .../server-pause-update-and-create.test.ts | 54 ++ ...multaneous-create-delete-same-path.test.ts | 38 ++ .../text-pending-create-not-displaced.test.ts | 36 ++ .../three-client-rename-create-delete.test.ts | 55 ++ ...ate-does-not-survive-remote-delete.test.ts | 36 ++ .../update-during-create-processing.test.ts | 42 ++ ...ser-parenthesized-file-not-deleted.test.ts | 47 ++ .../tests/watermark-advances-on-skip.test.ts | 35 ++ ...ark-gap-remote-update-not-recorded.test.ts | 37 ++ .../deterministic-tests/src/utils/assert.ts | 5 + .../src/utils/assertable-state.ts | 150 ++++++ .../src/utils/find-free-port.ts | 29 ++ .../deterministic-tests/src/utils/sleep.ts | 3 + .../src/utils/with-timeout.ts | 15 + frontend/deterministic-tests/tsconfig.json | 12 + .../deterministic-tests/webpack.config.js | 30 ++ frontend/package.json | 3 +- 127 files changed, 7722 insertions(+), 1 deletion(-) create mode 100644 frontend/deterministic-tests/README.md create mode 100644 frontend/deterministic-tests/package.json create mode 100644 frontend/deterministic-tests/src/cli.ts create mode 100644 frontend/deterministic-tests/src/consts.ts create mode 100644 frontend/deterministic-tests/src/deterministic-agent.ts create mode 100644 frontend/deterministic-tests/src/managed-websocket.ts create mode 100644 frontend/deterministic-tests/src/parse-args.ts create mode 100644 frontend/deterministic-tests/src/prefixed-logger.ts create mode 100644 frontend/deterministic-tests/src/run-with-concurrency.ts create mode 100644 frontend/deterministic-tests/src/server-control.ts create mode 100644 frontend/deterministic-tests/src/server-manager.ts create mode 100644 frontend/deterministic-tests/src/test-definition.ts create mode 100644 frontend/deterministic-tests/src/test-registry.ts create mode 100644 frontend/deterministic-tests/src/test-runner.ts create mode 100644 frontend/deterministic-tests/src/tests/binary-pending-create-not-displaced.test.ts create mode 100644 frontend/deterministic-tests/src/tests/binary-to-text-transition.test.ts create mode 100644 frontend/deterministic-tests/src/tests/catchup-create-and-update-not-skipped.test.ts create mode 100644 frontend/deterministic-tests/src/tests/coalesce-update-remote-update-data-loss.test.ts create mode 100644 frontend/deterministic-tests/src/tests/coalesced-remote-update-watermark-loss.test.ts create mode 100644 frontend/deterministic-tests/src/tests/concurrent-delete-during-remote-update.test.ts create mode 100644 frontend/deterministic-tests/src/tests/concurrent-edit-exact-same-position.test.ts create mode 100644 frontend/deterministic-tests/src/tests/concurrent-rename-and-create-at-target-create-first.test.ts create mode 100644 frontend/deterministic-tests/src/tests/concurrent-rename-and-create-at-target-rename-first.test.ts create mode 100644 frontend/deterministic-tests/src/tests/concurrent-rename-first-wins.test.ts create mode 100644 frontend/deterministic-tests/src/tests/concurrent-rename-same-target.test.ts create mode 100644 frontend/deterministic-tests/src/tests/concurrent-update-diff-consistency.test.ts create mode 100644 frontend/deterministic-tests/src/tests/create-delete-noop.test.ts create mode 100644 frontend/deterministic-tests/src/tests/create-during-reconciliation.test.ts create mode 100644 frontend/deterministic-tests/src/tests/create-merge-delete.test.ts create mode 100644 frontend/deterministic-tests/src/tests/create-merge-preserves-renamed-update.test.ts create mode 100644 frontend/deterministic-tests/src/tests/create-rename-create-same-path.test.ts create mode 100644 frontend/deterministic-tests/src/tests/create-rename-response-skips-file.test.ts create mode 100644 frontend/deterministic-tests/src/tests/create-update-coalesce-server-pause.test.ts create mode 100644 frontend/deterministic-tests/src/tests/delete-by-other-client-then-recreate.test.ts create mode 100644 frontend/deterministic-tests/src/tests/delete-during-pending-create.test.ts create mode 100644 frontend/deterministic-tests/src/tests/delete-recreate-concurrent-update.test.ts create mode 100644 frontend/deterministic-tests/src/tests/delete-recreate-different-content.test.ts create mode 100644 frontend/deterministic-tests/src/tests/delete-recreate-same-path.test.ts create mode 100644 frontend/deterministic-tests/src/tests/delete-recreated-pending-create-with-stale-deleting-record.test.ts create mode 100644 frontend/deterministic-tests/src/tests/delete-rename-conflict.test.ts create mode 100644 frontend/deterministic-tests/src/tests/displaced-file-not-marked-deleted.test.ts create mode 100644 frontend/deterministic-tests/src/tests/double-offline-cycle.test.ts create mode 100644 frontend/deterministic-tests/src/tests/idempotency-after-server-pause.test.ts create mode 100644 frontend/deterministic-tests/src/tests/interrupted-delete-retry.test.ts create mode 100644 frontend/deterministic-tests/src/tests/local-edit-lost-during-create-merge.test.ts create mode 100644 frontend/deterministic-tests/src/tests/local-rename-survives-remote-rename.test.ts create mode 100644 frontend/deterministic-tests/src/tests/local-update-survives-remote-rename.test.ts create mode 100644 frontend/deterministic-tests/src/tests/mc-cross-create-rename-same-target.test.ts create mode 100644 frontend/deterministic-tests/src/tests/mc-delete-then-offline-rename.test.ts create mode 100644 frontend/deterministic-tests/src/tests/mc-multi-delete-offline-rename.test.ts create mode 100644 frontend/deterministic-tests/src/tests/mc-three-client-rename-offline-update.test.ts create mode 100644 frontend/deterministic-tests/src/tests/merging-update-response-survives-user-rename.test.ts create mode 100644 frontend/deterministic-tests/src/tests/move-and-concurrent-remote-update.test.ts create mode 100644 frontend/deterministic-tests/src/tests/move-chain-three-files.test.ts create mode 100644 frontend/deterministic-tests/src/tests/move-identical-content-ambiguity.test.ts create mode 100644 frontend/deterministic-tests/src/tests/move-preserves-remote-update.test.ts create mode 100644 frontend/deterministic-tests/src/tests/move-remote-update-reverts-rename.test.ts create mode 100644 frontend/deterministic-tests/src/tests/move-then-delete-stale-path.test.ts create mode 100644 frontend/deterministic-tests/src/tests/multi-file-operations.test.ts create mode 100644 frontend/deterministic-tests/src/tests/offline-concurrent-renames.test.ts create mode 100644 frontend/deterministic-tests/src/tests/offline-create-same-path-mergeable.test.ts create mode 100644 frontend/deterministic-tests/src/tests/offline-delete-remote-rename.test.ts create mode 100644 frontend/deterministic-tests/src/tests/offline-delete-vs-remote-update.test.ts create mode 100644 frontend/deterministic-tests/src/tests/offline-edit-remote-rename.test.ts create mode 100644 frontend/deterministic-tests/src/tests/offline-edit-then-move-same-content.test.ts create mode 100644 frontend/deterministic-tests/src/tests/offline-mixed-operations.test.ts create mode 100644 frontend/deterministic-tests/src/tests/offline-move-then-remote-delete.test.ts create mode 100644 frontend/deterministic-tests/src/tests/offline-multiple-edits.test.ts create mode 100644 frontend/deterministic-tests/src/tests/offline-rename-and-edit.test.ts create mode 100644 frontend/deterministic-tests/src/tests/offline-rename-remote-create-old-path.test.ts create mode 100644 frontend/deterministic-tests/src/tests/offline-update-both-then-delete-one.test.ts create mode 100644 frontend/deterministic-tests/src/tests/online-both-create-same-path-deconflict.test.ts create mode 100644 frontend/deterministic-tests/src/tests/online-create-rename-concurrent-create-orphan.test.ts create mode 100644 frontend/deterministic-tests/src/tests/online-create-update-while-other-creates-same-path.test.ts create mode 100644 frontend/deterministic-tests/src/tests/online-delete-recreate-rapid-cycle.test.ts create mode 100644 frontend/deterministic-tests/src/tests/online-edit-vs-delete-convergence.test.ts create mode 100644 frontend/deterministic-tests/src/tests/overlapping-edits-same-section.test.ts create mode 100644 frontend/deterministic-tests/src/tests/queue-reset-loses-coalesced-local-edit.test.ts create mode 100644 frontend/deterministic-tests/src/tests/queued-create-delete-does-not-hijack-reused-path.test.ts create mode 100644 frontend/deterministic-tests/src/tests/rapid-create-update-delete-cycle.test.ts create mode 100644 frontend/deterministic-tests/src/tests/rapid-edit-delete-online-convergence.test.ts create mode 100644 frontend/deterministic-tests/src/tests/rapid-updates-after-merge.test.ts create mode 100644 frontend/deterministic-tests/src/tests/recently-deleted-cleared-on-reconnect.test.ts create mode 100644 frontend/deterministic-tests/src/tests/remote-quick-write-rename-before-record.test.ts create mode 100644 frontend/deterministic-tests/src/tests/remote-rename-collides-with-pending-local-create.test.ts create mode 100644 frontend/deterministic-tests/src/tests/remote-update-resurrects-deleted-doc.test.ts create mode 100644 frontend/deterministic-tests/src/tests/remote-update-survives-user-rename.test.ts create mode 100644 frontend/deterministic-tests/src/tests/rename-chain-during-pending-create.test.ts create mode 100644 frontend/deterministic-tests/src/tests/rename-chain-then-delete.test.ts create mode 100644 frontend/deterministic-tests/src/tests/rename-chain.test.ts create mode 100644 frontend/deterministic-tests/src/tests/rename-circular.test.ts create mode 100644 frontend/deterministic-tests/src/tests/rename-create-conflict.test.ts create mode 100644 frontend/deterministic-tests/src/tests/rename-overwrites-pending-create-then-delete.test.ts create mode 100644 frontend/deterministic-tests/src/tests/rename-pending-create-before-response.test.ts create mode 100644 frontend/deterministic-tests/src/tests/rename-pending-create-onto-pending-delete-path.test.ts create mode 100644 frontend/deterministic-tests/src/tests/rename-roundtrip.test.ts create mode 100644 frontend/deterministic-tests/src/tests/rename-swap.test.ts create mode 100644 frontend/deterministic-tests/src/tests/rename-to-path-of-unconfirmed-delete.test.ts create mode 100644 frontend/deterministic-tests/src/tests/rename-to-pending-path-fallback.test.ts create mode 100644 frontend/deterministic-tests/src/tests/rename-update-conflict.test.ts create mode 100644 frontend/deterministic-tests/src/tests/renamed-pending-create-reused-path-then-delete.test.ts create mode 100644 frontend/deterministic-tests/src/tests/reset-clears-recently-deleted-resurrection.test.ts create mode 100644 frontend/deterministic-tests/src/tests/same-doc-id-collapse-after-remote-quick-write-and-pending-rename.test.ts create mode 100644 frontend/deterministic-tests/src/tests/same-doc-id-collapse-on-local-create-after-remote-create.test.ts create mode 100644 frontend/deterministic-tests/src/tests/self-merge-pending-rename-aliases-second-create.test.ts create mode 100644 frontend/deterministic-tests/src/tests/sequential-create-duplicate-content.test.ts create mode 100644 frontend/deterministic-tests/src/tests/server-pause-both-clients-create.test.ts create mode 100644 frontend/deterministic-tests/src/tests/server-pause-both-edit-same-file.test.ts create mode 100644 frontend/deterministic-tests/src/tests/server-pause-delete-recreate.test.ts create mode 100644 frontend/deterministic-tests/src/tests/server-pause-rename-edit-resume.test.ts create mode 100644 frontend/deterministic-tests/src/tests/server-pause-update-and-create.test.ts create mode 100644 frontend/deterministic-tests/src/tests/simultaneous-create-delete-same-path.test.ts create mode 100644 frontend/deterministic-tests/src/tests/text-pending-create-not-displaced.test.ts create mode 100644 frontend/deterministic-tests/src/tests/three-client-rename-create-delete.test.ts create mode 100644 frontend/deterministic-tests/src/tests/update-does-not-survive-remote-delete.test.ts create mode 100644 frontend/deterministic-tests/src/tests/update-during-create-processing.test.ts create mode 100644 frontend/deterministic-tests/src/tests/user-parenthesized-file-not-deleted.test.ts create mode 100644 frontend/deterministic-tests/src/tests/watermark-advances-on-skip.test.ts create mode 100644 frontend/deterministic-tests/src/tests/watermark-gap-remote-update-not-recorded.test.ts create mode 100644 frontend/deterministic-tests/src/utils/assert.ts create mode 100644 frontend/deterministic-tests/src/utils/assertable-state.ts create mode 100644 frontend/deterministic-tests/src/utils/find-free-port.ts create mode 100644 frontend/deterministic-tests/src/utils/sleep.ts create mode 100644 frontend/deterministic-tests/src/utils/with-timeout.ts create mode 100644 frontend/deterministic-tests/tsconfig.json create mode 100644 frontend/deterministic-tests/webpack.config.js diff --git a/frontend/deterministic-tests/README.md b/frontend/deterministic-tests/README.md new file mode 100644 index 00000000..6fa2848c --- /dev/null +++ b/frontend/deterministic-tests/README.md @@ -0,0 +1,118 @@ +# Deterministic Tests + +Scripted multi-client (with an in-memory filesystem) sync tests that run against a real server. Each test defines a sequence of file operations, sync/server controls, and assertions to exercise a specific conflict or edge case. + +Complements the fuzz-based E2E tests (`test-client`): fuzz tests discover bugs through random operations; deterministic tests pin down exact reproduction sequences for known scenarios. + +## How it works + +Each test is a `TestDefinition`: a client count and an ordered list of steps. The test name is derived from the registry key (which matches the file name). The `TestRunner` spins up N `DeterministicAgent` instances (each wrapping a real `SyncClient` with an `InMemoryFileSystem`) pointed at a shared vault on the server, then executes steps one by one. + +Tests that don't pause the server share a single server process (vault-name isolation). Tests that use `pause-server`/`resume-server` (SIGSTOP/SIGCONT) each get a dedicated server, since SIGSTOP freezes the entire process. + +The runner executes two sequential phases: regular tests on the shared server, then pause-server tests on dedicated servers. Within each phase tests run in parallel up to a concurrency limit. + +## Step types + +Clients always start with syncing disabled. + +**File operations** (per-client, fire-and-forget — sync is enqueued but not awaited): + +- `create`, `update`, `rename`, `delete` +- `rename-next-write` — arm a deferred rename that fires the next time the given path is written. Lets a test race a user-rename against an in-flight remote create that's about to land at the same path. + +**Sync control:** + +- `sync` — wait for a specific client or all clients to finish pending operations +- `barrier` — retry until all clients converge to identical file state (60s timeout) +- `enable-sync` / `disable-sync` — simulate going online/offline +- `reset` — reset a client's tracked sync state (keeps disk files); equivalent to a forced re-handshake on next enable +- `sleep` — wall-clock pause; use sparingly, prefer `barrier` / `sync` + +**WebSocket control** (per-client): + +- `pause-websocket` / `resume-websocket` — buffer/release WebSocket messages for a specific client + +**Server control:** + +- `pause-server` / `resume-server` — SIGSTOP/SIGCONT the server process +- `resume-server-until-history-then-pause` — resume the server, wait until a specific client observes a matching history entry (`CREATE`/`UPDATE`/`DELETE` for a path), then re-pause. Used to land exactly one operation across the wire. + +**Fault injection** (per-client): + +- `drop-next-create-response` — arm a one-shot interceptor that lets the next `POST /documents` reach the server (commit happens) but throws `SyncResetError` before the client sees the response, simulating connection loss after server commit. +- `wait-for-dropped-create-response` — wait until the armed drop has fired. + +**Assertions:** + +- `assert-consistent` — all clients have identical files; optionally takes a custom `verify(state: AssertableState)` callback + +## Running + +```sh +# Build server first +cd sync-server && cargo build --release && cd - + +# Run all tests +cd frontend && npm run build -w sync-client && npm run test -w deterministic-tests + +# Filter by name +npm run test -w deterministic-tests -- --filter=rename + +# Control parallelism (default: number of CPU cores) +npm run test -w deterministic-tests -- -j 4 +``` + +## Adding a test + +1. Create `src/tests/my-scenario.test.ts`: + +```typescript +import type { TestDefinition } from "../test-definition"; + +export const myScenarioTest: TestDefinition = { + description: + "Client 0 creates A.md offline. After syncing, both clients should have the file.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "hello" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s) => { + s.assertFileCount(1).assertContent("A.md", "hello"); + } + } + ] +}; +``` + +The `verify` callback receives an `AssertableState` object with chainable assertion methods: + +```typescript +s.assertFileCount(n); // exact file count +s.assertFileExists("path"); // file must exist +s.assertFileNotExists("path"); // file must not exist +s.assertContent("path", "expected"); // exact content match +s.assertContains("path", "a", "b"); // all substrings present in file +s.assertContainsAny("path", "a", "b"); // at least one substring present +s.assertAnyFileContains("text"); // substring present in some file +s.assertNoFileContains("text"); // substring absent from every file +s.assertSubstringCount("path", "x", 3); // substring appears exactly N times +s.assertContentInAtMostOneFile("text"); // no duplicate content +s.ifFileExists("path", (s) => { /* … */ }); // conditional block +s.getContent("path"); // raw content (or "" if missing) +``` + +2. Register it in `src/test-registry.ts`: + +```typescript +import { myScenarioTest } from "./tests/my-scenario.test"; + +const TESTS = { + // ... + "my-scenario": myScenarioTest +}; +``` diff --git a/frontend/deterministic-tests/package.json b/frontend/deterministic-tests/package.json new file mode 100644 index 00000000..4bd82c74 --- /dev/null +++ b/frontend/deterministic-tests/package.json @@ -0,0 +1,23 @@ +{ + "name": "deterministic-tests", + "version": "0.14.0", + "private": true, + "bin": { + "deterministic-tests": "./dist/cli.js" + }, + "scripts": { + "dev": "webpack watch --mode development", + "build": "webpack --mode production", + "test": "npm run build && node dist/cli.js" + }, + "devDependencies": { + "commander": "^14.0.2", + "@types/node": "^25.0.2", + "sync-client": "file:../sync-client", + "ts-loader": "^9.5.4", + "tslib": "2.8.1", + "typescript": "5.9.3", + "webpack": "^5.103.0", + "webpack-cli": "^6.0.1" + } +} diff --git a/frontend/deterministic-tests/src/cli.ts b/frontend/deterministic-tests/src/cli.ts new file mode 100644 index 00000000..6e15cac0 --- /dev/null +++ b/frontend/deterministic-tests/src/cli.ts @@ -0,0 +1,243 @@ +import { TestRunner } from "./test-runner"; +import { ServerControl } from "./server-control"; +import { ServerManager } from "./server-manager"; +import { PrefixedLogger } from "./prefixed-logger"; +import { TESTS } from "./test-registry"; +import type { TestDefinition, TestResult } from "./test-definition"; +import { parseArgs } from "./parse-args"; +import { runWithConcurrency } from "./run-with-concurrency"; +import { TOKEN, SERVER_BINARY_PATH, CONFIG_PATH } from "./consts"; +import * as path from "node:path"; +import * as fs from "node:fs"; +import { debugging, Logger } from "sync-client"; + +const logger = new Logger(); +debugging.logToConsole(logger, { useColors: true }); + +process.on("unhandledRejection", (reason) => { + logger.error(`Unhandled Rejection: ${reason}`); + process.exit(1); +}); + +process.on("uncaughtException", (error) => { + logger.error(`Uncaught Exception: ${error}`); + process.exit(1); +}); + +const serverManager = new ServerManager(logger); +serverManager.installSignalHandlers(); + +function testUsesPauseServer(test: TestDefinition): boolean { + return test.steps.some( + (step) => + step.type === "pause-server" || + step.type === "resume-server" || + step.type === "resume-server-until-history-then-pause" + ); +} + +/** + * Walk up from the CLI binary's location until we find a directory + * containing `sync-server/` and `frontend/`. + */ +function findProjectRoot(): string { + let dir = path.dirname(__filename); + const root = path.parse(dir).root; + while (dir !== root) { + if ( + fs.existsSync(path.join(dir, "sync-server")) && + fs.existsSync(path.join(dir, "frontend")) + ) { + return dir; + } + dir = path.dirname(dir); + } + throw new Error( + `Could not locate project root (no ancestor of ${__filename} contains both 'sync-server' and 'frontend')` + ); +} + +interface NamedTestResult { + name: string; + result: TestResult; +} + +async function runSharedServerTest( + name: string, + test: TestDefinition, + sharedServer: ServerControl +): Promise { + const testLogger = new PrefixedLogger(logger, name); + const runner = new TestRunner( + sharedServer, + testLogger, + TOKEN, + sharedServer.remoteUri + ); + const result = await runner.runTest(name, test); + if (result.success) { + logger.info(`PASSED: ${name} (${result.duration}ms)`); + } else { + logger.error(`FAILED: ${name} - ${result.error}`); + } + return { name, result }; +} + +/** + * Run a test with its own dedicated server (for tests that use pause-server). + * SIGSTOP/SIGCONT affects the entire server process, so these tests need + * isolated servers to avoid interfering with other tests. + */ +async function runDedicatedServerTest( + name: string, + test: TestDefinition, + serverPath: string, + configPath: string +): Promise { + const testLogger = new PrefixedLogger(logger, name); + const server = new ServerControl(serverPath, configPath, testLogger); + serverManager.track(server); + + try { + await server.start(); + const runner = new TestRunner( + server, + testLogger, + TOKEN, + server.remoteUri + ); + const result = await runner.runTest(name, test); + if (result.success) { + logger.info(`PASSED: ${name} (${result.duration}ms)`); + } else { + logger.error(`FAILED: ${name} - ${result.error}`); + } + return { name, result }; + } finally { + try { + await server.stop(); + } catch { + // best-effort cleanup + } + serverManager.untrack(server); + } +} + +async function main(): Promise { + const projectRoot = findProjectRoot(); + const serverPath = path.join(projectRoot, SERVER_BINARY_PATH); + if (!fs.existsSync(serverPath)) { + logger.error(`Server binary not found at: ${serverPath}`); + process.exit(1); + } + + const configPath = path.join(projectRoot, CONFIG_PATH); + if (!fs.existsSync(configPath)) { + logger.error(`Config file not found at: ${configPath}`); + process.exit(1); + } + + const { filter, concurrency } = parseArgs(process.argv); + + const testsToRun: [string, TestDefinition][] = []; + for (const [key, test] of Object.entries(TESTS)) { + if (test) { + if ( + filter !== undefined && + filter.length > 0 && + !key.includes(filter) + ) { + continue; + } + testsToRun.push([key, test]); + } + } + + if (testsToRun.length === 0) { + logger.error( + filter !== undefined && filter.length > 0 + ? `No tests matched filter "${filter}"` + : "No tests found" + ); + process.exit(1); + } + + const regularTests = testsToRun.filter(([, t]) => !testUsesPauseServer(t)); + const pauseTests = testsToRun.filter(([, t]) => testUsesPauseServer(t)); + + logger.info(`Server: ${serverPath}`); + logger.info(`Config: ${configPath}`); + logger.info( + `Tests: ${testsToRun.length} total (${regularTests.length} regular, ${pauseTests.length} server-pause)` + ); + logger.info(`Concurrency: ${concurrency}`); + + const allResults: NamedTestResult[] = []; + + if (regularTests.length > 0) { + logger.info( + `\n--- Running ${regularTests.length} regular tests (shared server, concurrency ${concurrency}) ---` + ); + const sharedServer = new ServerControl(serverPath, configPath, logger); + serverManager.track(sharedServer); + + try { + await sharedServer.start(); + + const results = await runWithConcurrency( + regularTests, + concurrency, + async ([name, test]) => + runSharedServerTest(name, test, sharedServer) + ); + + allResults.push(...results); + } finally { + try { + await sharedServer.stop(); + } catch (error) { + logger.warn( + `Error stopping shared server: ${error instanceof Error ? error.message : String(error)}` + ); + } + serverManager.untrack(sharedServer); + } + } + + if (pauseTests.length > 0) { + logger.info( + `\n--- Running ${pauseTests.length} server-pause tests (dedicated servers, concurrency ${concurrency}) ---` + ); + + const results = await runWithConcurrency( + pauseTests, + concurrency, + async ([name, test]) => + runDedicatedServerTest(name, test, serverPath, configPath) + ); + + allResults.push(...results); + } + + const passed = allResults.filter((r) => r.result.success); + const failed = allResults.filter((r) => !r.result.success); + + logger.info( + `\n--- Results: ${passed.length}/${allResults.length} passed ---` + ); + + if (failed.length > 0) { + for (const { name, result } of failed) { + logger.error(` FAILED: ${name}: ${result.error}`); + } + process.exit(1); + } else { + logger.info("All tests passed!"); + process.exit(0); + } +} + +main().catch((err: unknown) => { + logger.error(`Unexpected error: ${err}`); + process.exit(1); +}); diff --git a/frontend/deterministic-tests/src/consts.ts b/frontend/deterministic-tests/src/consts.ts new file mode 100644 index 00000000..d9a2498f --- /dev/null +++ b/frontend/deterministic-tests/src/consts.ts @@ -0,0 +1,17 @@ +export const TOKEN = "test-token-change-me"; +export const SERVER_BINARY_PATH = "sync-server/target/release/sync_server"; +export const CONFIG_PATH = "sync-server/config-e2e.yml"; + +export const STOP_TIMEOUT_MS = 5_000; +export const CONVERGENCE_TIMEOUT_MS = 60_000; +export const CONVERGENCE_RETRY_DELAY_MS = 500; +export const AGENT_INIT_TIMEOUT_MS = 30_000; +export const IS_SYNC_ENABLED_BY_DEFAULT = false; + +export const WAIT_TIMEOUT_MS = 60_000; +export const WEBSOCKET_CONNECT_TIMEOUT_MS = 10_000; +export const WEBSOCKET_POLL_INTERVAL_MS = 50; + +export const SERVER_READY_POLL_INTERVAL_MS = 100; +export const SERVER_READY_MAX_ATTEMPTS = 50; +export const SERVER_START_MAX_ATTEMPTS = 5; diff --git a/frontend/deterministic-tests/src/deterministic-agent.ts b/frontend/deterministic-tests/src/deterministic-agent.ts new file mode 100644 index 00000000..b32b01c2 --- /dev/null +++ b/frontend/deterministic-tests/src/deterministic-agent.ts @@ -0,0 +1,483 @@ +import type { + HistoryEntry, + StoredDatabase, + SyncSettings, + RelativePath, + TextWithCursors +} from "sync-client"; +import { + SyncClient, + SyncResetError, + debugging, + LogLevel, + utils +} from "sync-client"; +import { assert } from "./utils/assert"; +import { sleep } from "./utils/sleep"; +import { withTimeout } from "./utils/with-timeout"; +import { + IS_SYNC_ENABLED_BY_DEFAULT, + WAIT_TIMEOUT_MS, + WEBSOCKET_CONNECT_TIMEOUT_MS, + WEBSOCKET_POLL_INTERVAL_MS +} from "./consts"; +import { ManagedWebSocketFactory } from "./managed-websocket"; + +export class DeterministicAgent extends debugging.InMemoryFileSystem { + public readonly clientId: number; + private readonly logger: (msg: string) => void; + private client!: SyncClient; + private data: Partial<{ + settings: Partial; + database: Partial; + }> = {}; + private isSyncEnabled = IS_SYNC_ENABLED_BY_DEFAULT; + private readonly syncErrors: Error[] = []; + private readonly pendingSyncOperations = new Set>(); + private readonly wsFactory = new ManagedWebSocketFactory(); + private nextWriteRename: + | { + oldPath: RelativePath; + newPath: RelativePath; + } + | undefined; + private nextCreateResponseDrop: + | { + dropped: Promise; + resolveDropped: () => void; + } + | undefined; + + public constructor( + clientId: number, + initialSettings: Partial, + logger: (msg: string) => void + ) { + super(); + this.clientId = clientId; + this.logger = logger; + this.data.settings = { ...initialSettings }; + } + + public async init( + fetchImplementation: typeof globalThis.fetch + ): Promise { + this.client = await SyncClient.create({ + fs: this, + persistence: { + load: async () => this.data, + save: async (data) => void (this.data = data) + }, + fetch: this.wrapFetch(fetchImplementation), + webSocket: this.wsFactory.constructorFn + }); + + this.client.logger.onLogEmitted.add((line) => { + const prefix = `[Client ${this.clientId}]`; + switch (line.level) { + case LogLevel.ERROR: + this.logger(`${prefix} ERROR: ${line.message}`); + break; + case LogLevel.WARNING: + this.logger(`${prefix} WARN: ${line.message}`); + break; + case LogLevel.INFO: + this.logger(`${prefix} INFO: ${line.message}`); + break; + case LogLevel.DEBUG: + this.logger(`${prefix} DEBUG: ${line.message}`); + break; + } + }); + + await this.client.start(); + + const connectionCheck = await this.client.checkConnection(); + assert( + connectionCheck.isSuccessful, + `Client ${this.clientId} connection check failed` + ); + + if (this.isSyncEnabled) { + await this.waitForWebSocket(); + } + } + + public pauseWebSocket(): void { + this.log("Pausing WebSocket message delivery"); + this.wsFactory.pause(); + } + + public resumeWebSocket(): void { + this.log("Resuming WebSocket message delivery"); + this.wsFactory.resume(); + } + + public dropNextCreateResponse(): void { + assert( + this.nextCreateResponseDrop === undefined, + `Client ${this.clientId} already has a create response drop armed` + ); + let resolveDropped!: () => void; + const dropped = new Promise((resolve) => { + resolveDropped = resolve; + }); + this.nextCreateResponseDrop = { + dropped, + resolveDropped + }; + this.log("Armed next create response drop"); + } + + public async waitForDroppedCreateResponse(): Promise { + assert( + this.nextCreateResponseDrop !== undefined, + `Client ${this.clientId} has no create response drop armed` + ); + await withTimeout( + this.nextCreateResponseDrop.dropped, + WAIT_TIMEOUT_MS, + `Client ${this.clientId} timed out waiting for create response drop` + ); + this.log("Create response was dropped after server commit"); + } + + public async waitForHistoryEntry( + matches: (entry: HistoryEntry) => boolean, + onMatch?: (entry: HistoryEntry) => void + ): Promise { + const existing = this.client.getHistoryEntries().find(matches); + if (existing !== undefined) { + onMatch?.(existing); + return; + } + + await withTimeout( + new Promise((resolve) => { + const unsubscribe = this.client.onSyncHistoryUpdated.add(() => { + const entry = this.client + .getHistoryEntries() + .find(matches); + if (entry === undefined) { + return; + } + + unsubscribe(); + onMatch?.(entry); + resolve(); + }); + }), + WAIT_TIMEOUT_MS, + `Client ${this.clientId} timed out waiting for history entry` + ); + } + + public async waitForSync(): Promise { + this.log("Waiting for sync to complete..."); + // Drain agent-level sync operations first. These are the fire-and-forget + // promises from enqueueSync() that call into the SyncClient's methods. + // Without this, waitUntilFinished() might return before the SyncClient + // has even been told about the operation. + await this.drainPendingSyncOperations(); + await withTimeout( + this.client.waitUntilFinished(), + WAIT_TIMEOUT_MS, + `Client ${this.clientId} waitForSync timed out after ${WAIT_TIMEOUT_MS}ms` + ); + if (this.syncErrors.length > 0) { + const errors = this.syncErrors.splice(0); + throw new Error( + `Client ${this.clientId} had ${errors.length} sync error(s):\n${errors.map((e) => e.message).join("\n")}` + ); + } + this.log("Sync complete"); + } + + public async reset(): Promise { + this.log("Resetting client (clears tracked state, keeps disk files)"); + await this.drainPendingSyncOperations(); + await this.client.reset(); + if (this.isSyncEnabled) { + await this.waitForWebSocket(); + } + } + + public async disableSync(): Promise { + this.log("Disabling sync"); + // Drain pending enqueued operations before disabling so the SyncClient + // knows about all operations that were enqueued while sync was enabled. + await this.drainPendingSyncOperations(); + await this.client.setSetting("isSyncEnabled", false); + this.isSyncEnabled = false; + // Wait for in-flight operations to drain. Disabling sync triggers + // a reset, which aborts in-flight fetches with SyncResetError. + try { + await withTimeout( + this.client.waitUntilFinished(), + WAIT_TIMEOUT_MS, + `Client ${this.clientId} disableSync drain timed out` + ); + } catch (error) { + if (error instanceof Error && error.name === "SyncResetError") { + this.log("Disable sync drain interrupted by reset (expected)"); + } else { + throw error; + } + } + } + + public async enableSync(): Promise { + this.log("Enabling sync"); + await this.client.setSetting("isSyncEnabled", true); + this.isSyncEnabled = true; + await this.waitForWebSocket(); + } + + public async getFileContent(path: string): Promise { + const bytes = await this.read(path); + return new TextDecoder().decode(bytes); + } + + public renameNextWrite(oldPath: RelativePath, newPath: RelativePath): void { + assert( + this.nextWriteRename === undefined, + `Client ${this.clientId} already has a next-write rename armed` + ); + this.nextWriteRename = { oldPath, newPath }; + this.log(`Armed next write rename: ${oldPath} -> ${newPath}`); + } + + public async cleanup(): Promise { + this.log("Cleaning up..."); + // Guard against uninitialized client (init() failed partway). + // The class field uses `!:` so TS thinks this is always defined, + // but at runtime it can be undefined when init() throws partway. + const maybeClient = this.client as SyncClient | undefined; + if (maybeClient === undefined) { + this.log("Client not initialized, nothing to clean up"); + return; + } + try { + await this.drainPendingSyncOperations(); + await withTimeout( + this.client.waitUntilFinished(), + WAIT_TIMEOUT_MS, + `Client ${this.clientId} cleanup waitUntilFinished timed out` + ); + } catch (error) { + if (error instanceof Error && error.name === "SyncResetError") { + this.log(`Cleanup interrupted by reset (expected): ${error}`); + } else { + this.log(`Cleanup waitUntilFinished failed: ${error}`); + } + } + // Surface any background sync errors that arrived after the last + // waitForSync (e.g. between the final assert-consistent and here). + // Without this, regressions that fault the engine during the very + // last step of a test would be silently swallowed. + const pendingErrors = this.syncErrors.splice(0); + await this.client.destroy(); + this.log("Cleanup complete"); + if (pendingErrors.length > 0) { + throw new Error( + `Client ${this.clientId} had ${pendingErrors.length} background sync error(s) during cleanup:\n${pendingErrors.map((e) => e.message).join("\n")}` + ); + } + } + + public override async read(path: RelativePath): Promise { + await Promise.resolve(); + return super.read(path); + } + + public override async write( + path: RelativePath, + content: Uint8Array + ): Promise { + await Promise.resolve(); + const isNew = !this.files.has(path); + await super.write(path, content); + + if (this.isSyncEnabled && isNew) { + this.enqueueSync(async () => { + this.client.syncLocallyCreatedFile(path); + }); + } + + const nextWriteRename = this.nextWriteRename; + if ( + nextWriteRename !== undefined && + nextWriteRename.oldPath === path + ) { + this.nextWriteRename = undefined; + await super.rename( + nextWriteRename.oldPath, + nextWriteRename.newPath + ); + if (this.isSyncEnabled) { + this.enqueueSync(async () => { + this.client.syncLocallyUpdatedFile({ + oldPath: nextWriteRename.oldPath, + relativePath: nextWriteRename.newPath + }); + }); + } + // The rename consumed `path`. Skip the post-update enqueue below + // — it would send a syncLocallyUpdatedFile for a path that no + // longer exists. + return; + } + + if (!this.isSyncEnabled) { + return; + } + + if (!isNew) { + this.enqueueSync(async () => { + this.client.syncLocallyUpdatedFile({ relativePath: path }); + }); + } + } + + public override async atomicUpdateText( + path: RelativePath, + updater: (current: TextWithCursors) => TextWithCursors + ): Promise { + const result = await super.atomicUpdateText(path, updater); + if (this.isSyncEnabled) { + this.enqueueSync(async () => { + this.client.syncLocallyUpdatedFile({ relativePath: path }); + }); + } + return result; + } + + public override async delete(path: RelativePath): Promise { + await super.delete(path); + if (this.isSyncEnabled) { + this.enqueueSync(async () => { + this.client.syncLocallyDeletedFile(path); + }); + } + } + + public override async rename( + oldPath: RelativePath, + newPath: RelativePath + ): Promise { + await super.rename(oldPath, newPath); + if (this.isSyncEnabled) { + this.enqueueSync(async () => { + this.client.syncLocallyUpdatedFile({ + oldPath, + relativePath: newPath + }); + }); + } + } + + private async waitForWebSocket(): Promise { + const deadline = Date.now() + WEBSOCKET_CONNECT_TIMEOUT_MS; + while (!this.client.isWebSocketConnected && Date.now() < deadline) { + await sleep(WEBSOCKET_POLL_INTERVAL_MS); + } + assert( + this.client.isWebSocketConnected, + `Client ${this.clientId} WebSocket failed to connect within ${WEBSOCKET_CONNECT_TIMEOUT_MS}ms` + ); + } + + /** + * Wait until all agent-level enqueued sync operations have completed. + * Uses a loop because completing one operation can trigger new enqueues. + */ + private async drainPendingSyncOperations(): Promise { + while (this.pendingSyncOperations.size > 0) { + await utils.awaitAll([...this.pendingSyncOperations]); + } + } + + private enqueueSync(operation: () => Promise): void { + const promise = this.executeSyncOperation(operation).catch( + (error: unknown) => { + const err = + error instanceof Error ? error : new Error(String(error)); + this.log(`Background sync failed: ${err.message}`); + this.syncErrors.push(err); + } + ); + this.pendingSyncOperations.add(promise); + void promise.finally(() => { + this.pendingSyncOperations.delete(promise); + }); + } + + private async executeSyncOperation( + operation: () => Promise + ): Promise { + try { + await operation(); + } catch (error) { + if (error instanceof Error && error.name === "SyncResetError") { + this.log(`Sync operation interrupted by reset: ${error}`); + return; + } + if ( + error instanceof Error && + error.message.includes("has been destroyed") + ) { + this.log(`Sync operation interrupted by destroy: ${error}`); + return; + } + + throw error; + } + } + + private log(message: string): void { + this.logger(`[Client ${this.clientId}] ${message}`); + } + + private wrapFetch( + fetchImplementation: typeof globalThis.fetch + ): typeof globalThis.fetch { + return async (input, init) => { + const response = await fetchImplementation(input, init); + const drop = this.nextCreateResponseDrop; + if ( + drop !== undefined && + DeterministicAgent.isCreateDocumentRequest(input, init) + ) { + this.nextCreateResponseDrop = undefined; + try { + await response.body?.cancel(); + } catch { + // Best-effort — body may already be consumed/closed. + } + drop.resolveDropped(); + throw new SyncResetError(); + } + return response; + }; + } + + private static isCreateDocumentRequest( + input: RequestInfo | URL, + init: RequestInit | undefined + ): boolean { + const method = + init?.method ?? + (typeof Request !== "undefined" && input instanceof Request + ? input.method + : "GET"); + if (method.toUpperCase() !== "POST") { + return false; + } + + const url = + input instanceof URL + ? input + : new URL(typeof input === "string" ? input : input.url); + return /\/documents\/?$/.test(url.pathname); + } +} diff --git a/frontend/deterministic-tests/src/managed-websocket.ts b/frontend/deterministic-tests/src/managed-websocket.ts new file mode 100644 index 00000000..c759891b --- /dev/null +++ b/frontend/deterministic-tests/src/managed-websocket.ts @@ -0,0 +1,245 @@ +/** + * A WebSocket wrapper that can pause and resume message delivery. + * When paused, incoming messages are buffered. When resumed, buffered + * messages are delivered in order via the onmessage handler. + * + * Member layout follows typescript-eslint default member-ordering: all + * accessor properties are declared with `declare` and wired through the + * constructor using Object.defineProperty so we don't need conflicting + * get/set accessor pairs. + */ +class ManagedWebSocket implements WebSocket { + public static readonly CONNECTING = WebSocket.CONNECTING; + public static readonly OPEN = WebSocket.OPEN; + public static readonly CLOSING = WebSocket.CLOSING; + public static readonly CLOSED = WebSocket.CLOSED; + + public readonly CONNECTING = WebSocket.CONNECTING; + public readonly OPEN = WebSocket.OPEN; + public readonly CLOSING = WebSocket.CLOSING; + public readonly CLOSED = WebSocket.CLOSED; + + declare public readonly readyState: number; + declare public readonly url: string; + declare public readonly protocol: string; + declare public readonly extensions: string; + declare public readonly bufferedAmount: number; + declare public binaryType: BinaryType; + declare public onopen: ((this: WebSocket, ev: Event) => unknown) | null; + declare public onclose: + | ((this: WebSocket, ev: CloseEvent) => unknown) + | null; + declare public onerror: ((this: WebSocket, ev: Event) => unknown) | null; + declare public onmessage: + | ((this: WebSocket, ev: MessageEvent) => unknown) + | null; + + private readonly ws: WebSocket; + private readonly bufferedMessages: MessageEvent[] = []; + private paused = false; + private externalOnMessage: ((event: MessageEvent) => unknown) | null = null; + + public constructor(url: string | URL, protocols?: string | string[]) { + this.ws = new WebSocket(url, protocols); + + const { ws } = this; + Object.defineProperties(this, { + readyState: { + get: (): number => ws.readyState, + enumerable: true, + configurable: true + }, + url: { + get: (): string => ws.url, + enumerable: true, + configurable: true + }, + protocol: { + get: (): string => ws.protocol, + enumerable: true, + configurable: true + }, + extensions: { + get: (): string => ws.extensions, + enumerable: true, + configurable: true + }, + bufferedAmount: { + get: (): number => ws.bufferedAmount, + enumerable: true, + configurable: true + }, + binaryType: { + get: (): BinaryType => ws.binaryType, + set: (v: BinaryType): void => { + ws.binaryType = v; + }, + enumerable: true, + configurable: true + }, + onopen: { + get: (): ((this: WebSocket, ev: Event) => unknown) | null => + ws.onopen, + set: ( + h: ((this: WebSocket, ev: Event) => unknown) | null + ): void => { + ws.onopen = h; + }, + enumerable: true, + configurable: true + }, + onclose: { + get: (): + | ((this: WebSocket, ev: CloseEvent) => unknown) + | null => ws.onclose, + set: ( + h: ((this: WebSocket, ev: CloseEvent) => unknown) | null + ): void => { + ws.onclose = h; + }, + enumerable: true, + configurable: true + }, + onerror: { + get: (): ((this: WebSocket, ev: Event) => unknown) | null => + ws.onerror, + set: ( + h: ((this: WebSocket, ev: Event) => unknown) | null + ): void => { + ws.onerror = h; + }, + enumerable: true, + configurable: true + }, + onmessage: { + get: (): + | ((this: WebSocket, ev: MessageEvent) => unknown) + | null => this.externalOnMessage, + set: ( + h: ((this: WebSocket, ev: MessageEvent) => unknown) | null + ): void => { + this.externalOnMessage = h; + }, + enumerable: true, + configurable: true + } + }); + + this.ws.onmessage = (event: MessageEvent): void => { + if (this.paused) { + this.bufferedMessages.push(event); + } else { + this.externalOnMessage?.(event); + } + }; + } + + public pause(): void { + this.paused = true; + } + + public resume(): void { + // Drain buffered messages BEFORE flipping `paused` to false. + // If `externalOnMessage` is async (its return type is `unknown`), + // dispatch yields control between buffered messages, and a fresh + // live `ws.onmessage` event firing during that yield would jump + // ahead of unprocessed buffered messages — silently reordering + // events relative to the wire. Keeping `paused = true` during the + // drain forces the live handler to keep buffering, so we splice + // those late arrivals onto the tail and dispatch them in order. + while (this.bufferedMessages.length > 0) { + const messages = this.bufferedMessages.splice(0); + for (const msg of messages) { + this.externalOnMessage?.(msg); + } + } + this.paused = false; + } + + public send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void { + this.ws.send(data); + } + + public close(code?: number, reason?: string): void { + this.ws.close(code, reason); + } + + public addEventListener( + ...args: Parameters + ): void { + // Only the `.onmessage` setter routes through the pause buffer. + // If sync-client ever attaches "message" listeners via + // addEventListener instead, those messages would bypass pause/resume + // and deterministic tests would silently lose their fault injection. + if (args[0] === "message") { + throw new Error( + "ManagedWebSocket: addEventListener('message') bypasses the " + + "pause buffer. Use the .onmessage setter instead, or " + + "extend ManagedWebSocket to route message listeners." + ); + } + this.ws.addEventListener(...args); + } + + public removeEventListener( + ...args: Parameters + ): void { + this.ws.removeEventListener(...args); + } + + public dispatchEvent(event: Event): boolean { + return this.ws.dispatchEvent(event); + } +} + +/** + * Factory that creates ManagedWebSocket instances and tracks them + * for pause/resume control from the test harness + */ +export class ManagedWebSocketFactory { + // Append-only: closed sockets stay tracked. Bounded per test (one + // factory per agent, each test discards its agents on cleanup), so + // not a real leak — but iterating over closed instances on + // pause/resume is a deliberate no-op since their `.onmessage` is + // already detached. + private readonly instances: ManagedWebSocket[] = []; + // Sticky pause state: applied to current instances on `pause()` AND + // to any new instance created later (e.g. WS reconnect after a + // `disable-sync` / `reset` cycle). Without this, a test pausing the + // WS before the agent reconnects would silently see the new socket + // start un-paused and miss the messages it meant to buffer. + private currentlyPaused = false; + + public get constructorFn(): typeof globalThis.WebSocket { + const trackInstance = (instance: ManagedWebSocket): void => { + this.instances.push(instance); + if (this.currentlyPaused) { + instance.pause(); + } + }; + class TrackedManagedWebSocket extends ManagedWebSocket { + public constructor( + url: string | URL, + protocols?: string | string[] + ) { + super(url, protocols); + trackInstance(this); + } + } + return TrackedManagedWebSocket; + } + + public pause(): void { + this.currentlyPaused = true; + for (const ws of this.instances) { + ws.pause(); + } + } + + public resume(): void { + this.currentlyPaused = false; + for (const ws of this.instances) { + ws.resume(); + } + } +} diff --git a/frontend/deterministic-tests/src/parse-args.ts b/frontend/deterministic-tests/src/parse-args.ts new file mode 100644 index 00000000..11c56f19 --- /dev/null +++ b/frontend/deterministic-tests/src/parse-args.ts @@ -0,0 +1,43 @@ +import * as os from "node:os"; +import { Command, InvalidArgumentError } from "commander"; + +export interface CliArgs { + filter: string | undefined; + concurrency: number; +} + +function parsePositiveInt(value: string): number { + const n = parseInt(value, 10); + if (isNaN(n) || n <= 0) { + throw new InvalidArgumentError("must be a positive integer"); + } + return n; +} + +export function parseArgs(argv: string[]): CliArgs { + const program = new Command(); + + program + .name("deterministic-tests") + .description("Scripted multi-client sync tests against a real server") + .option( + "-f, --filter ", + "Run only tests whose name contains this substring" + ) + .option( + "-j, --concurrency ", + "Number of tests to run in parallel", + parsePositiveInt, + os.cpus().length + ); + + program.parse(argv); + + /* eslint-disable @typescript-eslint/no-unsafe-type-assertion */ + const opts = program.opts(); + const filter = opts.filter as string | undefined; + const concurrency = opts.concurrency as number; + /* eslint-enable @typescript-eslint/no-unsafe-type-assertion */ + + return { filter, concurrency }; +} diff --git a/frontend/deterministic-tests/src/prefixed-logger.ts b/frontend/deterministic-tests/src/prefixed-logger.ts new file mode 100644 index 00000000..769d7545 --- /dev/null +++ b/frontend/deterministic-tests/src/prefixed-logger.ts @@ -0,0 +1,28 @@ +import { Logger } from "sync-client"; + +export class PrefixedLogger extends Logger { + private readonly base: Logger; + private readonly prefix: string; + + public constructor(base: Logger, prefix: string) { + super(); + this.base = base; + this.prefix = prefix; + } + + public override debug(message: string): void { + this.base.debug(`[${this.prefix}] ${message}`); + } + + public override info(message: string): void { + this.base.info(`[${this.prefix}] ${message}`); + } + + public override warn(message: string): void { + this.base.warn(`[${this.prefix}] ${message}`); + } + + public override error(message: string): void { + this.base.error(`[${this.prefix}] ${message}`); + } +} diff --git a/frontend/deterministic-tests/src/run-with-concurrency.ts b/frontend/deterministic-tests/src/run-with-concurrency.ts new file mode 100644 index 00000000..f5bcf745 --- /dev/null +++ b/frontend/deterministic-tests/src/run-with-concurrency.ts @@ -0,0 +1,33 @@ +export async function runWithConcurrency( + items: T[], + concurrency: number, + fn: (item: T) => Promise +): Promise { + const results: R[] = []; + const errors: unknown[] = []; + const executing = new Set>(); + + for (let i = 0; i < items.length; i++) { + const index = i; + const p = fn(items[index]) + .then((result) => { + results[index] = result; + }) + .catch((error: unknown) => { + errors.push(error); + }) + .finally(() => executing.delete(p)); + executing.add(p); + if (executing.size >= concurrency) { + await Promise.race(executing); + } + } + + // eslint-disable-next-line no-restricted-properties + await Promise.all(executing); + + if (errors.length > 0) { + throw errors[0]; + } + return results; +} diff --git a/frontend/deterministic-tests/src/server-control.ts b/frontend/deterministic-tests/src/server-control.ts new file mode 100644 index 00000000..9cb4cde0 --- /dev/null +++ b/frontend/deterministic-tests/src/server-control.ts @@ -0,0 +1,296 @@ +import { spawn, type ChildProcess } from "node:child_process"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { sleep } from "./utils/sleep"; +import { findFreePort } from "./utils/find-free-port"; +import type { Logger } from "sync-client"; +import { + STOP_TIMEOUT_MS, + SERVER_READY_POLL_INTERVAL_MS, + SERVER_READY_MAX_ATTEMPTS, + SERVER_START_MAX_ATTEMPTS +} from "./consts"; + +export class ServerControl { + private process: ChildProcess | null = null; + private readonly serverPath: string; + private readonly baseConfigPath: string; + private readonly logger: Logger; + private _port: number | undefined; + private tempDir: string | undefined; + private _isPaused = false; + + public constructor(serverPath: string, configPath: string, logger: Logger) { + this.serverPath = serverPath; + this.baseConfigPath = configPath; + this.logger = logger; + } + + public get port(): number { + if (this._port === undefined) { + throw new Error("Server has not been started yet"); + } + return this._port; + } + + public get remoteUri(): string { + return `http://localhost:${this.port}`; + } + + public async start(): Promise { + if (this.process !== null) { + throw new Error("Server is already running"); + } + + // Retry on bind failure: findFreePort closes its probe before we + // spawn, so under heavy parallelism another process can grab the + // same port. Each attempt picks a fresh port. + let lastError: unknown; + for (let attempt = 1; attempt <= SERVER_START_MAX_ATTEMPTS; attempt++) { + try { + await this.startOnce(); + return; + } catch (error) { + lastError = error; + this.logger.warn( + `Server start attempt ${attempt}/${SERVER_START_MAX_ATTEMPTS} failed: ${error instanceof Error ? error.message : String(error)}` + ); + // startOnce already cleaned up its child + tempdir on failure. + } + } + throw new Error( + `Server failed to start after ${SERVER_START_MAX_ATTEMPTS} attempts: ${lastError instanceof Error ? lastError.message : String(lastError)}`, + { cause: lastError instanceof Error ? lastError : undefined } + ); + } + + private async startOnce(): Promise { + const reservation = await findFreePort(); + this._port = reservation.port; + const tmpBase = os.tmpdir(); + this.tempDir = fs.mkdtempSync(path.join(tmpBase, "vault-link-test-")); + const tempConfigPath = path.join(this.tempDir, "config.yml"); + const dbDir = path.join(this.tempDir, "databases"); + + this.writeConfigFile(tempConfigPath, dbDir); + + this.logger.info( + `Starting server: ${this.serverPath} (port ${this._port})` + ); + + // Release the port reservation right before spawning to minimize + // the TOCTOU window between port discovery and server binding. + reservation.release(); + + this.process = spawn(this.serverPath, [tempConfigPath], { + stdio: ["ignore", "pipe", "pipe"], + detached: false + }); + + this.process.stdout?.on("data", (data: Buffer) => { + this.logger.info(`[SERVER] ${data.toString().trim()}`); + }); + + this.process.stderr?.on("data", (data: Buffer) => { + this.logger.info(`[SERVER] ${data.toString().trim()}`); + }); + + this.process.on("error", (err) => { + this.logger.error(`[SERVER] Process error: ${err.message}`); + }); + + const currentProcess = this.process; + currentProcess.on("exit", (code, signal) => { + this.logger.info( + `Server exited with code ${code}, signal ${signal}` + ); + // Only clear state if this handler is for the current process. + // A fast stop→start cycle could create a new process before this + // handler fires — clearing state here would corrupt the new one. + if (this.process === currentProcess) { + this.process = null; + this._isPaused = false; + } + }); + + try { + await this.waitForReady(); + } catch (error) { + // Kill the spawned process if it failed to become ready, + // preventing a zombie process from lingering. + try { + await this.stop(); + } catch { + // Best-effort cleanup + } + throw error; + } + } + + public async waitForReady( + maxAttempts: number = SERVER_READY_MAX_ATTEMPTS + ): Promise { + const pingUrl = `${this.remoteUri}/vaults/test/ping`; + for (let i = 0; i < maxAttempts; i++) { + if (this.process?.exitCode !== null) { + throw new Error( + "Server process died while waiting for it to become ready" + ); + } + try { + const response = await fetch(pingUrl); + if (response.ok) { + this.logger.info("[SERVER] Ready"); + return; + } + } catch { + // Server not ready yet, continue polling + } + await sleep(SERVER_READY_POLL_INTERVAL_MS); + } + throw new Error("Server failed to start within timeout"); + } + + public pause(): void { + if (this.process?.pid === undefined) { + throw new Error("Server is not running"); + } + if (this._isPaused) { + this.logger.warn("Server is already paused, skipping double-pause"); + return; + } + this.logger.info("Server pausing..."); + try { + process.kill(this.process.pid, "SIGSTOP"); + this._isPaused = true; + this.logger.info("Server paused (SIGSTOP sent)"); + } catch (error) { + throw new Error( + `Failed to pause server (pid ${this.process.pid}): ${error instanceof Error ? error.message : String(error)}` + ); + } + } + + public resume(): void { + if (this.process?.pid === undefined) { + throw new Error("Server is not running"); + } + if (!this._isPaused) { + return; + } + this.logger.info("Server resuming..."); + try { + process.kill(this.process.pid, "SIGCONT"); + this._isPaused = false; + this.logger.info("Server resumed (SIGCONT sent)"); + } catch (error) { + throw new Error( + `Failed to resume server (pid ${this.process.pid}): ${error instanceof Error ? error.message : String(error)}` + ); + } + } + + public async stop(): Promise { + const proc = this.process; + if (proc?.pid === undefined) { + this.cleanupTempDir(); + return; + } + + // Resume if paused — a SIGSTOP'd process ignores SIGKILL + if (this._isPaused) { + try { + process.kill(proc.pid, "SIGCONT"); + } catch { + // Process may already be gone + } + this._isPaused = false; + } + + this.logger.info("Server stopping..."); + + // Set up a promise that resolves when the process actually exits. + const exitPromise = new Promise((resolve) => { + if (proc.exitCode !== null) { + resolve(); + return; + } + proc.on("exit", () => { + resolve(); + }); + }); + + try { + process.kill(proc.pid, "SIGKILL"); + } catch { + // Process already gone + } + + // Wait for the process to actually exit before cleaning up, + // with a 5s safety timeout to avoid hanging forever. + await Promise.race([exitPromise, sleep(STOP_TIMEOUT_MS)]); + + this.process = null; + this._isPaused = false; + this.cleanupTempDir(); + } + + public isRunning(): boolean { + const proc = this.process; + return ( + proc !== null && + proc.pid !== undefined && + proc.exitCode === null && + proc.signalCode === null + ); + } + + /** + * Synchronously SIGCONT-then-SIGKILL the child process. Safe to call + * from a `process.on("exit", ...)` handler, where async work cannot + * run. Used as a last-resort cleanup so a SIGSTOP'd server doesn't + * outlive the test runner and wedge the next CI invocation. + */ + public forceKillSync(): void { + const proc = this.process; + if (proc?.pid === undefined) { + return; + } + try { + process.kill(proc.pid, "SIGCONT"); + } catch { + // Process may already be gone or never paused. + } + try { + process.kill(proc.pid, "SIGKILL"); + } catch { + // Process already gone. + } + } + + private writeConfigFile(destPath: string, dbDir: string): void { + // Assumes config-e2e.yml has exactly one 2-space-indented `port:` and + // one `databases_directory_path:` (under `server:` and `database:` + // respectively) + const baseConfig = fs.readFileSync(this.baseConfigPath, "utf-8"); + const config = baseConfig + .replace(/^\s*port:\s*\d+/m, ` port: ${this._port}`) + .replace( + /^\s*databases_directory_path:\s*.+/m, + ` databases_directory_path: ${dbDir}` + ); + fs.writeFileSync(destPath, config); + } + + private cleanupTempDir(): void { + if (this.tempDir !== undefined) { + try { + fs.rmSync(this.tempDir, { recursive: true, force: true }); + } catch { + // Best-effort cleanup + } + this.tempDir = undefined; + } + } +} diff --git a/frontend/deterministic-tests/src/server-manager.ts b/frontend/deterministic-tests/src/server-manager.ts new file mode 100644 index 00000000..76c624f7 --- /dev/null +++ b/frontend/deterministic-tests/src/server-manager.ts @@ -0,0 +1,71 @@ +import type { ServerControl } from "./server-control"; +import type { Logger } from "sync-client"; + +export class ServerManager { + private readonly activeServers = new Set(); + private readonly logger: Logger; + private isShuttingDown = false; + + public constructor(logger: Logger) { + this.logger = logger; + } + + public track(server: ServerControl): void { + this.activeServers.add(server); + } + + public untrack(server: ServerControl): void { + this.activeServers.delete(server); + } + + public async stopAll(): Promise { + if (this.isShuttingDown) { + return; + } + this.isShuttingDown = true; + + const servers = Array.from(this.activeServers); + // eslint-disable-next-line no-restricted-properties + await Promise.all( + servers.map(async (server) => { + try { + await server.stop(); + } catch { + // Best-effort cleanup during shutdown + } + }) + ); + } + + public installSignalHandlers(): void { + process.on("SIGINT", () => { + this.logger.info("Received SIGINT, shutting down..."); + void this.stopAll() + .catch(() => { + /* no-op */ + }) + .then(() => process.exit(130)); + }); + + process.on("SIGTERM", () => { + this.logger.info("Received SIGTERM, shutting down..."); + void this.stopAll() + .catch(() => { + /* no-op */ + }) + .then(() => process.exit(143)); + }); + + // Last-resort synchronous cleanup. Runs even when the process is + // exiting via process.exit() from unhandledRejection / + // uncaughtException — paths where async stopAll() cannot complete. + // SIGSTOP'd servers MUST receive SIGCONT before SIGKILL or the + // kernel keeps them as zombies holding the test's tmpdir, and the + // next CI run can't reuse the port. + process.on("exit", () => { + for (const server of this.activeServers) { + server.forceKillSync(); + } + }); + } +} diff --git a/frontend/deterministic-tests/src/test-definition.ts b/frontend/deterministic-tests/src/test-definition.ts new file mode 100644 index 00000000..bd832a50 --- /dev/null +++ b/frontend/deterministic-tests/src/test-definition.ts @@ -0,0 +1,49 @@ +import type { AssertableState } from "./utils/assertable-state"; + +export interface ClientState { + files: Map; + clientFiles: Map[]; +} + +export type TestStep = + | { type: "create"; client: number; path: string; content: string } + | { type: "update"; client: number; path: string; content: string } + | { type: "rename"; client: number; oldPath: string; newPath: string } + | { + type: "rename-next-write"; + client: number; + oldPath: string; + newPath: string; + } + | { type: "delete"; client: number; path: string } + | { type: "sync"; client?: number } + | { type: "disable-sync"; client: number } + | { type: "enable-sync"; client: number } + | { type: "pause-server" } + | { type: "resume-server" } + | { + type: "resume-server-until-history-then-pause"; + client: number; + syncType: "CREATE" | "UPDATE" | "DELETE"; + path: string; + } + | { type: "barrier" } + | { type: "assert-consistent"; verify?: (state: AssertableState) => void } + | { type: "pause-websocket"; client: number } + | { type: "resume-websocket"; client: number } + | { type: "drop-next-create-response"; client: number } + | { type: "wait-for-dropped-create-response"; client: number } + | { type: "sleep"; ms: number } + | { type: "reset"; client: number }; + +export interface TestDefinition { + description?: string; + clients: number; + steps: TestStep[]; +} + +export interface TestResult { + success: boolean; + error?: string; + duration?: number; +} diff --git a/frontend/deterministic-tests/src/test-registry.ts b/frontend/deterministic-tests/src/test-registry.ts new file mode 100644 index 00000000..1a07b411 --- /dev/null +++ b/frontend/deterministic-tests/src/test-registry.ts @@ -0,0 +1,245 @@ +import type { TestDefinition } from "./test-definition"; +import { renameCreateConflictTest } from "./tests/rename-create-conflict.test"; +import { renameChainTest } from "./tests/rename-chain.test"; +import { renameUpdateConflictTest } from "./tests/rename-update-conflict.test"; +import { deleteRenameConflictTest } from "./tests/delete-rename-conflict.test"; +import { multiFileOperationsTest } from "./tests/multi-file-operations.test"; +import { deleteRecreateSamePathTest } from "./tests/delete-recreate-same-path.test"; +import { offlineRenameAndEditTest } from "./tests/offline-rename-and-edit.test"; +import { simultaneousCreateDeleteSamePathTest } from "./tests/simultaneous-create-delete-same-path.test"; +import { idempotencyAfterServerPauseTest } from "./tests/idempotency-after-server-pause.test"; +import { sequentialCreateDuplicateContentTest } from "./tests/sequential-create-duplicate-content.test"; +import { mcThreeClientRenameOfflineUpdateTest } from "./tests/mc-three-client-rename-offline-update.test"; +import { mcMultiDeleteOfflineRenameTest } from "./tests/mc-multi-delete-offline-rename.test"; +import { mcCrossCreateRenameSameTargetTest } from "./tests/mc-cross-create-rename-same-target.test"; +import { mcDeleteThenOfflineRenameTest } from "./tests/mc-delete-then-offline-rename.test"; +import { offlineMixedOperationsTest } from "./tests/offline-mixed-operations.test"; +import { offlineConcurrentRenamesTest } from "./tests/offline-concurrent-renames.test"; +import { offlineMultipleEditsTest } from "./tests/offline-multiple-edits.test"; +import { serverPauseBothClientsCreateTest } from "./tests/server-pause-both-clients-create.test"; +import { serverPauseUpdateAndCreateTest } from "./tests/server-pause-update-and-create.test"; +import { renameSwapTest } from "./tests/rename-swap.test"; +import { renameCircularTest } from "./tests/rename-circular.test"; +import { renameRoundtripTest } from "./tests/rename-roundtrip.test"; +import { offlineRenameRemoteCreateOldPathTest } from "./tests/offline-rename-remote-create-old-path.test"; +import { offlineEditRemoteRenameTest } from "./tests/offline-edit-remote-rename.test"; +import { renameChainThenDeleteTest } from "./tests/rename-chain-then-delete.test"; +import { offlineDeleteRemoteRenameTest } from "./tests/offline-delete-remote-rename.test"; +import { overlappingEditsSameSectionTest } from "./tests/overlapping-edits-same-section.test"; +import { rapidUpdatesAfterMergeTest } from "./tests/rapid-updates-after-merge.test"; +import { deleteRecreateConcurrentUpdateTest } from "./tests/delete-recreate-concurrent-update.test"; +import { moveAndConcurrentRemoteUpdateTest } from "./tests/move-and-concurrent-remote-update.test"; +import { offlineDeleteVsRemoteUpdateTest } from "./tests/offline-delete-vs-remote-update.test"; +import { doubleOfflineCycleTest } from "./tests/double-offline-cycle.test"; +import { serverPauseRenameEditResumeTest } from "./tests/server-pause-rename-edit-resume.test"; +import { offlineUpdateBothThenDeleteOneTest } from "./tests/offline-update-both-then-delete-one.test"; +import { offlineCreateSamePathMergeableTest } from "./tests/offline-create-same-path-mergeable.test"; +import { deleteDuringPendingCreateTest } from "./tests/delete-during-pending-create.test"; +import { threeClientRenameCreateDeleteTest } from "./tests/three-client-rename-create-delete.test"; +import { renameToPathOfUnconfirmedDeleteTest } from "./tests/rename-to-path-of-unconfirmed-delete.test"; +import { offlineEditThenMoveSameContentTest } from "./tests/offline-edit-then-move-same-content.test"; +import { rapidCreateUpdateDeleteCycleTest } from "./tests/rapid-create-update-delete-cycle.test"; +import { serverPauseBothEditSameFileTest } from "./tests/server-pause-both-edit-same-file.test"; +import { deleteRecreateDifferentContentTest } from "./tests/delete-recreate-different-content.test"; +import { updateDuringCreateProcessingTest } from "./tests/update-during-create-processing.test"; +import { offlineMoveThenRemoteDeleteTest } from "./tests/offline-move-then-remote-delete.test"; +import { resetClearsRecentlyDeletedResurrectionTest } from "./tests/reset-clears-recently-deleted-resurrection.test"; +import { moveThenDeleteStalePathTest } from "./tests/move-then-delete-stale-path.test"; +import { interruptedDeleteRetryTest } from "./tests/interrupted-delete-retry.test"; +import { updateDoesNotSurviveRemoteDeleteTest } from "./tests/update-does-not-survive-remote-delete.test"; +import { movePreservesRemoteUpdateTest } from "./tests/move-preserves-remote-update.test"; +import { recentlyDeletedClearedOnReconnectTest } from "./tests/recently-deleted-cleared-on-reconnect.test"; +import { watermarkAdvancesOnSkipTest } from "./tests/watermark-advances-on-skip.test"; +import { watermarkGapRemoteUpdateNotRecordedTest } from "./tests/watermark-gap-remote-update-not-recorded.test"; +import { queueResetLosesCoalescedLocalEditTest } from "./tests/queue-reset-loses-coalesced-local-edit.test"; +import { renameToPendingPathFallbackTest } from "./tests/rename-to-pending-path-fallback.test"; +import { moveRemoteUpdateRevertsRenameTest } from "./tests/move-remote-update-reverts-rename.test"; +import { localEditLostDuringCreateMergeTest } from "./tests/local-edit-lost-during-create-merge.test"; +import { renamePendingCreateBeforeResponseTest } from "./tests/rename-pending-create-before-response.test"; +import { createRenameResponseSkipsFileTest } from "./tests/create-rename-response-skips-file.test"; +import { onlineCreateRenameConcurrentCreateOrphanTest } from "./tests/online-create-rename-concurrent-create-orphan.test"; +import { concurrentRenameFirstWinsTest } from "./tests/concurrent-rename-first-wins.test"; +import { binaryToTextTransitionTest } from "./tests/binary-to-text-transition.test"; +import { textPendingCreateNotDisplacedTest } from "./tests/text-pending-create-not-displaced.test"; +import { binaryPendingCreateNotDisplacedTest } from "./tests/binary-pending-create-not-displaced.test"; +import { coalesceUpdateRemoteUpdateDataLossTest } from "./tests/coalesce-update-remote-update-data-loss.test"; +import { coalescedRemoteUpdateWatermarkLossTest } from "./tests/coalesced-remote-update-watermark-loss.test"; +import { concurrentDeleteDuringRemoteUpdateTest } from "./tests/concurrent-delete-during-remote-update.test"; +import { concurrentEditExactSamePositionTest } from "./tests/concurrent-edit-exact-same-position.test"; +import { concurrentRenameAndCreateAtTargetRenameFirstTest } from "./tests/concurrent-rename-and-create-at-target-rename-first.test"; +import { concurrentRenameAndCreateAtTargetCreateFirstTest } from "./tests/concurrent-rename-and-create-at-target-create-first.test"; +import { concurrentRenameSameTargetTest } from "./tests/concurrent-rename-same-target.test"; +import { concurrentUpdateDiffConsistencyTest } from "./tests/concurrent-update-diff-consistency.test"; +import { userParenthesizedFileNotDeletedTest } from "./tests/user-parenthesized-file-not-deleted.test"; +import { createDeleteNoopTest } from "./tests/create-delete-noop.test"; +import { createMergeDeleteTest } from "./tests/create-merge-delete.test"; +import { moveIdenticalContentAmbiguityTest } from "./tests/move-identical-content-ambiguity.test"; +import { createUpdateCoalesceServerPauseTest } from "./tests/create-update-coalesce-server-pause.test"; +import { createDuringReconciliationTest } from "./tests/create-during-reconciliation.test"; +import { createMergePreservesRenamedUpdateTest } from "./tests/create-merge-preserves-renamed-update.test"; +import { createRenameCreateSamePathTest } from "./tests/create-rename-create-same-path.test"; +import { moveChainThreeFilesTest } from "./tests/move-chain-three-files.test"; +import { deleteByOtherClientThenRecreateTest } from "./tests/delete-by-other-client-then-recreate.test"; +import { onlineDeleteRecreateRapidCycleTest } from "./tests/online-delete-recreate-rapid-cycle.test"; +import { onlineEditVsDeleteConvergenceTest } from "./tests/online-edit-vs-delete-convergence.test"; +import { rapidEditDeleteOnlineConvergenceTest } from "./tests/rapid-edit-delete-online-convergence.test"; +import { serverPauseDeleteRecreateTest } from "./tests/server-pause-delete-recreate.test"; +import { onlineBothCreateSamePathDeconflictTest } from "./tests/online-both-create-same-path-deconflict.test"; +import { onlineCreateUpdateWhileOtherCreatesSamePathTest } from "./tests/online-create-update-while-other-creates-same-path.test"; +import { displacedFileNotMarkedDeletedTest } from "./tests/displaced-file-not-marked-deleted.test"; +import { remoteUpdateResurrectsDeletedDocTest } from "./tests/remote-update-resurrects-deleted-doc.test"; +import { localUpdateSurvivesRemoteRenameTest } from "./tests/local-update-survives-remote-rename.test"; +import { mergingUpdateResponseSurvivesUserRenameTest } from "./tests/merging-update-response-survives-user-rename.test"; +import { catchupCreateAndUpdateNotSkippedTest } from "./tests/catchup-create-and-update-not-skipped.test"; +import { localRenameSurvivesRemoteRenameTest } from "./tests/local-rename-survives-remote-rename.test"; +import { renameChainDuringPendingCreateTest } from "./tests/rename-chain-during-pending-create.test"; +import { remoteRenameCollidesWithPendingLocalCreateTest } from "./tests/remote-rename-collides-with-pending-local-create.test"; +import { remoteUpdateSurvivesUserRenameTest } from "./tests/remote-update-survives-user-rename.test"; +import { sameDocIdCollapseOnLocalCreateAfterRemoteCreateTest } from "./tests/same-doc-id-collapse-on-local-create-after-remote-create.test"; +import { sameDocIdCollapseAfterRemoteQuickWriteAndPendingRenameTest } from "./tests/same-doc-id-collapse-after-remote-quick-write-and-pending-rename.test"; +import { renameOverwritesPendingCreateThenDeleteTest } from "./tests/rename-overwrites-pending-create-then-delete.test"; +import { deleteRecreatedPendingCreateWithStaleDeletingRecordTest } from "./tests/delete-recreated-pending-create-with-stale-deleting-record.test"; +import { queuedCreateDeleteDoesNotHijackReusedPathTest } from "./tests/queued-create-delete-does-not-hijack-reused-path.test"; +import { renamedPendingCreateReusedPathThenDeleteTest } from "./tests/renamed-pending-create-reused-path-then-delete.test"; +import { renamePendingCreateOntoPendingDeletePathTest } from "./tests/rename-pending-create-onto-pending-delete-path.test"; +import { remoteQuickWriteRenameBeforeRecordTest } from "./tests/remote-quick-write-rename-before-record.test"; +import { selfMergePendingRenameAliasesSecondCreateTest } from "./tests/self-merge-pending-rename-aliases-second-create.test"; + +export const TESTS: Partial> = { + "rename-create-conflict": renameCreateConflictTest, + "rename-chain": renameChainTest, + "rename-update-conflict": renameUpdateConflictTest, + "delete-rename-conflict": deleteRenameConflictTest, + "multi-file-operations": multiFileOperationsTest, + "delete-recreate-same-path": deleteRecreateSamePathTest, + "offline-rename-and-edit": offlineRenameAndEditTest, + "simultaneous-create-delete-same-path": + simultaneousCreateDeleteSamePathTest, + "idempotency-after-server-pause": idempotencyAfterServerPauseTest, + "sequential-create-duplicate-content": sequentialCreateDuplicateContentTest, + "mc-three-client-rename-offline-update": + mcThreeClientRenameOfflineUpdateTest, + "mc-multi-delete-offline-rename": mcMultiDeleteOfflineRenameTest, + "mc-cross-create-rename-same-target": mcCrossCreateRenameSameTargetTest, + "mc-delete-then-offline-rename": mcDeleteThenOfflineRenameTest, + "offline-mixed-operations": offlineMixedOperationsTest, + "offline-concurrent-renames": offlineConcurrentRenamesTest, + "offline-multiple-edits": offlineMultipleEditsTest, + "server-pause-both-clients-create": serverPauseBothClientsCreateTest, + "server-pause-update-and-create": serverPauseUpdateAndCreateTest, + "rename-swap": renameSwapTest, + "rename-circular": renameCircularTest, + "rename-roundtrip": renameRoundtripTest, + "offline-rename-remote-create-old-path": + offlineRenameRemoteCreateOldPathTest, + "offline-edit-remote-rename": offlineEditRemoteRenameTest, + "rename-chain-then-delete": renameChainThenDeleteTest, + "offline-delete-remote-rename": offlineDeleteRemoteRenameTest, + "overlapping-edits-same-section": overlappingEditsSameSectionTest, + "rapid-updates-after-merge": rapidUpdatesAfterMergeTest, + "delete-recreate-concurrent-update": deleteRecreateConcurrentUpdateTest, + "move-and-concurrent-remote-update": moveAndConcurrentRemoteUpdateTest, + "double-offline-cycle": doubleOfflineCycleTest, + "server-pause-rename-edit-resume": serverPauseRenameEditResumeTest, + "offline-update-both-then-delete-one": offlineUpdateBothThenDeleteOneTest, + "offline-create-same-path-mergeable": offlineCreateSamePathMergeableTest, + "delete-during-pending-create": deleteDuringPendingCreateTest, + "three-client-rename-create-delete": threeClientRenameCreateDeleteTest, + "rename-to-path-of-unconfirmed-delete": renameToPathOfUnconfirmedDeleteTest, + "offline-edit-then-move-same-content": offlineEditThenMoveSameContentTest, + "rapid-create-update-delete-cycle": rapidCreateUpdateDeleteCycleTest, + "server-pause-both-edit-same-file": serverPauseBothEditSameFileTest, + "delete-recreate-different-content": deleteRecreateDifferentContentTest, + "update-during-create-processing": updateDuringCreateProcessingTest, + "offline-move-then-remote-delete": offlineMoveThenRemoteDeleteTest, + "reset-clears-recently-deleted-resurrection": + resetClearsRecentlyDeletedResurrectionTest, + "move-then-delete-stale-path": moveThenDeleteStalePathTest, + "offline-delete-vs-remote-update": offlineDeleteVsRemoteUpdateTest, + "interrupted-delete-retry": interruptedDeleteRetryTest, + "update-does-not-survive-remote-delete": updateDoesNotSurviveRemoteDeleteTest, + "move-preserves-remote-update": movePreservesRemoteUpdateTest, + "recently-deleted-cleared-on-reconnect": + recentlyDeletedClearedOnReconnectTest, + "watermark-advances-on-skip": watermarkAdvancesOnSkipTest, + "watermark-gap-remote-update-not-recorded": + watermarkGapRemoteUpdateNotRecordedTest, + "queue-reset-loses-coalesced-local-edit": + queueResetLosesCoalescedLocalEditTest, + "rename-to-pending-path-fallback": renameToPendingPathFallbackTest, + "move-remote-update-reverts-rename": moveRemoteUpdateRevertsRenameTest, + "local-edit-lost-during-create-merge": localEditLostDuringCreateMergeTest, + "rename-pending-create-before-response": + renamePendingCreateBeforeResponseTest, + "create-rename-response-skips-file": createRenameResponseSkipsFileTest, + "online-create-rename-concurrent-create-orphan": + onlineCreateRenameConcurrentCreateOrphanTest, + "concurrent-rename-first-wins": concurrentRenameFirstWinsTest, + "binary-to-text-transition": binaryToTextTransitionTest, + "text-pending-create-not-displaced": textPendingCreateNotDisplacedTest, + "binary-pending-create-not-displaced": binaryPendingCreateNotDisplacedTest, + "coalesce-update-remote-update-data-loss": + coalesceUpdateRemoteUpdateDataLossTest, + "coalesced-remote-update-watermark-loss": + coalescedRemoteUpdateWatermarkLossTest, + "concurrent-delete-during-remote-update": + concurrentDeleteDuringRemoteUpdateTest, + "concurrent-edit-exact-same-position": concurrentEditExactSamePositionTest, + "concurrent-rename-and-create-at-target-rename-first": + concurrentRenameAndCreateAtTargetRenameFirstTest, + "concurrent-rename-and-create-at-target-create-first": + concurrentRenameAndCreateAtTargetCreateFirstTest, + "concurrent-rename-same-target": concurrentRenameSameTargetTest, + "concurrent-update-diff-consistency": concurrentUpdateDiffConsistencyTest, + "user-parenthesized-file-not-deleted": userParenthesizedFileNotDeletedTest, + "create-delete-noop": createDeleteNoopTest, + "create-merge-delete": createMergeDeleteTest, + "move-identical-content-ambiguity": moveIdenticalContentAmbiguityTest, + "create-update-coalesce-server-pause": createUpdateCoalesceServerPauseTest, + "create-during-reconciliation": createDuringReconciliationTest, + "create-merge-preserves-renamed-update": + createMergePreservesRenamedUpdateTest, + "create-rename-create-same-path": createRenameCreateSamePathTest, + "move-chain-three-files": moveChainThreeFilesTest, + "delete-by-other-client-then-recreate": deleteByOtherClientThenRecreateTest, + "online-delete-recreate-rapid-cycle": onlineDeleteRecreateRapidCycleTest, + "online-edit-vs-delete-convergence": onlineEditVsDeleteConvergenceTest, + "rapid-edit-delete-online-convergence": + rapidEditDeleteOnlineConvergenceTest, + "server-pause-delete-recreate": serverPauseDeleteRecreateTest, + "online-both-create-same-path-deconflict": + onlineBothCreateSamePathDeconflictTest, + "online-create-update-while-other-creates-same-path": + onlineCreateUpdateWhileOtherCreatesSamePathTest, + "displaced-file-not-marked-deleted": displacedFileNotMarkedDeletedTest, + "remote-update-resurrects-deleted-doc": + remoteUpdateResurrectsDeletedDocTest, + "local-update-survives-remote-rename": localUpdateSurvivesRemoteRenameTest, + "merging-update-response-survives-user-rename": + mergingUpdateResponseSurvivesUserRenameTest, + "catchup-create-and-update-not-skipped": + catchupCreateAndUpdateNotSkippedTest, + "local-rename-survives-remote-rename": localRenameSurvivesRemoteRenameTest, + "rename-chain-during-pending-create": renameChainDuringPendingCreateTest, + "remote-rename-collides-with-pending-local-create": + remoteRenameCollidesWithPendingLocalCreateTest, + "remote-update-survives-user-rename": remoteUpdateSurvivesUserRenameTest, + "same-doc-id-collapse-on-local-create-after-remote-create": + sameDocIdCollapseOnLocalCreateAfterRemoteCreateTest, + "renamed-pending-create-reused-path-then-delete": + renamedPendingCreateReusedPathThenDeleteTest, + "rename-pending-create-onto-pending-delete-path": + renamePendingCreateOntoPendingDeletePathTest, + "rename-overwrites-pending-create-then-delete": + renameOverwritesPendingCreateThenDeleteTest, + "same-doc-id-collapse-after-remote-quick-write-and-pending-rename": + sameDocIdCollapseAfterRemoteQuickWriteAndPendingRenameTest, + "delete-recreated-pending-create-with-stale-deleting-record": + deleteRecreatedPendingCreateWithStaleDeletingRecordTest, + "queued-create-delete-does-not-hijack-reused-path": + queuedCreateDeleteDoesNotHijackReusedPathTest, + "remote-quick-write-rename-before-record": + remoteQuickWriteRenameBeforeRecordTest, + "self-merge-pending-rename-aliases-second-create": + selfMergePendingRenameAliasesSecondCreateTest +}; diff --git a/frontend/deterministic-tests/src/test-runner.ts b/frontend/deterministic-tests/src/test-runner.ts new file mode 100644 index 00000000..411e9b08 --- /dev/null +++ b/frontend/deterministic-tests/src/test-runner.ts @@ -0,0 +1,399 @@ +import type { TestDefinition, TestResult, TestStep } from "./test-definition"; +import { DeterministicAgent } from "./deterministic-agent"; +import type { ServerControl } from "./server-control"; +import type { SyncSettings, Logger } from "sync-client"; +import { assert } from "./utils/assert"; +import { AssertableState } from "./utils/assertable-state"; +import { sleep } from "./utils/sleep"; +import { withTimeout } from "./utils/with-timeout"; +import { + CONVERGENCE_TIMEOUT_MS, + CONVERGENCE_RETRY_DELAY_MS, + AGENT_INIT_TIMEOUT_MS, + IS_SYNC_ENABLED_BY_DEFAULT +} from "./consts"; +import { randomUUID } from "node:crypto"; + +export class TestRunner { + private agents: DeterministicAgent[] = []; + private readonly serverControl: ServerControl; + private readonly token: string; + private readonly remoteUri: string; + private readonly logger: Logger; + + public constructor( + serverControl: ServerControl, + logger: Logger, + token: string, + remoteUri: string + ) { + this.serverControl = serverControl; + this.logger = logger; + this.token = token; + this.remoteUri = remoteUri; + } + + public async runTest( + name: string, + test: TestDefinition + ): Promise { + const startTime = Date.now(); + this.logger.info(`Running test: ${name}`); + if (test.description !== undefined && test.description !== "") { + this.logger.info(`Description: ${test.description}`); + } + this.logger.info(`Clients: ${test.clients}`); + this.logger.info(`Steps: ${test.steps.length}`); + + try { + assert( + this.serverControl.isRunning(), + "Server is not running before test start" + ); + + await this.initializeAgents(test.clients); + + for (let i = 0; i < test.steps.length; i++) { + const step = test.steps[i]; + this.logger.info( + `Step ${i + 1}/${test.steps.length}: ${JSON.stringify(step)}` + ); + await this.executeStep(step); + } + + await this.cleanup(); + + const duration = Date.now() - startTime; + this.logger.info(`\n✓ Test passed: ${name} (${duration}ms)`); + + return { + success: true, + duration + }; + } catch (error) { + const duration = Date.now() - startTime; + const errorMessage = + error instanceof Error ? error.message : String(error); + this.logger.info(`\n✗ Test failed: ${name}`); + this.logger.info(`Error: ${errorMessage}`); + + await this.cleanup(); + + return { + success: false, + error: errorMessage, + duration + }; + } + } + + private async initializeAgents(count: number): Promise { + assert(count > 0, `Client count must be positive, got ${count}`); + const vaultName = `test-${randomUUID()}`; + this.logger.info( + `Initializing ${count} agents with vault: ${vaultName}` + ); + + for (let i = 0; i < count; i++) { + const settings: Partial = { + isSyncEnabled: IS_SYNC_ENABLED_BY_DEFAULT, + token: this.token, + vaultName, + remoteUri: this.remoteUri + }; + + const agent = new DeterministicAgent(i, settings, (msg) => { + this.logger.info(msg); + }); + + // Push before init so cleanup() handles this agent if init fails + this.agents.push(agent); + await withTimeout( + agent.init(fetch), + AGENT_INIT_TIMEOUT_MS, + `Client ${i} init timed out after ${AGENT_INIT_TIMEOUT_MS}ms` + ); + this.logger.info(`Initialized client ${i}`); + } + + this.logger.info("All agents initialized"); + } + + private getAgent(index: number): DeterministicAgent { + assert( + index >= 0 && index < this.agents.length, + `Client index ${index} out of bounds (have ${this.agents.length} agents)` + ); + return this.agents[index]; + } + + private async executeStep(step: TestStep): Promise { + switch (step.type) { + case "create": + case "update": + await this.getAgent(step.client).write( + step.path, + new TextEncoder().encode(step.content) + ); + break; + + case "rename": + await this.getAgent(step.client).rename( + step.oldPath, + step.newPath + ); + break; + + case "rename-next-write": + this.getAgent(step.client).renameNextWrite( + step.oldPath, + step.newPath + ); + break; + + case "delete": + await this.getAgent(step.client).delete(step.path); + break; + + case "sync": + if (step.client !== undefined) { + await this.getAgent(step.client).waitForSync(); + } else { + for (const agent of this.agents) { + await agent.waitForSync(); + } + } + break; + + case "disable-sync": + await this.getAgent(step.client).disableSync(); + break; + + case "enable-sync": + await this.getAgent(step.client).enableSync(); + break; + + case "pause-server": + this.serverControl.pause(); + break; + + case "resume-server": + this.serverControl.resume(); + // Verify the server is actually responsive before proceeding. + // This replaces relying solely on hardcoded waits. + await this.serverControl.waitForReady(); + break; + + case "resume-server-until-history-then-pause": { + const agent = this.getAgent(step.client); + const historySeen = agent.waitForHistoryEntry( + (entry) => + entry.details.type === step.syncType && + entry.details.relativePath === step.path, + () => this.serverControl.pause() + ); + this.serverControl.resume(); + await historySeen; + break; + } + + case "barrier": + await this.waitForConvergence(); + break; + + case "assert-consistent": + await this.assertConsistent(step.verify); + break; + + case "pause-websocket": + this.getAgent(step.client).pauseWebSocket(); + break; + + case "resume-websocket": + this.getAgent(step.client).resumeWebSocket(); + break; + + case "drop-next-create-response": + this.getAgent(step.client).dropNextCreateResponse(); + break; + + case "wait-for-dropped-create-response": + await this.getAgent(step.client).waitForDroppedCreateResponse(); + break; + + case "sleep": + await sleep(step.ms); + break; + + case "reset": + await this.getAgent(step.client).reset(); + break; + + default: { + const unknownStep = step as { type: string }; + throw new Error(`Unknown step type: ${unknownStep.type}`); + } + } + } + + /** + * Wait for all agents to reach a consistent state. + * + * Waiting for agents is done in two full rounds: the first round + * drains in-flight operations, but completing those operations can + * trigger new work on OTHER agents via server broadcasts. The second + * round waits for that cascading work to settle. Deeper cascades + * are handled by the outer retry loop. + */ + private async waitForConvergence(): Promise { + this.logger.info("Barrier: waiting for convergence..."); + + const deadline = Date.now() + CONVERGENCE_TIMEOUT_MS; + let lastError: Error | undefined = undefined; + + while (Date.now() < deadline) { + await this.waitAllAgentsSettled(); + + try { + await this.assertConsistent(); + this.logger.info("Barrier complete: all clients converged"); + return; + } catch (error) { + lastError = + error instanceof Error ? error : new Error(String(error)); + this.logger.info("Barrier: not yet converged, retrying..."); + await sleep(CONVERGENCE_RETRY_DELAY_MS); + } + } + + throw new Error( + `Convergence timed out after ${CONVERGENCE_TIMEOUT_MS}ms: ${lastError?.message ?? "no consistency check ran"}`, + { cause: lastError } + ); + } + + /** + * Wait for all agents to be simultaneously idle. + * + * Completing work on agent A can trigger a server broadcast that + * enqueues new work on agent B, which can cascade further. With N + * agents the worst-case cascade depth is N (a chain A→B→C→…→A), + * so we run N+1 sequential passes to drain it. Extra passes are + * essentially free when there is no outstanding work. + * + * The outer {@link waitForConvergence} loop with consistency checks + * remains the ultimate guarantee — this method just minimizes how + * many slow retry iterations are needed. + */ + private async waitAllAgentsSettled(): Promise { + const rounds = this.agents.length + 1; + for (let round = 0; round < rounds; round++) { + for (const agent of this.agents) { + await agent.waitForSync(); + } + } + } + + private async assertConsistent( + verify?: (state: AssertableState) => void + ): Promise { + this.logger.info("Asserting all clients are consistent..."); + assert( + this.agents.length >= 2, + "Need at least 2 agents for consistency check" + ); + + // Snapshot all agents' file states upfront to minimize the window + // where background sync could mutate state between reads. + const clientFiles: Map[] = []; + for (const agent of this.agents) { + const sortedFiles = (await agent.listFilesRecursively()).sort(); + const fileMap = new Map(); + for (const file of sortedFiles) { + const content = await agent.getFileContent(file); + fileMap.set(file, content); + } + clientFiles.push(fileMap); + } + + const referenceFiles = Array.from(clientFiles[0].keys()); + + this.logger.info( + `Reference client has ${referenceFiles.length} files: ${referenceFiles.join(", ")}` + ); + + for (let i = 1; i < clientFiles.length; i++) { + const agentFileKeys = Array.from(clientFiles[i].keys()); + + this.logger.info( + `Client ${i} has ${agentFileKeys.length} files: ${agentFileKeys.join(", ")}` + ); + + assert( + agentFileKeys.length === referenceFiles.length, + `File count mismatch: client 0 has ${referenceFiles.length} files, client ${i} has ${agentFileKeys.length} files` + ); + + for (let j = 0; j < agentFileKeys.length; j++) { + assert( + agentFileKeys[j] === referenceFiles[j], + `File list mismatch at index ${j}: client 0 has "${referenceFiles[j]}", client ${i} has "${agentFileKeys[j]}"` + ); + } + + for (const file of referenceFiles) { + const referenceContent = clientFiles[0].get(file); + const agentContent = clientFiles[i].get(file); + + assert( + referenceContent === agentContent, + `Content mismatch for ${file}:\nClient 0: "${referenceContent}"\nClient ${i}: "${agentContent}"` + ); + } + } + + this.logger.info("✓ All clients are consistent"); + + if (verify) { + this.logger.info("Running custom verification..."); + try { + verify( + new AssertableState({ + files: clientFiles[0], + clientFiles + }) + ); + } catch (error) { + const msg = + error instanceof Error ? error.message : String(error); + throw new Error(`Custom verification failed: ${msg}`); + } + this.logger.info("✓ Custom verification passed"); + } + } + + private async cleanup(): Promise { + // Always resume the server in case a test paused it and then + // failed before reaching the resume step. Without this, all + // subsequent tests would hang because the server process is + // frozen (SIGSTOP) and can't respond to HTTP or WebSocket. + try { + this.serverControl.resume(); + } catch { + // Server wasn't paused or isn't running — safe to ignore + } + + this.logger.info("\nCleaning up agents..."); + for (const agent of this.agents) { + try { + await agent.cleanup(); + } catch (error) { + this.logger.warn( + `Agent cleanup error: ${error instanceof Error ? error.message : String(error)}` + ); + } + } + this.agents = []; + this.logger.info("Cleanup complete"); + } +} diff --git a/frontend/deterministic-tests/src/tests/binary-pending-create-not-displaced.test.ts b/frontend/deterministic-tests/src/tests/binary-pending-create-not-displaced.test.ts new file mode 100644 index 00000000..467c19f0 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/binary-pending-create-not-displaced.test.ts @@ -0,0 +1,40 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const binaryPendingCreateNotDisplacedTest: TestDefinition = { + description: + "Two clients each create a binary file at the same path while offline. " + + "After syncing, both files should exist on both clients at separate paths.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "data.bin", + content: "binary data from client 0" + }, + { + type: "create", + client: 1, + path: "data.bin", + content: "binary data from client 1" + }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(2) + .assertFileExists("data.bin") + .assertFileExists("data (1).bin") + .assertAnyFileContains( + "binary data from client 0", + "binary data from client 1" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/binary-to-text-transition.test.ts b/frontend/deterministic-tests/src/tests/binary-to-text-transition.test.ts new file mode 100644 index 00000000..8b934c1b --- /dev/null +++ b/frontend/deterministic-tests/src/tests/binary-to-text-transition.test.ts @@ -0,0 +1,97 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const binaryToTextTransitionTest: TestDefinition = { + description: + "A .bin file is created and synced. Both clients edit it offline " + + "(binary last-write-wins), then client 0 renames it to .md and " + + "writes a clean text baseline. Both clients edit different sections " + + "offline. The text merge should preserve both edits.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "data.bin", + content: "original content" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("data.bin", "original content"); + } + }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + + { type: "update", client: 0, path: "data.bin", content: "version A" }, + { type: "update", client: 1, path: "data.bin", content: "version B" }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContainsAny( + "data.bin", + "version A", + "version B" + ); + } + }, + + { type: "disable-sync", client: 1 }, + { type: "rename", client: 0, oldPath: "data.bin", newPath: "data.md" }, + { + type: "update", + client: 0, + path: "data.md", + content: "top line\nmiddle line\nbottom line" + }, + { type: "sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent( + "data.md", + "top line\nmiddle line\nbottom line" + ); + } + }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + + { + type: "update", + client: 0, + path: "data.md", + content: "alpha\nmiddle line\nbottom line" + }, + { + type: "update", + client: 1, + path: "data.md", + content: "top line\nmiddle line\nbeta" + }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContains("data.md", "alpha", "beta"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/catchup-create-and-update-not-skipped.test.ts b/frontend/deterministic-tests/src/tests/catchup-create-and-update-not-skipped.test.ts new file mode 100644 index 00000000..2d40228f --- /dev/null +++ b/frontend/deterministic-tests/src/tests/catchup-create-and-update-not-skipped.test.ts @@ -0,0 +1,66 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const catchupCreateAndUpdateNotSkippedTest: TestDefinition = { + description: + "Client 1 disconnects (sync disabled). Client 0 creates a doc and " + + "then updates it. When Client 1 reconnects, the server's catch-up " + + "stream sends only the doc's *latest* version (the update), not the " + + "full history. Pre-fix the wire's `is_new_file` was set to " + + "`creation == latest_version`, so the catch-up flagged the doc as " + + "non-new even though Client 1 had never seen its creation. Client " + + "1's `processRemoteChange` then dropped it as a 'stale RemoteChange " + + "for untracked, non-new document' and the doc was silently lost. " + + "Post-fix `is_new_file` in the catch-up stream means 'new relative " + + "to the recipient's watermark' (`creation > last_seen_vault_update_id`).", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + // Establish a baseline so Client 1's last_seen is non-zero before + // we take it offline. This makes the bug genuinely about catch-up + // missing the create rather than just an empty-vault first sync. + { type: "create", client: 0, path: "warmup.md", content: "w\n" }, + { type: "barrier" }, + + // Client 1 goes offline. + { type: "disable-sync", client: 1 }, + + // Client 0 creates the doc (vault_update_id v_C, after Client 1's + // watermark). Client 1 doesn't see this because it's offline. + { type: "create", client: 0, path: "doc.md", content: "v1\n" }, + // Wait for the create's HTTP to land before the update; otherwise + // both writes are coalesced into a single POST and the server + // never sees the doc as "create followed by update". + { type: "sync", client: 0 }, + + // Client 0 updates the doc (vault_update_id v_X > v_C). The + // server's `latest_document_versions` view now returns the + // *update* row — its `creation_vault_update_id != vault_update_id`. + { + type: "update", + client: 0, + path: "doc.md", + content: "v1\nupdate\n" + }, + { type: "sync", client: 0 }, + + // Client 1 reconnects. Server's catch-up replays docs with + // `vault_update_id > last_seen`. For doc.md it sends v_X with + // `is_new_file` derived from `creation_vault_update_id > + // last_seen_vault_update_id` (post-fix) — so Client 1 treats it + // as a fresh create and downloads the latest content. + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state.assertFileCount(2); + state.assertFileExists("doc.md"); + state.assertContent("doc.md", "v1\nupdate\n"); + state.assertContent("warmup.md", "w\n"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/coalesce-update-remote-update-data-loss.test.ts b/frontend/deterministic-tests/src/tests/coalesce-update-remote-update-data-loss.test.ts new file mode 100644 index 00000000..1972526a --- /dev/null +++ b/frontend/deterministic-tests/src/tests/coalesce-update-remote-update-data-loss.test.ts @@ -0,0 +1,59 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const coalesceUpdateRemoteUpdateDataLossTest: TestDefinition = { + description: + "Divergent offline edits with text-merge expectation. Client 0's " + + "remote update fully lands before Client 1 reconnects (`sync`-after " + + "the c0 update enforces this), so Client 1's offline edit merges " + + "against a server-known version, not a coalesced batch. Both " + + "additions must survive in the final merged content. (Filename's " + + "'coalesce' framing is aspirational — a true update-coalesce test " + + "would skip the c0 sync and queue overlapping local + remote " + + "updates against the same parent version.)", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "doc.md", + content: "line 1\nline 2\nline 3" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 1 }, + + { + type: "update", + client: 0, + path: "doc.md", + content: "line 1\nline 2\nline 3\nclient 0 addition" + }, + { type: "sync", client: 0 }, + + { + type: "update", + client: 1, + path: "doc.md", + content: "client 1 addition\nline 1\nline 2\nline 3" + }, + + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(1) + .assertContains( + "doc.md", + "client 0 addition", + "client 1 addition" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/coalesced-remote-update-watermark-loss.test.ts b/frontend/deterministic-tests/src/tests/coalesced-remote-update-watermark-loss.test.ts new file mode 100644 index 00000000..aceb8baa --- /dev/null +++ b/frontend/deterministic-tests/src/tests/coalesced-remote-update-watermark-loss.test.ts @@ -0,0 +1,53 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const coalescedRemoteUpdateWatermarkLossTest: TestDefinition = { + description: + "Client 0 sends three rapid updates. After syncing, both clients " + + "disconnect and reconnect twice. Content should remain correct " + + "after each reconnect.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "doc.md", content: "original" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "update", client: 0, path: "doc.md", content: "update 1" }, + { type: "update", client: 0, path: "doc.md", content: "update 2" }, + { type: "update", client: 0, path: "doc.md", content: "final update" }, + + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContent("doc.md", "final update"); + } + }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContent("doc.md", "final update"); + } + }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContent("doc.md", "final update"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/concurrent-delete-during-remote-update.test.ts b/frontend/deterministic-tests/src/tests/concurrent-delete-during-remote-update.test.ts new file mode 100644 index 00000000..88376f22 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/concurrent-delete-during-remote-update.test.ts @@ -0,0 +1,32 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const concurrentDeleteDuringRemoteUpdateTest: TestDefinition = { + description: + "One client updates a file while the other deletes it at the same " + + "time. Both clients should converge without errors.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "doc.md", content: "original" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + + { type: "update", client: 0, path: "doc.md", content: "updated by 0" }, + { type: "delete", client: 1, path: "doc.md" }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state.assertFileCount(0); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/concurrent-edit-exact-same-position.test.ts b/frontend/deterministic-tests/src/tests/concurrent-edit-exact-same-position.test.ts new file mode 100644 index 00000000..5c141a0e --- /dev/null +++ b/frontend/deterministic-tests/src/tests/concurrent-edit-exact-same-position.test.ts @@ -0,0 +1,49 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const concurrentEditExactSamePositionTest: TestDefinition = { + description: + "Both clients replace the same word in a file with different text " + + "while offline. After syncing, the merged result should contain " + + "both replacements.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "doc.md", + content: "the quick brown fox" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + { + type: "update", + client: 0, + path: "doc.md", + content: "the slow brown fox" + }, + { + type: "update", + client: 1, + path: "doc.md", + content: "the fast brown fox" + }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(1) + .assertContains("doc.md", "slow", "fast", "brown fox"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/concurrent-rename-and-create-at-target-create-first.test.ts b/frontend/deterministic-tests/src/tests/concurrent-rename-and-create-at-target-create-first.test.ts new file mode 100644 index 00000000..cd8046ce --- /dev/null +++ b/frontend/deterministic-tests/src/tests/concurrent-rename-and-create-at-target-create-first.test.ts @@ -0,0 +1,49 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const concurrentRenameAndCreateAtTargetCreateFirstTest: TestDefinition = { + description: + "One client renames X to Y while another creates a new file at Y, " + + "both offline. After syncing, Y should contain merged content from " + + "both the renamed file and the newly created file.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "X.md", + content: "original file X" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + + { type: "rename", client: 0, oldPath: "X.md", newPath: "Y.md" }, + + { + type: "create", + client: 1, + path: "Y.md", + content: "brand new Y content" + }, + + { type: "enable-sync", client: 1 }, + { type: "sync", client: 1 }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(2) + .assertContains("Y (1).md", "original file X") + .assertContains("Y.md", "brand new Y content"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/concurrent-rename-and-create-at-target-rename-first.test.ts b/frontend/deterministic-tests/src/tests/concurrent-rename-and-create-at-target-rename-first.test.ts new file mode 100644 index 00000000..0ac0b721 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/concurrent-rename-and-create-at-target-rename-first.test.ts @@ -0,0 +1,52 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const concurrentRenameAndCreateAtTargetRenameFirstTest: TestDefinition = { + description: + "One client renames X to Y while another creates a new file at Y, " + + "both offline. We can't merge the create because it would result in a cycle", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "X.md", + content: "original file X" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + + { type: "rename", client: 0, oldPath: "X.md", newPath: "Y.md" }, + + { + type: "create", + client: 1, + path: "Y.md", + content: "brand new Y content" + }, + + { type: "enable-sync", client: 0 }, + { type: "sync", client: 0 }, + + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileNotExists("X.md") + .assertFileExists("Y.md") + .assertFileExists("Y (1).md") + .assertAnyFileContains( + "original file X", + "brand new Y content" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/concurrent-rename-first-wins.test.ts b/frontend/deterministic-tests/src/tests/concurrent-rename-first-wins.test.ts new file mode 100644 index 00000000..5337649d --- /dev/null +++ b/frontend/deterministic-tests/src/tests/concurrent-rename-first-wins.test.ts @@ -0,0 +1,61 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const concurrentRenameFirstWinsTest: TestDefinition = { + description: + "Both clients start online with the same file. Both go offline, " + + "rename the file to different paths, and edit it. When they reconnect, " + + "the first rename to reach the server wins the path and both content " + + "edits are merged.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "A.md", + content: "line 1\nline 2\nline 3" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("A.md", "line 1\nline 2\nline 3"); + } + }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + + { type: "rename", client: 0, oldPath: "A.md", newPath: "B.md" }, + { + type: "update", + client: 0, + path: "B.md", + content: "edit from 0\nline 2\nline 3" + }, + + { type: "rename", client: 1, oldPath: "A.md", newPath: "C.md" }, + { + type: "update", + client: 1, + path: "C.md", + content: "line 1\nline 2\nedit from 1" + }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("A.md") + .assertFileCount(2) + .assertContent("B.md", "edit from 0\nline 2\nline 3") + .assertContent("C.md", "line 1\nline 2\nedit from 1"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/concurrent-rename-same-target.test.ts b/frontend/deterministic-tests/src/tests/concurrent-rename-same-target.test.ts new file mode 100644 index 00000000..0b72c0f3 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/concurrent-rename-same-target.test.ts @@ -0,0 +1,39 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const concurrentRenameSameTargetTest: TestDefinition = { + description: + "One client renames A to C while the other renames B to C, both offline. " + + "After syncing, both file contents should be preserved via path deconfliction.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "content-a" }, + { type: "create", client: 0, path: "B.md", content: "content-b" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 1 }, + + { type: "rename", client: 0, oldPath: "A.md", newPath: "C.md" }, + { type: "sync", client: 0 }, + + { type: "rename", client: 1, oldPath: "B.md", newPath: "C.md" }, + + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(2) + .assertFileNotExists("A.md") + .assertFileNotExists("B.md") + .assertFileExists("C.md") + .assertFileExists("C (1).md") + .assertAnyFileContains("content-a", "content-b"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/concurrent-update-diff-consistency.test.ts b/frontend/deterministic-tests/src/tests/concurrent-update-diff-consistency.test.ts new file mode 100644 index 00000000..d21ce16b --- /dev/null +++ b/frontend/deterministic-tests/src/tests/concurrent-update-diff-consistency.test.ts @@ -0,0 +1,51 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const concurrentUpdateDiffConsistencyTest: TestDefinition = { + description: + "Both clients edit different sections of the same file while offline. " + + "After syncing, the merged file should contain both edits.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "doc.md", + content: "header\nmiddle\nfooter" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + { + type: "update", + client: 0, + path: "doc.md", + content: "header by 0\nmiddle\nfooter" + }, + { + type: "update", + client: 1, + path: "doc.md", + content: "header\nmiddle\nfooter by 1" + }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(1) + .assertContent( + "doc.md", + "header by 0\nmiddle\nfooter by 1" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/create-delete-noop.test.ts b/frontend/deterministic-tests/src/tests/create-delete-noop.test.ts new file mode 100644 index 00000000..6c766001 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/create-delete-noop.test.ts @@ -0,0 +1,27 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const createDeleteNoopTest: TestDefinition = { + description: + "A client creates a file, updates it multiple times, then deletes it, all while " + + "offline. After syncing, neither client should have the file.", + clients: 2, + steps: [ + { type: "enable-sync", client: 1 }, + + { type: "create", client: 0, path: "temp.md", content: "version 1" }, + { type: "update", client: 0, path: "temp.md", content: "version 2" }, + { type: "update", client: 0, path: "temp.md", content: "version 3" }, + { type: "delete", client: 0, path: "temp.md" }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("temp.md"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/create-during-reconciliation.test.ts b/frontend/deterministic-tests/src/tests/create-during-reconciliation.test.ts new file mode 100644 index 00000000..0fe51106 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/create-during-reconciliation.test.ts @@ -0,0 +1,50 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const createDuringReconciliationTest: TestDefinition = { + description: + "Client creates two files while offline, reconnects, then immediately " + + "creates a third file. All three files should sync to the other client.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { + type: "create", + client: 0, + path: "A.md", + content: "offline A" + }, + { + type: "create", + client: 0, + path: "B.md", + content: "offline B" + }, + + { type: "enable-sync", client: 0 }, + + { + type: "create", + client: 0, + path: "C.md", + content: "post-reconnect C" + }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(3) + .assertContent("A.md", "offline A") + .assertContent("B.md", "offline B") + .assertContent("C.md", "post-reconnect C"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/create-merge-delete.test.ts b/frontend/deterministic-tests/src/tests/create-merge-delete.test.ts new file mode 100644 index 00000000..ef7ea5c3 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/create-merge-delete.test.ts @@ -0,0 +1,37 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const createMergeDeleteTest: TestDefinition = { + description: + "Two clients create A.md offline with different content. Both come online and " + + "the content is merged. Then one client deletes A.md. Both clients should " + + "converge on an empty state.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "from-zero" }, + { type: "create", client: 1, path: "A.md", content: "from-one" }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(1) + .assertContains("A.md", "from-zero", "from-one"); + } + }, + + { type: "delete", client: 0, path: "A.md" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(0).assertFileNotExists("A.md"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/create-merge-preserves-renamed-update.test.ts b/frontend/deterministic-tests/src/tests/create-merge-preserves-renamed-update.test.ts new file mode 100644 index 00000000..a9bc37d4 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/create-merge-preserves-renamed-update.test.ts @@ -0,0 +1,59 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const createMergePreservesRenamedUpdateTest: TestDefinition = { + description: + "Both clients create the same file, which gets merged. One client goes " + + "offline, renames the file, updates it, and creates a new file at the " + + "original path. After reconnecting, the updated content must be preserved.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "doc.md", content: "alpha" }, + { type: "create", client: 1, path: "doc.md", content: "beta" }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state.assertContains("doc.md", "alpha", "beta"); + } + }, + + { type: "disable-sync", client: 1 }, + + { + type: "rename", + client: 1, + oldPath: "doc.md", + newPath: "moved.md" + }, + { + type: "update", + client: 1, + path: "moved.md", + content: "alpha beta extra-update" + }, + + { + type: "create", + client: 1, + path: "doc.md", + content: "new-content" + }, + + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertContent("moved.md", "alpha beta extra-update") + .assertContent("doc.md", "new-content"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/create-rename-create-same-path.test.ts b/frontend/deterministic-tests/src/tests/create-rename-create-same-path.test.ts new file mode 100644 index 00000000..b9e16c90 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/create-rename-create-same-path.test.ts @@ -0,0 +1,34 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const createRenameCreateSamePathTest: TestDefinition = { + description: + "Client creates A.md, renames to B.md, creates new A.md, renames " + + "to C.md, creates yet another A.md. All three files should exist " + + "as separate documents on both clients.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "first file" }, + { type: "rename", client: 0, oldPath: "A.md", newPath: "B.md" }, + + { type: "create", client: 0, path: "A.md", content: "second file" }, + { type: "rename", client: 0, oldPath: "A.md", newPath: "C.md" }, + + { type: "create", client: 0, path: "A.md", content: "third file" }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(3) + .assertContent("B.md", "first file") + .assertContent("C.md", "second file") + .assertContent("A.md", "third file"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/create-rename-response-skips-file.test.ts b/frontend/deterministic-tests/src/tests/create-rename-response-skips-file.test.ts new file mode 100644 index 00000000..aa24b110 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/create-rename-response-skips-file.test.ts @@ -0,0 +1,36 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const createRenameResponseSkipsFileTest: TestDefinition = { + description: + "Client 0 creates a file online then immediately renames it. " + + "Client 1 must receive the file content at the renamed path.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + + { + type: "create", + client: 0, + path: "doc.md", + content: "the-content" + }, + + { + type: "rename", + client: 0, + oldPath: "doc.md", + newPath: "renamed.md" + }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertAnyFileContains("the-content"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/create-update-coalesce-server-pause.test.ts b/frontend/deterministic-tests/src/tests/create-update-coalesce-server-pause.test.ts new file mode 100644 index 00000000..9b752d05 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/create-update-coalesce-server-pause.test.ts @@ -0,0 +1,32 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const createUpdateCoalesceServerPauseTest: TestDefinition = { + description: + "Client creates a file and immediately updates it while the server is " + + "paused. When the server resumes, both clients should have the final " + + "updated content.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + + { type: "pause-server" }, + + { type: "create", client: 0, path: "doc.md", content: "initial" }, + { type: "update", client: 0, path: "doc.md", content: "final version" }, + + { type: "resume-server" }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(1) + .assertContent("doc.md", "final version"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/delete-by-other-client-then-recreate.test.ts b/frontend/deterministic-tests/src/tests/delete-by-other-client-then-recreate.test.ts new file mode 100644 index 00000000..dfef9961 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/delete-by-other-client-then-recreate.test.ts @@ -0,0 +1,40 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const deleteByOtherClientThenRecreateTest: TestDefinition = { + description: + "Client 1 deletes a file and the delete propagates. Then client 0 " + + "creates a new file at the same path. Both clients must have the file.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "original" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "delete", client: 1, path: "A.md" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("A.md"); + } + }, + + { + type: "create", + client: 0, + path: "A.md", + content: "recreated by client 0" + }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("A.md", "recreated by client 0"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/delete-during-pending-create.test.ts b/frontend/deterministic-tests/src/tests/delete-during-pending-create.test.ts new file mode 100644 index 00000000..3ba393b8 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/delete-during-pending-create.test.ts @@ -0,0 +1,35 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const deleteDuringPendingCreateTest: TestDefinition = { + description: + "Client 0 creates a file while the server is paused, then deletes it before the server resumes. " + + "After resume, the file should end up deleted on both clients.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "pause-server" }, + + { + type: "create", + client: 0, + path: "ephemeral.md", + content: "this will be deleted" + }, + + { type: "delete", client: 0, path: "ephemeral.md" }, + + { type: "resume-server" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(0).assertFileNotExists("ephemeral.md"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/delete-recreate-concurrent-update.test.ts b/frontend/deterministic-tests/src/tests/delete-recreate-concurrent-update.test.ts new file mode 100644 index 00000000..6cb4cb98 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/delete-recreate-concurrent-update.test.ts @@ -0,0 +1,42 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const deleteRecreateConcurrentUpdateTest: TestDefinition = { + description: + "Client 0 deletes and recreates A.md with new content while offline. Client 1 updates A.md concurrently. " + + "After client 0 reconnects, both clients must converge with client 0's recreated content preserved.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "original" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { type: "delete", client: 0, path: "A.md" }, + { + type: "create", + client: 0, + path: "A.md", + content: "recreated by client 0" + }, + + { + type: "update", + client: 1, + path: "A.md", + content: "updated by client 1" + }, + { type: "sync", client: 1 }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileExists("A.md").assertContains("A.md", "recreated"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/delete-recreate-different-content.test.ts b/frontend/deterministic-tests/src/tests/delete-recreate-different-content.test.ts new file mode 100644 index 00000000..782c3cd5 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/delete-recreate-different-content.test.ts @@ -0,0 +1,54 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const deleteRecreateDifferentContentTest: TestDefinition = { + description: + "Client 0 deletes and recreates A.md with new content offline while client 1 edits A.md offline. " + + "Both clients should converge with content from both sides merged.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "A.md", + content: "original content here" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + + { type: "delete", client: 0, path: "A.md" }, + { + type: "create", + client: 0, + path: "A.md", + content: "brand new content" + }, + + { + type: "update", + client: 1, + path: "A.md", + content: "edit from client 1" + }, + + { type: "enable-sync", client: 0 }, + { type: "sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContains( + "A.md", + "brand new", + "client 1" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/delete-recreate-same-path.test.ts b/frontend/deterministic-tests/src/tests/delete-recreate-same-path.test.ts new file mode 100644 index 00000000..dde8d341 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/delete-recreate-same-path.test.ts @@ -0,0 +1,34 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const deleteRecreateSamePathTest: TestDefinition = { + description: + "Client 0 creates A.md, syncs. Then deletes A.md and creates a new A.md " + + "with different content. Both clients should converge on the new content.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "version 1" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("A.md", "version 1"); + } + }, + + { type: "disable-sync", client: 0 }, + { type: "delete", client: 0, path: "A.md" }, + { type: "create", client: 0, path: "A.md", content: "version 2" }, + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("A.md", "version 2"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/delete-recreated-pending-create-with-stale-deleting-record.test.ts b/frontend/deterministic-tests/src/tests/delete-recreated-pending-create-with-stale-deleting-record.test.ts new file mode 100644 index 00000000..80e95f48 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/delete-recreated-pending-create-with-stale-deleting-record.test.ts @@ -0,0 +1,52 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const deleteRecreatedPendingCreateWithStaleDeletingRecordTest: TestDefinition = + { + description: + "A local delete for a recreated pending create must target the " + + "new pending create, not an older same-path record whose server " + + "delete has been acked but whose WebSocket delete receipt is " + + "still paused.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "pause-websocket", client: 0 }, + { type: "pause-server" }, + { + type: "create", + client: 0, + path: "binary-14.bin", + content: "BINARY:first" + }, + { type: "sleep", ms: 100 }, + { type: "delete", client: 0, path: "binary-14.bin" }, + { type: "resume-server" }, + { type: "sync", client: 0 }, + + { type: "pause-server" }, + { + type: "create", + client: 0, + path: "binary-14.bin", + content: "BINARY:second" + }, + { type: "sleep", ms: 100 }, + { type: "delete", client: 0, path: "binary-14.bin" }, + { type: "resume-server" }, + { type: "sync", client: 0 }, + + { type: "resume-websocket", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state.assertFileCount(0); + } + } + ] + }; diff --git a/frontend/deterministic-tests/src/tests/delete-rename-conflict.test.ts b/frontend/deterministic-tests/src/tests/delete-rename-conflict.test.ts new file mode 100644 index 00000000..91e6289b --- /dev/null +++ b/frontend/deterministic-tests/src/tests/delete-rename-conflict.test.ts @@ -0,0 +1,43 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const deleteRenameConflictTest: TestDefinition = { + description: + "Client 0 deletes A.md while client 1 renames A.md to C.md offline. " + + "After client 1 reconnects, both clients should converge to the same state.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "content-a" }, + { type: "create", client: 0, path: "B.md", content: "content-b" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileExists("A.md").assertFileExists("B.md"); + } + }, + + { type: "disable-sync", client: 1 }, + + { type: "delete", client: 0, path: "A.md" }, + { type: "sync", client: 0 }, + + { type: "rename", client: 1, oldPath: "A.md", newPath: "C.md" }, + + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("B.md", "content-b"); + s.assertFileNotExists("A.md"); + s.ifFileExists("C.md", (inner) => + inner.assertContent("C.md", "content-a") + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/displaced-file-not-marked-deleted.test.ts b/frontend/deterministic-tests/src/tests/displaced-file-not-marked-deleted.test.ts new file mode 100644 index 00000000..cb995243 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/displaced-file-not-marked-deleted.test.ts @@ -0,0 +1,38 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const displacedFileNotMarkedDeletedTest: TestDefinition = { + description: + "Client 0 creates a new file at path B.md while client 1 renames " + + "A.md to B.md. The remote download of B.md displaces client 1's " + + "renamed file. The displaced document must not be permanently " + + "marked as recently deleted, so it can still be synced.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "content of A" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 1 }, + + { type: "create", client: 0, path: "B.md", content: "content of B" }, + { type: "rename", client: 0, oldPath: "A.md", newPath: "C.md" }, + { type: "sync", client: 0 }, + + { type: "rename", client: 1, oldPath: "A.md", newPath: "B.md" }, + { type: "enable-sync", client: 1 }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(2) + .assertContent("B.md", "content of B") + .assertContent("C.md", "content of A"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/double-offline-cycle.test.ts b/frontend/deterministic-tests/src/tests/double-offline-cycle.test.ts new file mode 100644 index 00000000..744d862e --- /dev/null +++ b/frontend/deterministic-tests/src/tests/double-offline-cycle.test.ts @@ -0,0 +1,77 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const doubleOfflineCycleTest: TestDefinition = { + description: + "Client 0 goes through three offline-edit-reconnect cycles. " + + "Each offline edit must propagate to client 1 after reconnection.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "doc.md", + content: "initial" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("doc.md", "initial"); + } + }, + + { type: "disable-sync", client: 0 }, + { + type: "update", + client: 0, + path: "doc.md", + content: "first edit" + }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("doc.md", "first edit"); + } + }, + + { type: "disable-sync", client: 0 }, + { + type: "update", + client: 0, + path: "doc.md", + content: "second edit" + }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("doc.md", "second edit"); + } + }, + + { type: "disable-sync", client: 0 }, + { + type: "update", + client: 0, + path: "doc.md", + content: "third edit" + }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContent("doc.md", "third edit"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/idempotency-after-server-pause.test.ts b/frontend/deterministic-tests/src/tests/idempotency-after-server-pause.test.ts new file mode 100644 index 00000000..551c702d --- /dev/null +++ b/frontend/deterministic-tests/src/tests/idempotency-after-server-pause.test.ts @@ -0,0 +1,33 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const idempotencyAfterServerPauseTest: TestDefinition = { + description: + "Client 0 creates a file, then the server is paused mid-response. " + + "After the server resumes, both clients must converge to a single copy of the file with no duplicates.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "create", + client: 0, + path: "doc.md", + content: "important data" + }, + { type: "pause-server" }, + + { type: "resume-server" }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContent("doc.md", "important data"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/interrupted-delete-retry.test.ts b/frontend/deterministic-tests/src/tests/interrupted-delete-retry.test.ts new file mode 100644 index 00000000..3ae7eda5 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/interrupted-delete-retry.test.ts @@ -0,0 +1,29 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const interruptedDeleteRetryTest: TestDefinition = { + description: + "Client 0 deletes a file, then the server is paused. " + + "After the server resumes, both clients should have zero files.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "doc.md", content: "to be deleted" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "delete", client: 0, path: "doc.md" }, + + { type: "pause-server" }, + + { type: "resume-server" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(0); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/local-edit-lost-during-create-merge.test.ts b/frontend/deterministic-tests/src/tests/local-edit-lost-during-create-merge.test.ts new file mode 100644 index 00000000..20925889 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/local-edit-lost-during-create-merge.test.ts @@ -0,0 +1,41 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const localEditLostDuringCreateMergeTest: TestDefinition = { + description: + "Both clients create doc.md with different content while offline. " + + "Client 0 also edits the file before syncing. After both connect, " + + "the merged result should contain content from both clients.", + clients: 2, + steps: [ + { type: "create", client: 1, path: "doc.md", content: "from-client-1" }, + { + type: "create", + client: 0, + path: "doc.md", + content: "from-client-0" + }, + { + type: "update", + client: 0, + path: "doc.md", + content: "local-edit-during-create" + }, + + { type: "enable-sync", client: 1 }, + { type: "sync", client: 1 }, + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContains( + "doc.md", + "from-client-1", + "local-edit-during-create" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/local-rename-survives-remote-rename.test.ts b/frontend/deterministic-tests/src/tests/local-rename-survives-remote-rename.test.ts new file mode 100644 index 00000000..c2b80af3 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/local-rename-survives-remote-rename.test.ts @@ -0,0 +1,80 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const localRenameSurvivesRemoteRenameTest: TestDefinition = { + description: + "Drain processes a RemoteChange (remote rename for doc D) while a " + + "LocalUpdate (user rename of D) is also queued behind it. " + + "`processRemoteUpdate` moves the disk file and, because there is a " + + "pending LocalUpdate, takes the else branch — but its setDocument " + + "uses the stale `record.path` (= the user-rename target) instead of " + + "the actualPath the file just moved to. The queued LocalUpdate then " + + "reads from `record.path`, throws FileNotFoundError, and is " + + "silently dropped. Setup pins the queue order: a sentinel " + + "LocalUpdate keeps drain busy on a SIGSTOPped HTTP roundtrip while " + + "we resume client 0's WebSocket (enqueues RemoteChange) and then " + + "user-rename D (enqueues LocalUpdate after the RemoteChange). On " + + "server resume the drain pops the sentinel, then RemoteChange, then " + + "LocalUpdate — exactly the order that triggers the bug.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "create", client: 0, path: "doc.md", content: "v1\n" }, + { type: "create", client: 0, path: "sentinel.md", content: "s\n" }, + { type: "barrier" }, + + // Pause client 0's WebSocket so the upcoming remote rename buffers. + { type: "pause-websocket", client: 0 }, + + // Server applies remote rename of doc.md -> remote.md. Broadcast + // is buffered on client 0's WebSocket. + { type: "rename", client: 1, oldPath: "doc.md", newPath: "remote.md" }, + { type: "sync", client: 1 }, + + // Pause the server BEFORE arming the sentinel, so the sentinel's + // HTTP request will buffer at the kernel and keep drain occupied. + { type: "pause-server" }, + + // Sentinel: a LocalUpdate on a *different* doc that drain pops + // first. Its HTTP roundtrip stalls on SIGSTOP, freezing drain + // until we resume the server. While drain is frozen we can grow + // the queue with additional events whose order we control. + { + type: "update", + client: 0, + path: "sentinel.md", + content: "s\nedit\n" + }, + + // Resume the WebSocket — buffered remote rename enqueues as a + // RemoteChange. Drain is still stuck on the sentinel HTTP. + { type: "resume-websocket", client: 0 }, + + // User renames doc.md -> local.md on client 0. queue.enqueue + // mutates the doc's record.path to "local.md" and pushes a + // LocalUpdate(rename) onto the tail of the queue. Queue is now + // [sentinel-update (in-flight), RemoteChange, LocalUpdate-rename]. + { type: "rename", client: 0, oldPath: "doc.md", newPath: "local.md" }, + + // Resume the server. Drain pops sentinel-update (succeeds), then + // RemoteChange. Pre-fix: processRemoteUpdate moves disk + // local.md -> remote.md, takes the else branch, and + // setDocument(record.path = "local.md", …) leaves record.path + // stale. Drain pops the LocalUpdate-rename and reads from the + // stale record.path, hits FileNotFoundError, silent skip. + // Post-fix: when a local event is pending, we re-queue the + // remote update without touching disk or record, so the local + // rename drains first and both ends converge. + { type: "resume-server" }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state.assertFileCount(2); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/local-update-survives-remote-rename.test.ts b/frontend/deterministic-tests/src/tests/local-update-survives-remote-rename.test.ts new file mode 100644 index 00000000..0d8348c0 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/local-update-survives-remote-rename.test.ts @@ -0,0 +1,69 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const localUpdateSurvivesRemoteRenameTest: TestDefinition = { + description: + "Client 0 has a local content edit pending while a remote rename for " + + "the same doc arrives over the WebSocket. The remote rename's internal " + + "move relocates the disk file from the old path (where the user wrote) " + + "to the new server path. Previously, the queued LocalUpdate's " + + "`event.path` was left pointing at the now-vacated old path, so " + + "`skipIfOversized`'s `getFileSize(event.path)` threw " + + "`FileNotFoundError`, which `processEvent`'s catch silently swallowed " + + "as 'Skipping sync event 'local-update' because the file no longer " + + "exists' — and the user's edit was lost. The fix routes the size " + + "check through `tracked.path` (the doc's current disk path), " + + "matching the path `processLocalUpdate` itself reads from.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "doc.md", content: "v1\n" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + // Pause client 0's WebSocket so the upcoming remote rename buffers + // there until we've already enqueued client 0's local content + // edit. This guarantees the LocalUpdate sits in client 0's queue + // when the rename's RemoteChange drains. + { type: "pause-websocket", client: 0 }, + + { + type: "rename", + client: 1, + oldPath: "doc.md", + newPath: "renamed.md" + }, + { type: "sync", client: 1 }, + + // Client 0 still believes the file is at `doc.md` (its WebSocket is + // paused, so the rename hasn't reached it). The user edits content + // at `doc.md`. This pushes a LocalUpdate(D, path=doc.md, + // originalPath=doc.md, isUserRename=false) into client 0's queue. + { + type: "update", + client: 0, + path: "doc.md", + content: "v1\nclient 0 edit\n" + }, + + // Resume the WebSocket. The buffered remote rename (server-broadcast) + // drains. `processRemoteUpdate` does an internal `move(doc.md, + // renamed.md)` and, because there's a pending LocalUpdate for D, + // takes the else branch (re-enqueue v_K, setDocument(renamed.md, …)). + // Then drain reaches the LocalUpdate. Pre-fix: skipped silently. + // Post-fix: PUTs the user's content to the doc (at its new path, + // since this is a content-only edit, not a user rename). + { type: "resume-websocket", client: 0 }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state.assertFileCount(1); + state.assertFileExists("renamed.md"); + state.assertContent("renamed.md", "v1\nclient 0 edit\n"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/mc-cross-create-rename-same-target.test.ts b/frontend/deterministic-tests/src/tests/mc-cross-create-rename-same-target.test.ts new file mode 100644 index 00000000..d986a733 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/mc-cross-create-rename-same-target.test.ts @@ -0,0 +1,46 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const mcCrossCreateRenameSameTargetTest: TestDefinition = { + description: + "Client 0 creates X.md, Client 1 creates Y.md. Both sync. Client 0 renames " + + "X.md -> Z.md. Client 1 (offline) renames Y.md -> Z.md. Both must converge " + + "with both contents preserved via path deconfliction.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "X.md", content: "content-x" }, + { type: "create", client: 1, path: "Y.md", content: "content-y" }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileExists("X.md").assertFileExists("Y.md"); + } + }, + + { type: "disable-sync", client: 1 }, + + { type: "rename", client: 0, oldPath: "X.md", newPath: "Z.md" }, + { type: "sync", client: 0 }, + + { type: "rename", client: 1, oldPath: "Y.md", newPath: "Z.md" }, + + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(2) + .assertFileNotExists("X.md") + .assertFileNotExists("Y.md") + .assertFileExists("Z.md") + .assertAnyFileContains("content-x", "content-y"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/mc-delete-then-offline-rename.test.ts b/frontend/deterministic-tests/src/tests/mc-delete-then-offline-rename.test.ts new file mode 100644 index 00000000..6727e99d --- /dev/null +++ b/frontend/deterministic-tests/src/tests/mc-delete-then-offline-rename.test.ts @@ -0,0 +1,39 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const mcDeleteThenOfflineRenameTest: TestDefinition = { + description: + "Client 0 creates A.md, both sync. Client 1 goes offline. Client 0 deletes " + + "A.md and syncs. Client 1 (offline) renames A.md to B.md. Client 1 reconnects. " + + "Both must converge. C.md (unrelated) must be unaffected.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "original" }, + { type: "create", client: 0, path: "C.md", content: "unrelated" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 1 }, + + { type: "delete", client: 0, path: "A.md" }, + { type: "sync", client: 0 }, + + { type: "rename", client: 1, oldPath: "A.md", newPath: "B.md" }, + + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("C.md", "unrelated").assertFileNotExists( + "A.md" + ); + s.ifFileExists("B.md", (inner) => + inner.assertContent("B.md", "original") + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/mc-multi-delete-offline-rename.test.ts b/frontend/deterministic-tests/src/tests/mc-multi-delete-offline-rename.test.ts new file mode 100644 index 00000000..8db90aab --- /dev/null +++ b/frontend/deterministic-tests/src/tests/mc-multi-delete-offline-rename.test.ts @@ -0,0 +1,49 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const mcMultiDeleteOfflineRenameTest: TestDefinition = { + description: + "Client 0 creates 5 files. Client 1 deletes 2 while Client 0 (offline) " + + "renames one of the deleted files. Both must converge.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "file-1.md", content: "content-1" }, + { type: "create", client: 0, path: "file-2.md", content: "content-2" }, + { type: "create", client: 0, path: "file-3.md", content: "content-3" }, + { type: "create", client: 0, path: "file-4.md", content: "content-4" }, + { type: "create", client: 0, path: "file-5.md", content: "content-5" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + + { type: "delete", client: 1, path: "file-2.md" }, + { type: "delete", client: 1, path: "file-4.md" }, + { type: "sync", client: 1 }, + + { + type: "rename", + client: 0, + oldPath: "file-2.md", + newPath: "renamed.md" + }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileExists("file-1.md") + .assertFileExists("file-3.md") + .assertFileExists("file-5.md") + .assertFileNotExists("file-2.md") + .assertFileNotExists("file-4.md"); + s.ifFileExists("renamed.md", (inner) => + inner.assertContent("renamed.md", "content-2") + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/mc-three-client-rename-offline-update.test.ts b/frontend/deterministic-tests/src/tests/mc-three-client-rename-offline-update.test.ts new file mode 100644 index 00000000..4167b925 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/mc-three-client-rename-offline-update.test.ts @@ -0,0 +1,41 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const mcThreeClientRenameOfflineUpdateTest: TestDefinition = { + description: + "Client 0 creates A.md. Client 1 renames to B.md. Client 2 (offline) " + + "updates A.md. All three converge with updated content at B.md.", + clients: 3, + steps: [ + { type: "create", client: 0, path: "A.md", content: "original" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "enable-sync", client: 2 }, + { type: "barrier" }, + + { type: "disable-sync", client: 2 }, + + { type: "rename", client: 1, oldPath: "A.md", newPath: "B.md" }, + { type: "sync", client: 1 }, + { type: "sync", client: 0 }, + + { + type: "update", + client: 2, + path: "A.md", + content: "updated-by-client-2" + }, + + { type: "enable-sync", client: 2 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1) + .assertFileNotExists("A.md") + .assertContains("B.md", "updated-by-client-2"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/merging-update-response-survives-user-rename.test.ts b/frontend/deterministic-tests/src/tests/merging-update-response-survives-user-rename.test.ts new file mode 100644 index 00000000..e93240f9 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/merging-update-response-survives-user-rename.test.ts @@ -0,0 +1,77 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const mergingUpdateResponseSurvivesUserRenameTest: TestDefinition = { + description: + "Client 1 sends a content update with a stale `parent_version_id` " + + "(its WebSocket is paused, so it hasn't seen Client 0's intervening " + + "edit). The server merges and replies with `MergingUpdate` carrying " + + "the merged text. Before the response lands, the user renames the " + + "doc on Client 1, vacating the disk path the in-flight " + + "`processLocalUpdate` captured. Pre-fix: " + + "`handleMaybeMergingResponse`'s `operations.write(diskPath, …)` " + + "hits the `we wont recreate it` early-return inside `write`, " + + "silently dropping the server-merged content — Client 0's edit is " + + "lost on Client 1's disk, and Client 1's next local-update PUT " + + "(rebased on the now-untracked merged version) deletes Client 0's " + + "edit on the server too. Post-fix: the response is written to the " + + "doc's current tracked disk path, preserving both edits.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "create", client: 0, path: "doc.md", content: "0\n" }, + { type: "barrier" }, + + // Stop Client 1 from seeing Client 0's next edit, so its next + // outbound PUT carries a stale `parent_version_id` and the server + // is forced to merge. + { type: "pause-websocket", client: 1 }, + + // Server now holds v_b = "0\nA\n". Client 1's tracked parent + // version stays at v_a = "0\n". + { type: "update", client: 0, path: "doc.md", content: "0\nA\n" }, + { type: "sync", client: 0 }, + + // Pause the server. Subsequent HTTP PUTs from Client 1 buffer at + // the OS layer until resume. This guarantees the merge response + // for Client 1's update is still in flight when the rename below + // mutates `queue.documents`. + { type: "pause-server" }, + + // Client 1 edits doc.md with "B". The drain pops the LocalUpdate, + // captures `diskPath = "doc.md"`, reads the file, and sends the + // HTTP PUT — which buffers because the server is SIGSTOPped. + { type: "update", client: 1, path: "doc.md", content: "0\nB\n" }, + + // User renames the file while the previous PUT is still in flight. + // `queue.enqueue`'s rename branch updates `documents` to point at + // `renamed.md` synchronously, but `processLocalUpdate`'s captured + // `diskPath` ("doc.md") is a local — it can't be retargeted. + { type: "rename", client: 1, oldPath: "doc.md", newPath: "renamed.md" }, + + // Resume the server. It reconciles parent=v_a, latest=v_b, + // new="0\nB\n" → v_c with both edits, replies `MergingUpdate`. + // Pre-fix: write("doc.md", …) sees no file at that path + // (renamed.md now holds the data) and bails out without ever + // writing the merged bytes. Post-fix: the merged bytes land at + // the tracked path (renamed.md). + { type: "resume-server" }, + { type: "resume-websocket", client: 1 }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state.assertFileCount(1); + state.assertFileExists("renamed.md"); + state.assertFileNotExists("doc.md"); + // Both edits survive: Client 0's "A" and Client 1's "B". + // The reconcile may interleave them either way; assert + // both tokens are present in the converged content. + state.assertContains("renamed.md", "A", "B"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/move-and-concurrent-remote-update.test.ts b/frontend/deterministic-tests/src/tests/move-and-concurrent-remote-update.test.ts new file mode 100644 index 00000000..86657f0f --- /dev/null +++ b/frontend/deterministic-tests/src/tests/move-and-concurrent-remote-update.test.ts @@ -0,0 +1,43 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const moveAndConcurrentRemoteUpdateTest: TestDefinition = { + description: + "Client 0 renames A.md to B.md offline while client 1 updates A.md. " + + "After client 0 reconnects, both should have B.md with client 1's updated content.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "A.md", + content: "original content" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { type: "rename", client: 0, oldPath: "A.md", newPath: "B.md" }, + + { + type: "update", + client: 1, + path: "A.md", + content: "updated by client 1" + }, + { type: "sync", client: 1 }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1) + .assertFileNotExists("A.md") + .assertContains("B.md", "updated by client 1"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/move-chain-three-files.test.ts b/frontend/deterministic-tests/src/tests/move-chain-three-files.test.ts new file mode 100644 index 00000000..fe9267d4 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/move-chain-three-files.test.ts @@ -0,0 +1,42 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const moveChainThreeFilesTest: TestDefinition = { + description: + "Three files have their contents rotated (A gets C's content, B gets A's, C gets B's) " + + "while offline. After reconnecting, both clients should converge with the rotated contents.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + + { type: "create", client: 0, path: "A.md", content: "was A" }, + { type: "create", client: 0, path: "B.md", content: "was B" }, + { type: "create", client: 0, path: "C.md", content: "was C" }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + + { type: "delete", client: 0, path: "A.md" }, + { type: "delete", client: 0, path: "B.md" }, + { type: "delete", client: 0, path: "C.md" }, + + { type: "create", client: 0, path: "A.md", content: "was C" }, + { type: "create", client: 0, path: "B.md", content: "was A" }, + { type: "create", client: 0, path: "C.md", content: "was B" }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(3) + .assertContent("A.md", "was C") + .assertContent("B.md", "was A") + .assertContent("C.md", "was B"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/move-identical-content-ambiguity.test.ts b/frontend/deterministic-tests/src/tests/move-identical-content-ambiguity.test.ts new file mode 100644 index 00000000..2a9ce0b4 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/move-identical-content-ambiguity.test.ts @@ -0,0 +1,44 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const moveIdenticalContentAmbiguityTest: TestDefinition = { + description: + "Two files with identical content exist. One is deleted and the other renamed " + + "while offline. The system should still converge correctly despite the ambiguity.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "A.md", + content: "identical content" + }, + { + type: "create", + client: 0, + path: "B.md", + content: "identical content" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 1 }, + { type: "delete", client: 1, path: "A.md" }, + { type: "rename", client: 1, oldPath: "B.md", newPath: "C.md" }, + + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(1) + .assertFileNotExists("A.md") + .assertFileNotExists("B.md") + .assertContent("C.md", "identical content"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/move-preserves-remote-update.test.ts b/frontend/deterministic-tests/src/tests/move-preserves-remote-update.test.ts new file mode 100644 index 00000000..13e27349 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/move-preserves-remote-update.test.ts @@ -0,0 +1,48 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const movePreservesRemoteUpdateTest: TestDefinition = { + description: + "Client 0 renames a file offline while client 1 edits it offline. " + + "After both reconnect, the renamed file should contain client 1's edit.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "doc.md", + content: "line 1\nline 2" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + + { type: "rename", client: 0, oldPath: "doc.md", newPath: "renamed.md" }, + { + type: "update", + client: 1, + path: "doc.md", + content: "line 1\nclient 1 edit\nline 2" + }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1); + const [content] = Array.from(s.files.values()); + if (!content.includes("client 1 edit")) { + throw new Error( + `Expected merged content to include "client 1 edit", got: "${content}"` + ); + } + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/move-remote-update-reverts-rename.test.ts b/frontend/deterministic-tests/src/tests/move-remote-update-reverts-rename.test.ts new file mode 100644 index 00000000..433bf01b --- /dev/null +++ b/frontend/deterministic-tests/src/tests/move-remote-update-reverts-rename.test.ts @@ -0,0 +1,38 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const moveRemoteUpdateRevertsRenameTest: TestDefinition = { + description: + "Client 1 updates a file while client 0 is offline. Client 0 reconnects and renames the file. " + + "Both clients should converge with client 1's updated content.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "doc.md", content: "original" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { + type: "update", + client: 1, + path: "doc.md", + content: "updated by client 1" + }, + { type: "sync", client: 1 }, + + { type: "enable-sync", client: 0 }, + { type: "rename", client: 0, oldPath: "doc.md", newPath: "renamed.md" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContent( + "renamed.md", + "updated by client 1" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/move-then-delete-stale-path.test.ts b/frontend/deterministic-tests/src/tests/move-then-delete-stale-path.test.ts new file mode 100644 index 00000000..4f5feab5 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/move-then-delete-stale-path.test.ts @@ -0,0 +1,34 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const moveThenDeleteStalePathTest: TestDefinition = { + description: + "Client 0 renames A.md to B.md and immediately deletes B.md. " + + "Both clients should end up with zero files.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "A.md", + content: "content to delete" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "rename", client: 0, oldPath: "A.md", newPath: "B.md" }, + { type: "delete", client: 0, path: "B.md" }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(0) + .assertFileNotExists("A.md") + .assertFileNotExists("B.md"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/multi-file-operations.test.ts b/frontend/deterministic-tests/src/tests/multi-file-operations.test.ts new file mode 100644 index 00000000..a47f5a2a --- /dev/null +++ b/frontend/deterministic-tests/src/tests/multi-file-operations.test.ts @@ -0,0 +1,45 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const multiFileOperationsTest: TestDefinition = { + description: + "Client 0 deletes A.md while client 1 is offline. Client 1 updates B.md and renames A.md to D.md offline. " + + "After client 1 reconnects, both clients must converge with B.md updated and C.md intact.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "content-a" }, + { type: "create", client: 0, path: "B.md", content: "content-b" }, + { type: "create", client: 0, path: "C.md", content: "content-c" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 1 }, + + { type: "delete", client: 0, path: "A.md" }, + { type: "sync", client: 0 }, + + { + type: "update", + client: 1, + path: "B.md", + content: "updated by client 1" + }, + { type: "rename", client: 1, oldPath: "A.md", newPath: "D.md" }, + + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContains("B.md", "updated") + .assertFileExists("C.md") + .assertFileNotExists("A.md"); + s.ifFileExists("D.md", (inner) => + inner.assertContent("D.md", "content-a") + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/offline-concurrent-renames.test.ts b/frontend/deterministic-tests/src/tests/offline-concurrent-renames.test.ts new file mode 100644 index 00000000..6c946b9c --- /dev/null +++ b/frontend/deterministic-tests/src/tests/offline-concurrent-renames.test.ts @@ -0,0 +1,59 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const offlineConcurrentRenamesTest: TestDefinition = { + description: + "Client 0 creates A.md and syncs to both clients. Both clients go offline. " + + "Client 0 renames A.md to B.md. Client 1 renames A.md to C.md. " + + "Both reconnect. The system must converge -- both clients should " + + "agree on the final state and the content must not be lost.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "shared-content" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("A.md", "shared-content"); + } + }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + + { + type: "rename", + client: 0, + oldPath: "A.md", + newPath: "B.md" + }, + + { + type: "rename", + client: 1, + oldPath: "A.md", + newPath: "C.md" + }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("A.md") + .assertFileCount(1) + .assertAnyFileContains("shared-content"); + s.ifFileExists("B.md", (inner) => + inner.assertContent("B.md", "shared-content") + ); + s.ifFileExists("C.md", (inner) => + inner.assertContent("C.md", "shared-content") + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/offline-create-same-path-mergeable.test.ts b/frontend/deterministic-tests/src/tests/offline-create-same-path-mergeable.test.ts new file mode 100644 index 00000000..cbd59a4a --- /dev/null +++ b/frontend/deterministic-tests/src/tests/offline-create-same-path-mergeable.test.ts @@ -0,0 +1,41 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const offlineCreateSamePathMergeableTest: TestDefinition = { + description: + "Both clients create a file at the same path while offline with different text content. " + + "After both sync, both clients must converge to a merged result containing both contributions.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "notes.md", + content: "alpha wrote this line" + }, + { + type: "create", + client: 1, + path: "notes.md", + content: "beta wrote this different line" + }, + + { type: "enable-sync", client: 0 }, + { type: "sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1) + .assertFileExists("notes.md") + .assertContains( + "notes.md", + "alpha wrote this line", + "beta wrote this different line" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/offline-delete-remote-rename.test.ts b/frontend/deterministic-tests/src/tests/offline-delete-remote-rename.test.ts new file mode 100644 index 00000000..1e9ea8f7 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/offline-delete-remote-rename.test.ts @@ -0,0 +1,38 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const offlineDeleteRemoteRenameTest: TestDefinition = { + description: + "Client 0 deletes A.md offline while client 1 renames it to A_renamed.md. " + + "After client 0 reconnects, both clients must converge.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "content-a" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { type: "delete", client: 0, path: "A.md" }, + + { + type: "rename", + client: 1, + oldPath: "A.md", + newPath: "A_renamed.md" + }, + { type: "sync", client: 1 }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("A.md").assertFileNotExists( + "A_renamed.md" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/offline-delete-vs-remote-update.test.ts b/frontend/deterministic-tests/src/tests/offline-delete-vs-remote-update.test.ts new file mode 100644 index 00000000..21e81aa6 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/offline-delete-vs-remote-update.test.ts @@ -0,0 +1,46 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const offlineDeleteVsRemoteUpdateTest: TestDefinition = { + description: + "Client 0 deletes A.md offline while client 1 updates it. Both clients must converge.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "A.md", + content: "original content" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("A.md", "original content"); + } + }, + + { type: "disable-sync", client: 0 }, + { type: "delete", client: 0, path: "A.md" }, + + { + type: "update", + client: 1, + path: "A.md", + content: "important update by client 1" + }, + { type: "sync", client: 1 }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(0); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/offline-edit-remote-rename.test.ts b/frontend/deterministic-tests/src/tests/offline-edit-remote-rename.test.ts new file mode 100644 index 00000000..ffc41b89 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/offline-edit-remote-rename.test.ts @@ -0,0 +1,49 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const offlineEditRemoteRenameTest: TestDefinition = { + description: + "Client 0 edits A.md offline while client 1 renames A.md to B.md. " + + "After client 0 reconnects, the edit must appear in B.md and A.md must not exist.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "original" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("A.md", "original"); + } + }, + + { type: "disable-sync", client: 0 }, + { + type: "update", + client: 0, + path: "A.md", + content: "edited by client 0" + }, + + { + type: "rename", + client: 1, + oldPath: "A.md", + newPath: "B.md" + }, + { type: "sync", client: 1 }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("A.md") + .assertFileCount(1) + .assertContains("B.md", "edited by client 0"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/offline-edit-then-move-same-content.test.ts b/frontend/deterministic-tests/src/tests/offline-edit-then-move-same-content.test.ts new file mode 100644 index 00000000..970eabd3 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/offline-edit-then-move-same-content.test.ts @@ -0,0 +1,51 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const offlineEditThenMoveSameContentTest: TestDefinition = { + description: + "A file is renamed and edited to match a deleted file's content. Both clients must converge despite the ambiguity.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "A.md", + content: "content A" + }, + { + type: "create", + client: 0, + path: "B.md", + content: "content B" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + + { type: "delete", client: 0, path: "A.md" }, + + { type: "rename", client: 0, oldPath: "B.md", newPath: "C.md" }, + + { + type: "update", + client: 0, + path: "C.md", + content: "content A" + }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("A.md") + .assertFileNotExists("B.md") + .assertContent("C.md", "content A") + .assertFileCount(1); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/offline-mixed-operations.test.ts b/frontend/deterministic-tests/src/tests/offline-mixed-operations.test.ts new file mode 100644 index 00000000..da875b6e --- /dev/null +++ b/frontend/deterministic-tests/src/tests/offline-mixed-operations.test.ts @@ -0,0 +1,57 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const offlineMixedOperationsTest: TestDefinition = { + description: + "Client 0 creates 3 files, syncs to both clients. Client 0 goes offline, " + + "deletes file 1, renames file 2 to a new name, and edits file 3. " + + "When Client 0 reconnects, all three operations should propagate to Client 1.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "file1.md", content: "content-1" }, + { type: "create", client: 0, path: "file2.md", content: "content-2" }, + { type: "create", client: 0, path: "file3.md", content: "content-3" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("file1.md", "content-1") + .assertContent("file2.md", "content-2") + .assertContent("file3.md", "content-3"); + } + }, + + { type: "disable-sync", client: 0 }, + + { type: "delete", client: 0, path: "file1.md" }, + { + type: "rename", + client: 0, + oldPath: "file2.md", + newPath: "moved.md" + }, + { + type: "update", + client: 0, + path: "file3.md", + content: "updated-content-3" + }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("file1.md") + .assertFileNotExists("file2.md") + .assertContent("moved.md", "content-2") + .assertContent("file3.md", "updated-content-3") + .assertFileCount(2); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/offline-move-then-remote-delete.test.ts b/frontend/deterministic-tests/src/tests/offline-move-then-remote-delete.test.ts new file mode 100644 index 00000000..f8e92bd9 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/offline-move-then-remote-delete.test.ts @@ -0,0 +1,36 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const offlineMoveThenRemoteDeleteTest: TestDefinition = { + description: + "Client 0 renames A.md to B.md offline while client 1 deletes A.md. " + + "Both clients must converge to having no files.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "A.md", + content: "content to delete" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { type: "rename", client: 0, oldPath: "A.md", newPath: "B.md" }, + + { type: "delete", client: 1, path: "A.md" }, + { type: "sync", client: 1 }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(0); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/offline-multiple-edits.test.ts b/frontend/deterministic-tests/src/tests/offline-multiple-edits.test.ts new file mode 100644 index 00000000..6341fe8f --- /dev/null +++ b/frontend/deterministic-tests/src/tests/offline-multiple-edits.test.ts @@ -0,0 +1,40 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const offlineMultipleEditsTest: TestDefinition = { + description: + "Client 0 creates a file and syncs. Client 0 goes offline, edits the file " + + "5 times with different content. When Client 0 reconnects, both clients " + + "must converge to the final version.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "doc.md", content: "original" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("doc.md", "original"); + } + }, + + { type: "disable-sync", client: 0 }, + + { type: "update", client: 0, path: "doc.md", content: "edit-1" }, + { type: "update", client: 0, path: "doc.md", content: "edit-2" }, + { type: "update", client: 0, path: "doc.md", content: "edit-3" }, + { type: "update", client: 0, path: "doc.md", content: "edit-4" }, + { type: "update", client: 0, path: "doc.md", content: "edit-5-final" }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContent("doc.md", "edit-5-final"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/offline-rename-and-edit.test.ts b/frontend/deterministic-tests/src/tests/offline-rename-and-edit.test.ts new file mode 100644 index 00000000..836c7fb2 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/offline-rename-and-edit.test.ts @@ -0,0 +1,43 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const offlineRenameAndEditTest: TestDefinition = { + description: + "Client 0 creates A.md and syncs. Client 0 goes offline, renames A.md " + + "to B.md, then edits B.md. When Client 0 reconnects, the rename and edit " + + "should both propagate to Client 1.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "original" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("A.md", "original"); + } + }, + + { type: "disable-sync", client: 0 }, + { type: "rename", client: 0, oldPath: "A.md", newPath: "B.md" }, + { + type: "update", + client: 0, + path: "B.md", + content: "edited after rename" + }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("A.md") + .assertFileCount(1) + .assertContent("B.md", "edited after rename"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/offline-rename-remote-create-old-path.test.ts b/frontend/deterministic-tests/src/tests/offline-rename-remote-create-old-path.test.ts new file mode 100644 index 00000000..c1b2913a --- /dev/null +++ b/frontend/deterministic-tests/src/tests/offline-rename-remote-create-old-path.test.ts @@ -0,0 +1,51 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const offlineRenameRemoteCreateOldPathTest: TestDefinition = { + description: + "Client 0 renames X.md to Y.md while offline. Client 1 updates X.md " + + "(same document). When Client 0 reconnects, the rename and update " + + "should merge. Y.md should exist with Client 1's content.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "X.md", content: "original" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("X.md", "original"); + } + }, + + { type: "disable-sync", client: 0 }, + { + type: "rename", + client: 0, + oldPath: "X.md", + newPath: "Y.md" + }, + + { + type: "update", + client: 1, + path: "X.md", + content: "updated-by-client-1" + }, + { type: "sync", client: 1 }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContains( + "Y.md", + "updated-by-client-1" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/offline-update-both-then-delete-one.test.ts b/frontend/deterministic-tests/src/tests/offline-update-both-then-delete-one.test.ts new file mode 100644 index 00000000..3442cda7 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/offline-update-both-then-delete-one.test.ts @@ -0,0 +1,75 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const offlineUpdateBothThenDeleteOneTest: TestDefinition = { + description: + "Client 0 goes offline, updates A.md and B.md, then deletes B.md. " + + "Client 1 updates B.md while Client 0 is offline. When Client 0 " + + "reconnects, A.md should have the update and B.md should be " + + "consistently resolved (delete wins).", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "A.md", + content: "A original" + }, + { + type: "create", + client: 0, + path: "B.md", + content: "B original" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("A.md", "A original").assertContent( + "B.md", + "B original" + ); + } + }, + + { type: "disable-sync", client: 0 }, + + { + type: "update", + client: 0, + path: "A.md", + content: "A updated by client 0" + }, + { + type: "update", + client: 0, + path: "B.md", + content: "B updated by client 0" + }, + + { type: "delete", client: 0, path: "B.md" }, + + { + type: "update", + client: 1, + path: "B.md", + content: "B updated by client 1" + }, + { type: "sync", client: 1 }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent( + "A.md", + "A updated by client 0" + ).assertFileNotExists("B.md"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/online-both-create-same-path-deconflict.test.ts b/frontend/deterministic-tests/src/tests/online-both-create-same-path-deconflict.test.ts new file mode 100644 index 00000000..b951b0be --- /dev/null +++ b/frontend/deterministic-tests/src/tests/online-both-create-same-path-deconflict.test.ts @@ -0,0 +1,34 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const onlineBothCreateSamePathDeconflictTest: TestDefinition = { + description: + "Both clients create a file at the same path while online. " + + "One client's create gets deconflicted by the server. " + + "Both files must exist on both clients after convergence.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "pause-websocket", client: 1 }, + { type: "create", client: 0, path: "A.md", content: " from-client-0 " }, + { type: "update", client: 0, path: "A.md", content: " updated-by-0 " }, + { type: "sync" }, + + { type: "create", client: 1, path: "A.md", content: " from-client-1 " }, + { type: "resume-websocket", client: 1 }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(1) + .assertContains("A.md", "updated-by-0", "from-client-1 "); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/online-create-rename-concurrent-create-orphan.test.ts b/frontend/deterministic-tests/src/tests/online-create-rename-concurrent-create-orphan.test.ts new file mode 100644 index 00000000..f86b3347 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/online-create-rename-concurrent-create-orphan.test.ts @@ -0,0 +1,41 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const onlineCreateRenameConcurrentCreateOrphanTest: TestDefinition = { + description: + "Client 0 creates a binary file and renames it while offline, then reconnects and immediately deletes it. " + + "Both clients must converge to zero files.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + + { + type: "create", + client: 0, + path: "data.bin", + content: "BINARY:offline-content" + }, + { + type: "rename", + client: 0, + oldPath: "data.bin", + newPath: "moved.bin" + }, + + { type: "enable-sync", client: 0 }, + { type: "delete", client: 0, path: "moved.bin" }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state.assertFileCount(0); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/online-create-update-while-other-creates-same-path.test.ts b/frontend/deterministic-tests/src/tests/online-create-update-while-other-creates-same-path.test.ts new file mode 100644 index 00000000..e0ddc21a --- /dev/null +++ b/frontend/deterministic-tests/src/tests/online-create-update-while-other-creates-same-path.test.ts @@ -0,0 +1,48 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const onlineCreateUpdateWhileOtherCreatesSamePathTest: TestDefinition = { + description: + "Client 0 creates a binary file and updates it while client 1 also " + + "creates a binary file at the same path. Both clients are online. " + + "Both clients must end up with the same file set.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + + { type: "pause-websocket", client: 1 }, + { + type: "create", + client: 0, + path: "data.bin", + content: "BINARY:content-v1" + }, + { + type: "update", + client: 0, + path: "data.bin", + content: "BINARY:content-v2" + }, + { + type: "create", + client: 1, + path: "data.bin", + content: "BINARY:other-content" + }, + { type: "resume-websocket", client: 1 }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(2) + .assertNoFileContains("content-v1") + .assertAnyFileContains("content-v2") + .assertAnyFileContains("other-content"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/online-delete-recreate-rapid-cycle.test.ts b/frontend/deterministic-tests/src/tests/online-delete-recreate-rapid-cycle.test.ts new file mode 100644 index 00000000..de5d6c89 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/online-delete-recreate-rapid-cycle.test.ts @@ -0,0 +1,37 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const onlineDeleteRecreateRapidCycleTest: TestDefinition = { + description: + "A file is deleted and recreated multiple times by alternating clients while both are online. " + + "Both clients must converge after each cycle.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "round 0" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "delete", client: 1, path: "A.md" }, + { type: "barrier" }, + { type: "create", client: 0, path: "A.md", content: "round 1" }, + { type: "barrier" }, + + { type: "delete", client: 0, path: "A.md" }, + { type: "barrier" }, + { type: "create", client: 1, path: "A.md", content: "round 2" }, + { type: "barrier" }, + + { type: "delete", client: 1, path: "A.md" }, + { type: "barrier" }, + { type: "create", client: 0, path: "A.md", content: "round 3" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("A.md", "round 3"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/online-edit-vs-delete-convergence.test.ts b/frontend/deterministic-tests/src/tests/online-edit-vs-delete-convergence.test.ts new file mode 100644 index 00000000..d3a9d84e --- /dev/null +++ b/frontend/deterministic-tests/src/tests/online-edit-vs-delete-convergence.test.ts @@ -0,0 +1,31 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const onlineEditVsDeleteConvergenceTest: TestDefinition = { + description: + "Both clients are online. Client 0 edits a file while client 1 " + + "deletes it. The clients must converge to the same state.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "original" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "update", + client: 0, + path: "A.md", + content: "edited by client 0" + }, + { type: "delete", client: 1, path: "A.md" }, + + { type: "barrier" }, + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state.assertFileCount(0); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/overlapping-edits-same-section.test.ts b/frontend/deterministic-tests/src/tests/overlapping-edits-same-section.test.ts new file mode 100644 index 00000000..a93a6f69 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/overlapping-edits-same-section.test.ts @@ -0,0 +1,54 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const overlappingEditsSameSectionTest: TestDefinition = { + description: + "Both clients go offline and edit different parts of the same document. " + + "After both reconnect, both edits must be preserved without data loss.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "doc.md", + content: "# Title\n\nfooter" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + + { + type: "update", + client: 0, + path: "doc.md", + content: "# Title\nalpha addition\n\nfooter" + }, + + { + type: "update", + client: 1, + path: "doc.md", + content: "# Title\n\nbeta addition\nfooter" + }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContains( + "doc.md", + "# Title", + "alpha addition", + "beta addition", + "footer" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/queue-reset-loses-coalesced-local-edit.test.ts b/frontend/deterministic-tests/src/tests/queue-reset-loses-coalesced-local-edit.test.ts new file mode 100644 index 00000000..6d89acf4 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/queue-reset-loses-coalesced-local-edit.test.ts @@ -0,0 +1,36 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const queueResetLosesCoalescedLocalEditTest: TestDefinition = { + description: + "Client 0 goes offline, both clients edit doc.md concurrently, " + + "then client 0 reconnects. Both edits must be preserved.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "doc.md", content: "original" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + + { type: "update", client: 1, path: "doc.md", content: "alpha bravo" }, + { type: "sync", client: 1 }, + + { type: "update", client: 0, path: "doc.md", content: "charlie delta" }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContains( + "doc.md", + "alpha", + "charlie" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/queued-create-delete-does-not-hijack-reused-path.test.ts b/frontend/deterministic-tests/src/tests/queued-create-delete-does-not-hijack-reused-path.test.ts new file mode 100644 index 00000000..a29f8314 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/queued-create-delete-does-not-hijack-reused-path.test.ts @@ -0,0 +1,56 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const queuedCreateDeleteDoesNotHijackReusedPathTest: TestDefinition = { + description: + "A create/delete pair that is still queued behind another request " + + "must collapse locally. It must not later read a different file " + + "that reused the same path before the queued create drained.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "pause-server" }, + { + type: "create", + client: 1, + path: "blocker.bin", + content: "BINARY:blocker" + }, + { type: "sleep", ms: 100 }, + { + type: "create", + client: 1, + path: "target.bin", + content: "BINARY:old" + }, + { type: "delete", client: 1, path: "target.bin" }, + { + type: "create", + client: 1, + path: "source.bin", + content: "BINARY:new" + }, + { + type: "rename", + client: 1, + oldPath: "source.bin", + newPath: "target.bin" + }, + { type: "resume-server" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(2) + .assertContent("blocker.bin", "BINARY:blocker") + .assertContent("target.bin", "BINARY:new") + .assertFileNotExists("source.bin"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/rapid-create-update-delete-cycle.test.ts b/frontend/deterministic-tests/src/tests/rapid-create-update-delete-cycle.test.ts new file mode 100644 index 00000000..f9c58753 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/rapid-create-update-delete-cycle.test.ts @@ -0,0 +1,52 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const rapidCreateUpdateDeleteCycleTest: TestDefinition = { + description: + "Client 0 rapidly creates, updates, deletes, then re-creates a file while the server is paused. " + + "After the server resumes, client 1 must see only the final file.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "pause-server" }, + + { + type: "create", + client: 0, + path: "cycle.md", + content: "version 1" + }, + { + type: "update", + client: 0, + path: "cycle.md", + content: "version 2" + }, + { type: "delete", client: 0, path: "cycle.md" }, + + { type: "resume-server" }, + { type: "sync" }, + + { + type: "create", + client: 0, + path: "cycle.md", + content: "final creation" + }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContent( + "cycle.md", + "final creation" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/rapid-edit-delete-online-convergence.test.ts b/frontend/deterministic-tests/src/tests/rapid-edit-delete-online-convergence.test.ts new file mode 100644 index 00000000..48c062e0 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/rapid-edit-delete-online-convergence.test.ts @@ -0,0 +1,48 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const rapidEditDeleteOnlineConvergenceTest: TestDefinition = { + description: + "Client 0 rapidly edits multiple files while client 1 deletes some of them, all while both are online. " + + "Both clients must converge to a consistent state.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "content A" }, + { type: "create", client: 0, path: "B.md", content: "content B" }, + { type: "create", client: 0, path: "C.md", content: "content C" }, + { type: "create", client: 0, path: "D.md", content: "content D" }, + { type: "create", client: 0, path: "E.md", content: "content E" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "update", client: 0, path: "A.md", content: "A edit 1" }, + { type: "update", client: 0, path: "B.md", content: "B edit 1" }, + { type: "update", client: 0, path: "C.md", content: "C edit 1" }, + { type: "delete", client: 1, path: "A.md" }, + { type: "delete", client: 1, path: "C.md" }, + { type: "delete", client: 1, path: "E.md" }, + { type: "update", client: 0, path: "A.md", content: "A edit 2" }, + { type: "update", client: 0, path: "B.md", content: "B edit 2" }, + { type: "update", client: 0, path: "C.md", content: "C edit 2" }, + + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + for (const [path, content] of s.files) { + for (const clientFiles of s.clientFiles) { + if ( + clientFiles.has(path) && + clientFiles.get(path) !== content + ) { + throw new Error( + `Content mismatch for ${path}: "${clientFiles.get(path)}" vs "${content}"` + ); + } + } + } + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/rapid-updates-after-merge.test.ts b/frontend/deterministic-tests/src/tests/rapid-updates-after-merge.test.ts new file mode 100644 index 00000000..6f97ff05 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/rapid-updates-after-merge.test.ts @@ -0,0 +1,49 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const rapidUpdatesAfterMergeTest: TestDefinition = { + description: + "Both clients create the same file offline, triggering a merge on sync. " + + "Client 0 then rapidly sends three updates. Both clients must converge to the final update.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "doc.md", content: "from client 0" }, + { type: "create", client: 1, path: "doc.md", content: "from client 1" }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "update", + client: 0, + path: "doc.md", + content: "update 1" + }, + { type: "sync", client: 0 }, + + { + type: "update", + client: 0, + path: "doc.md", + content: "update 2" + }, + { type: "sync", client: 0 }, + + { + type: "update", + client: 0, + path: "doc.md", + content: "update 3" + }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContains("doc.md", "update 3"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/recently-deleted-cleared-on-reconnect.test.ts b/frontend/deterministic-tests/src/tests/recently-deleted-cleared-on-reconnect.test.ts new file mode 100644 index 00000000..c8e70243 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/recently-deleted-cleared-on-reconnect.test.ts @@ -0,0 +1,45 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const recentlyDeletedClearedOnReconnectTest: TestDefinition = { + description: + "After a client deletes a document and reconnects, it should " + + "accept new documents from other clients even if they happen to " + + "arrive at the same path as the deleted document.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + + { type: "create", client: 0, path: "doc.md", content: "original" }, + { type: "sync" }, + + { type: "delete", client: 0, path: "doc.md" }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + + { + type: "create", + client: 1, + path: "doc.md", + content: "new content from client 1" + }, + + { type: "enable-sync", client: 1 }, + { type: "sync", client: 1 }, + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContent( + "doc.md", + "new content from client 1" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/remote-quick-write-rename-before-record.test.ts b/frontend/deterministic-tests/src/tests/remote-quick-write-rename-before-record.test.ts new file mode 100644 index 00000000..ca184b27 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/remote-quick-write-rename-before-record.test.ts @@ -0,0 +1,36 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const remoteQuickWriteRenameBeforeRecordTest: TestDefinition = { + description: + "Client 0 receives a remote create and the user renames the new " + + "file immediately after the syncer writes it. The watcher event " + + "must bind to the new document instead of being dropped before " + + "the remote-create handler persists the record.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + + { + type: "rename-next-write", + client: 0, + oldPath: "doc.md", + newPath: "renamed.md" + }, + + { type: "create", client: 1, path: "doc.md", content: "v1\n" }, + { type: "sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1); + s.assertFileExists("renamed.md"); + s.assertFileNotExists("doc.md"); + s.assertContent("renamed.md", "v1\n"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/remote-rename-collides-with-pending-local-create.test.ts b/frontend/deterministic-tests/src/tests/remote-rename-collides-with-pending-local-create.test.ts new file mode 100644 index 00000000..d30fdc67 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/remote-rename-collides-with-pending-local-create.test.ts @@ -0,0 +1,76 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const remoteRenameCollidesWithPendingLocalCreateTest: TestDefinition = { + // TODO(refactor): the failure mode described below is the + // pre-refactor "deflect-to-conflict-uuid" path that no longer + // exists. Under the new model the wire loop never moves files for + // path placement, so the remote rename can't deflect anywhere; the + // reconciler waits for the slot to free. Convergence assertion is + // still valid (no conflict-uuid stashes, both files present, the + // local create lands at a server-deconflicted sibling). + description: + "Client 0 has doc D tracked at `original.md`. Client 1 owns doc E " + + "and renames it to `target.md` server-side. Before client 0's " + + "drain processes the WS broadcast for E, the user creates a new " + + "local file `target.md` (a different doc, untracked). When the " + + "buffered RemoteChange for E drains, the engine has to reconcile " + + "doc E onto `target.md` even though the slot is held by client " + + "0's pending LocalCreate. Convergence requires both clients end " + + "up with [target.md = E] and the local create lands at a " + + "server-deconflicted sibling (e.g. `target (1).md`).", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + + { type: "create", client: 1, path: "original.md", content: "v1\n" }, + { type: "barrier" }, + + // Pause client 0's WS so the upcoming remote rename buffers and + // we can stage a colliding local create before the rename + // drains on client 0. + { type: "pause-websocket", client: 0 }, + + // Client 1 renames the doc. Server commits, broadcasts to + // client 0 (buffered). + { + type: "rename", + client: 1, + oldPath: "original.md", + newPath: "target.md" + }, + { type: "sync", client: 1 }, + + // Client 0 still believes the doc is at `original.md`. The user + // creates a NEW file at `target.md` (an unrelated untracked + // doc). Disk on client 0 now has both `original.md` (the + // tracked doc) and `target.md` (the new untracked file). + { type: "create", client: 0, path: "target.md", content: "extra\n" }, + + // Resume client 0's WS. The buffered RemoteChange drains. + // The reconciler must converge without ever leaving a + // conflict-uuid stash on disk. + { type: "resume-websocket", client: 0 }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state.assertFileCount(2); + for (const path of state.files.keys()) { + if (path.startsWith("conflict-")) { + throw new Error( + `Unexpected conflict-uuid stash on a converged client: ${path}` + ); + } + } + state.assertFileExists("target.md"); + state.assertContent("target.md", "v1\n"); + // The local create gets server-deconflicted to a + // sibling path (e.g. `target (1).md`). + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/remote-update-resurrects-deleted-doc.test.ts b/frontend/deterministic-tests/src/tests/remote-update-resurrects-deleted-doc.test.ts new file mode 100644 index 00000000..eb2ed86d --- /dev/null +++ b/frontend/deterministic-tests/src/tests/remote-update-resurrects-deleted-doc.test.ts @@ -0,0 +1,59 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const remoteUpdateResurrectsDeletedDocTest: TestDefinition = { + description: + "Client 1 updates, deletes, and recreates P (with a new docId D2). " + + "While the buffered remote events are being processed by client 0, " + + "client 0 also makes a local edit to P. The local edit lands in the " + + "queue while v17 is mid-process, sending v17 down processRemoteUpdate's " + + "re-enqueue branch. The deferred v17 must NOT later resurrect D1 as a " + + "conflict-… file at P after the delete and the D2 create have drained.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + + { type: "create", client: 1, path: "P.md", content: "v8 content\n" }, + { type: "barrier" }, + + { type: "pause-websocket", client: 0 }, + + { + type: "update", + client: 1, + path: "P.md", + content: "v17 content from client 1\n" + }, + { type: "sync", client: 1 }, + { type: "delete", client: 1, path: "P.md" }, + { type: "sync", client: 1 }, + { + type: "create", + client: 1, + path: "P.md", + content: "v21 content (D2)\n" + }, + { type: "sync", client: 1 }, + + { type: "resume-websocket", client: 0 }, + + { + type: "update", + client: 0, + path: "P.md", + content: "local edit by client 0\n" + }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(1) + .assertContent("P.md", "v21 content (D2)\n"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/remote-update-survives-user-rename.test.ts b/frontend/deterministic-tests/src/tests/remote-update-survives-user-rename.test.ts new file mode 100644 index 00000000..b78ad143 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/remote-update-survives-user-rename.test.ts @@ -0,0 +1,84 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const remoteUpdateSurvivesUserRenameTest: TestDefinition = { + description: + "Client 0 updates a tracked doc; while Client 1 is processing the " + + "broadcast and parked on the GET for the new version's content, the " + + "user renames the doc on Client 1. Pre-fix: `processRemoteUpdate` " + + "captures `actualPath` before the await and, after the GET returns, " + + "calls `write(actualPath, …)` (no-op — file was renamed away), " + + "`updateCache(actualPath, …)`, and `setDocument(actualPath, …)`. " + + "`setDocument` mutates the same record in place so its `path` is " + + "yanked from the user's renamed slot back to the pre-rename path, " + + "wiping the rename out of the queue's documents map. The queued " + + "`LocalUpdate` then reads from the now-stale `record.path`, hits " + + "`FileNotFoundError`, and is silently dropped — the user's rename " + + "never reaches the server. Post-fix: the handler defers when a " + + "local event landed mid-await, so the rename drains first and " + + "the deferred remote update is folded into the broadcast that " + + "follows the rename round-trip.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "doc.md", content: "v1\n" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + // Buffer Client 1's incoming broadcasts so it doesn't see + // Client 0's update until we've paused the server. + { type: "pause-websocket", client: 1 }, + + // Server now holds v=2 of doc.md. + { type: "update", client: 0, path: "doc.md", content: "v2\n" }, + { type: "sync", client: 0 }, + + // Pause the server. Client 1's upcoming GET for the new version + // content blocks at the OS layer until resume. + { type: "pause-server" }, + + // Release the buffered broadcast. Client 1's drain enters + // `processRemoteUpdate`, captures `actualPath`, fires the GET, + // and parks awaiting the response. + { type: "resume-websocket", client: 1 }, + + // Yield long enough for the drain to traverse all microtask + // hops between the WS handler and the GET, so the HTTP request + // is queued at the (paused) server before the rename runs. + // Without this yield the rename would be enqueued before + // `processRemoteUpdate`'s entry-time `hasPendingLocalEvents` + // check and the early-defer branch would mask the bug. + { type: "sleep", ms: 50 }, + + // While the GET is in flight the user renames the doc. The queue + // mutates `record.path` to "renamed.md" in place and pushes a + // LocalUpdate carrying the rename target. + { + type: "rename", + client: 1, + oldPath: "doc.md", + newPath: "renamed.md" + }, + + // Resume the server. The GET response unblocks + // `processRemoteUpdate`. With the fix in place it sees the + // queued LocalUpdate and defers; without the fix it walks past + // the rename and clobbers the documents map, dropping the + // pending LocalUpdate's read on the way back through. + { type: "resume-server" }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1); + s.assertFileExists("renamed.md"); + s.assertFileNotExists("doc.md"); + // Both edits survive: the user's rename and Client 0's + // content update at v=2. + s.assertContent("renamed.md", "v2\n"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/rename-chain-during-pending-create.test.ts b/frontend/deterministic-tests/src/tests/rename-chain-during-pending-create.test.ts new file mode 100644 index 00000000..822e83df --- /dev/null +++ b/frontend/deterministic-tests/src/tests/rename-chain-during-pending-create.test.ts @@ -0,0 +1,64 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const renameChainDuringPendingCreateTest: TestDefinition = { + description: + "User creates a doc, then renames it twice while the LocalCreate's " + + "HTTP roundtrip is still in flight (server paused). Each rename " + + "pushes a LocalUpdate whose `documentId` is the create's Promise " + + "(see `pendingDocumentId` in `SyncEventQueue.enqueue`). After the " + + "create resolves, the first rename drains successfully and " + + "`setDocument` walks `events[]` to retarget queued LocalUpdates' " + + "`event.path` to the new disk location — but the comparison " + + "`e.documentId === record.documentId` mismatches the still-Promise " + + "references, so the second rename's `event.path` stays at the " + + "vacated previous slot. On the next drain step `skipIfOversized`'s " + + "`getFileSize(event.path)` throws FileNotFoundError, which " + + "`processEvent` swallows as 'Skipping sync event ... because the " + + "file no longer exists' — losing the user's final rename. " + + "Post-fix: `resolveCreate` (and the displacement-merge branch in " + + "`processCreate`) swap the Promise references for the resolved id " + + "before `setDocument` runs, so retarget works.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + // Pause the server so client 0's create stalls on the HTTP PUT + // while we queue rename events behind it. + { type: "pause-server" }, + + { type: "create", client: 0, path: "first.md", content: "v1\n" }, + { + type: "rename", + client: 0, + oldPath: "first.md", + newPath: "second.md" + }, + { + type: "rename", + client: 0, + oldPath: "second.md", + newPath: "third.md" + }, + + // Resume — drain pops LocalCreate (now resolves), then the two + // queued LocalUpdates. Pre-fix: only the first rename's + // file-system effect lands; the second is silently dropped. + // The server ends up with the doc at second.md, leaving + // client 0's local third.md untracked / out-of-sync. + { type: "resume-server" }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state.assertFileCount(1); + state.assertFileExists("third.md"); + state.assertContent("third.md", "v1\n"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/rename-chain-then-delete.test.ts b/frontend/deterministic-tests/src/tests/rename-chain-then-delete.test.ts new file mode 100644 index 00000000..03196919 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/rename-chain-then-delete.test.ts @@ -0,0 +1,50 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const renameChainThenDeleteTest: TestDefinition = { + description: + "Client 0 renames X.md to Y.md to Z.md, then deletes Z.md while client 1 is offline. " + + "After client 1 reconnects, both clients must have no files.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "X.md", content: "chain-content" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("X.md", "chain-content"); + } + }, + + { type: "disable-sync", client: 1 }, + + { + type: "rename", + client: 0, + oldPath: "X.md", + newPath: "Y.md" + }, + { type: "sync", client: 0 }, + { + type: "rename", + client: 0, + oldPath: "Y.md", + newPath: "Z.md" + }, + { type: "sync", client: 0 }, + { type: "delete", client: 0, path: "Z.md" }, + { type: "sync", client: 0 }, + + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(0); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/rename-chain.test.ts b/frontend/deterministic-tests/src/tests/rename-chain.test.ts new file mode 100644 index 00000000..8f9d7a7f --- /dev/null +++ b/frontend/deterministic-tests/src/tests/rename-chain.test.ts @@ -0,0 +1,34 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const renameChainTest: TestDefinition = { + description: + "Client 0 (offline) creates A.md, renames to B.md, then renames to C.md. " + + "When sync is enabled, only C.md should exist. Client 1 should receive C.md " + + "with the original content. Intermediate paths should never appear.", + clients: 2, + steps: [ + { type: "enable-sync", client: 1 }, + + { + type: "create", + client: 0, + path: "A.md", + content: "important content" + }, + { type: "rename", client: 0, oldPath: "A.md", newPath: "B.md" }, + { type: "rename", client: 0, oldPath: "B.md", newPath: "C.md" }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("A.md") + .assertFileNotExists("B.md") + .assertContent("C.md", "important content"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/rename-circular.test.ts b/frontend/deterministic-tests/src/tests/rename-circular.test.ts new file mode 100644 index 00000000..44a65149 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/rename-circular.test.ts @@ -0,0 +1,44 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const renameCircularTest: TestDefinition = { + description: + "Client 0 creates three files, syncs, then goes offline and performs a circular rename via a temp file (A->temp, C->A, B->C, temp->B). After reconnecting, all three contents should exist across three files but paths may be deconflicted.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "content-a" }, + { type: "create", client: 0, path: "B.md", content: "content-b" }, + { type: "create", client: 0, path: "C.md", content: "content-c" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("A.md", "content-a") + .assertContent("B.md", "content-b") + .assertContent("C.md", "content-c"); + } + }, + + { type: "disable-sync", client: 0 }, + { type: "rename", client: 0, oldPath: "A.md", newPath: "temp-a.md" }, + { type: "rename", client: 0, oldPath: "C.md", newPath: "A.md" }, + { type: "rename", client: 0, oldPath: "B.md", newPath: "C.md" }, + { type: "rename", client: 0, oldPath: "temp-a.md", newPath: "B.md" }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("temp-a.md") + .assertFileCount(3) + .assertAnyFileContains("content-c") + .assertAnyFileContains("content-a") + .assertAnyFileContains("content-b"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/rename-create-conflict.test.ts b/frontend/deterministic-tests/src/tests/rename-create-conflict.test.ts new file mode 100644 index 00000000..fc6a00a7 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/rename-create-conflict.test.ts @@ -0,0 +1,34 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const renameCreateConflictTest: TestDefinition = { + description: + "Client 0 creates A.md and syncs. Client 1 renames A.md to B.md and syncs. Client 0 (offline) creates B.md with the same content. After reconnecting, both clients should converge with only B.md.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "create", client: 0, path: "A.md", content: "hi" }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("A.md", "hi"); + } + }, + { type: "disable-sync", client: 0 }, + { type: "rename", client: 1, oldPath: "A.md", newPath: "B.md" }, + { type: "sync", client: 1 }, + { type: "create", client: 0, path: "B.md", content: "hi" }, + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(2) + .assertContent("B.md", "hi") + .assertContent("B (1).md", "hi"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/rename-overwrites-pending-create-then-delete.test.ts b/frontend/deterministic-tests/src/tests/rename-overwrites-pending-create-then-delete.test.ts new file mode 100644 index 00000000..0b47c781 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/rename-overwrites-pending-create-then-delete.test.ts @@ -0,0 +1,51 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const renameOverwritesPendingCreateThenDeleteTest: TestDefinition = { + description: + "A pending local create at a path must not mask a synced document renamed onto that path; later rename/delete events still belong to the synced document.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { + type: "create", + client: 0, + path: "tracked.bin", + content: "BINARY:tracked" + }, + { type: "barrier" }, + + { type: "pause-server" }, + + { + type: "create", + client: 0, + path: "pending.bin", + content: "BINARY:pending" + }, + { + type: "rename", + client: 0, + oldPath: "tracked.bin", + newPath: "pending.bin" + }, + { + type: "rename", + client: 0, + oldPath: "pending.bin", + newPath: "final.bin" + }, + { type: "delete", client: 0, path: "final.bin" }, + + { type: "resume-server" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state.assertFileCount(0); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/rename-pending-create-before-response.test.ts b/frontend/deterministic-tests/src/tests/rename-pending-create-before-response.test.ts new file mode 100644 index 00000000..26623c43 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/rename-pending-create-before-response.test.ts @@ -0,0 +1,42 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const renamePendingCreateBeforeResponseTest: TestDefinition = { + description: + "Client 0 creates a file while the server is paused, then renames it before the create completes. After the server resumes, both clients should converge with the file at the renamed path.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + + { type: "pause-server" }, + + { + type: "create", + client: 0, + path: "doc.md", + content: "original-content" + }, + + { + type: "rename", + client: 0, + oldPath: "doc.md", + newPath: "renamed.md" + }, + + { type: "resume-server" }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContent( + "renamed.md", + "original-content" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/rename-pending-create-onto-pending-delete-path.test.ts b/frontend/deterministic-tests/src/tests/rename-pending-create-onto-pending-delete-path.test.ts new file mode 100644 index 00000000..0906f209 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/rename-pending-create-onto-pending-delete-path.test.ts @@ -0,0 +1,59 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const renamePendingCreateOntoPendingDeletePathTest: TestDefinition = { + description: + "A pending create is renamed onto a path whose old server document " + + "has a queued delete. The delete must reach the server before the " + + "new create so the new generation is not merged into the soon-to-be " + + "deleted document.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "create", + client: 1, + path: "file-17.md", + content: "old\n" + }, + { type: "barrier" }, + + { type: "pause-server" }, + { + type: "create", + client: 1, + path: "blocker.md", + content: "blocker\n" + }, + { type: "sleep", ms: 100 }, + { + type: "create", + client: 1, + path: "file-23.md", + content: "new\n" + }, + { type: "delete", client: 1, path: "file-17.md" }, + { + type: "rename", + client: 1, + oldPath: "file-23.md", + newPath: "file-17.md" + }, + { type: "resume-server" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(2) + .assertContent("blocker.md", "blocker\n") + .assertContent("file-17.md", "new\n") + .assertFileNotExists("file-23.md"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/rename-roundtrip.test.ts b/frontend/deterministic-tests/src/tests/rename-roundtrip.test.ts new file mode 100644 index 00000000..0373debf --- /dev/null +++ b/frontend/deterministic-tests/src/tests/rename-roundtrip.test.ts @@ -0,0 +1,40 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const renameRoundtripTest: TestDefinition = { + description: + "Client 0 creates A.md, renames it to B.md, then renames it back to A.md. After each step both clients sync. Both should end with only A.md at the original path.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "original" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("A.md", "original"); + } + }, + + { type: "rename", client: 0, oldPath: "A.md", newPath: "B.md" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("A.md").assertContent("B.md", "original"); + } + }, + + { type: "rename", client: 0, oldPath: "B.md", newPath: "A.md" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("B.md").assertContent("A.md", "original"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/rename-swap.test.ts b/frontend/deterministic-tests/src/tests/rename-swap.test.ts new file mode 100644 index 00000000..9910e8ef --- /dev/null +++ b/frontend/deterministic-tests/src/tests/rename-swap.test.ts @@ -0,0 +1,44 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const renameSwapTest: TestDefinition = { + description: + "Client 0 has A.md and B.md synced. Goes offline and swaps them using " + + "a temp file: A.md -> temp.md, B.md -> A.md, temp.md -> B.md. " + + "When Client 0 reconnects, both contents should exist across two files.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "content-a" }, + { type: "create", client: 0, path: "B.md", content: "content-b" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("A.md", "content-a").assertContent( + "B.md", + "content-b" + ); + } + }, + + { type: "disable-sync", client: 0 }, + { type: "rename", client: 0, oldPath: "A.md", newPath: "temp.md" }, + { type: "rename", client: 0, oldPath: "B.md", newPath: "A.md" }, + { type: "rename", client: 0, oldPath: "temp.md", newPath: "B.md" }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("temp.md") + .assertFileCount(2) + .assertAnyFileContains("content-b") + .assertAnyFileContains("content-a"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/rename-to-path-of-unconfirmed-delete.test.ts b/frontend/deterministic-tests/src/tests/rename-to-path-of-unconfirmed-delete.test.ts new file mode 100644 index 00000000..34a3867c --- /dev/null +++ b/frontend/deterministic-tests/src/tests/rename-to-path-of-unconfirmed-delete.test.ts @@ -0,0 +1,44 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const renameToPathOfUnconfirmedDeleteTest: TestDefinition = { + description: + "Client 0 deletes A.md then renames B.md to A.md. After syncing, " + + "B's content should exist and the old A.md content should be gone. " + + "The server may deconflict the path if the delete and move arrive " + + "in the same transaction.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "A.md", + content: "content A" + }, + { + type: "create", + client: 0, + path: "B.md", + content: "content B" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "sync" }, + + { type: "delete", client: 0, path: "A.md" }, + { type: "barrier" }, + + { type: "rename", client: 0, oldPath: "B.md", newPath: "A.md" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("B.md").assertContains( + "A.md", + "content B" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/rename-to-pending-path-fallback.test.ts b/frontend/deterministic-tests/src/tests/rename-to-pending-path-fallback.test.ts new file mode 100644 index 00000000..8747218a --- /dev/null +++ b/frontend/deterministic-tests/src/tests/rename-to-pending-path-fallback.test.ts @@ -0,0 +1,43 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const renameToPendingPathFallbackTest: TestDefinition = { + description: + "Client 0 creates B.md and syncs. Goes offline, creates A.md, then renames B.md to A.md (overwriting the unsynced A). After reconnecting, B.md should be gone and A.md should have B's content.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "B.md", + content: "tracked B content" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + + { + type: "create", + client: 0, + path: "A.md", + content: "pending A content" + }, + + { type: "rename", client: 0, oldPath: "B.md", newPath: "A.md" }, + + { type: "enable-sync", client: 0 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("B.md").assertContains( + "A.md", + "tracked B content" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/rename-update-conflict.test.ts b/frontend/deterministic-tests/src/tests/rename-update-conflict.test.ts new file mode 100644 index 00000000..18d4c101 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/rename-update-conflict.test.ts @@ -0,0 +1,42 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const renameUpdateConflictTest: TestDefinition = { + description: + "Client 0 renames A.md to B.md while client 1 updates A.md offline. After client 1 reconnects, both should converge with the update at B.md.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "original" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("A.md", "original"); + } + }, + + { type: "disable-sync", client: 1 }, + + { type: "rename", client: 0, oldPath: "A.md", newPath: "B.md" }, + { type: "sync", client: 0 }, + + { + type: "update", + client: 1, + path: "A.md", + content: "updated by client 1" + }, + + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("A.md").assertContains("B.md", "updated"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/renamed-pending-create-reused-path-then-delete.test.ts b/frontend/deterministic-tests/src/tests/renamed-pending-create-reused-path-then-delete.test.ts new file mode 100644 index 00000000..3ffb376e --- /dev/null +++ b/frontend/deterministic-tests/src/tests/renamed-pending-create-reused-path-then-delete.test.ts @@ -0,0 +1,65 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const renamedPendingCreateReusedPathThenDeleteTest: TestDefinition = { + description: + "A queued create is renamed away from file-59.md, a newer local " + + "file reuses file-59.md before the queued create drains, and the " + + "renamed-away generation is deleted. The delete must not erase or " + + "orphan the newer file-59.md generation.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "pause-server" }, + { + type: "create", + client: 1, + path: "blocker.md", + content: "blocker\n" + }, + { type: "sleep", ms: 100 }, + + { + type: "create", + client: 1, + path: "file-59.md", + content: "old\n" + }, + { + type: "rename", + client: 1, + oldPath: "file-59.md", + newPath: "file-33.md" + }, + { + type: "create", + client: 1, + path: "file-59.md", + content: "new\n" + }, + + { + type: "resume-server-until-history-then-pause", + client: 1, + syncType: "CREATE", + path: "file-33.md" + }, + { type: "delete", client: 1, path: "file-33.md" }, + { type: "resume-server" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(2) + .assertContent("blocker.md", "blocker\n") + .assertContent("file-59.md", "new\n") + .assertFileNotExists("file-33.md"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/reset-clears-recently-deleted-resurrection.test.ts b/frontend/deterministic-tests/src/tests/reset-clears-recently-deleted-resurrection.test.ts new file mode 100644 index 00000000..e0a1565c --- /dev/null +++ b/frontend/deterministic-tests/src/tests/reset-clears-recently-deleted-resurrection.test.ts @@ -0,0 +1,43 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const resetClearsRecentlyDeletedResurrectionTest: TestDefinition = { + description: + "Client 0 deletes a file. Client 1 toggles sync off and on " + + "(simulating reconnect). The deleted file should NOT reappear " + + "on Client 1 after the sync reset.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "ghost.md", + content: "should be deleted" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "delete", client: 0, path: "ghost.md" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("ghost.md"); + } + }, + + { type: "disable-sync", client: 1 }, + { type: "enable-sync", client: 1 }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(0); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/same-doc-id-collapse-after-remote-quick-write-and-pending-rename.test.ts b/frontend/deterministic-tests/src/tests/same-doc-id-collapse-after-remote-quick-write-and-pending-rename.test.ts new file mode 100644 index 00000000..2a3b5de4 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/same-doc-id-collapse-after-remote-quick-write-and-pending-rename.test.ts @@ -0,0 +1,82 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const sameDocIdCollapseAfterRemoteQuickWriteAndPendingRenameTest: TestDefinition = + { + description: + "A remote create starts quick-writing at doc.md while a local " + + "create for the same path is queued and renamed to renamed.md. " + + "Because the local create was renamed before it reached the " + + "server, the two generations should remain separate tracked " + + "documents.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + + // Create a deleted latest version before client 1 joins. + // Catch-up will advance MinCovered with a non-contiguous id, + // keeping client 1's create lastSeen low enough to exercise + // the server's same-doc merge path from the e2e failure. + { + type: "create", + client: 0, + path: "history.md", + content: "history-v1" + }, + { type: "sync", client: 0 }, + { + type: "update", + client: 0, + path: "history.md", + content: "history-v2" + }, + { type: "sync", client: 0 }, + { type: "delete", client: 0, path: "history.md" }, + { type: "sync", client: 0 }, + + { type: "enable-sync", client: 1 }, + { type: "sync", client: 1 }, + + { type: "pause-websocket", client: 1 }, + + { + type: "create", + client: 0, + path: "doc.md", + content: "remote\n" + }, + { type: "sync", client: 0 }, + + // Let client 1's buffered RemoteCreate enter the quick-write + // path, but hold the content fetch until the local create has + // appeared and moved away from doc.md. + { type: "pause-server" }, + { type: "resume-websocket", client: 1 }, + { type: "sleep", ms: 100 }, + + { + type: "create", + client: 1, + path: "doc.md", + content: "local\n" + }, + { + type: "rename", + client: 1, + oldPath: "doc.md", + newPath: "renamed.md" + }, + + { type: "resume-server" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state.assertFileCount(2); + state.assertContent("doc.md", "remote\n"); + state.assertContent("renamed.md", "local\n"); + } + } + ] + }; diff --git a/frontend/deterministic-tests/src/tests/same-doc-id-collapse-on-local-create-after-remote-create.test.ts b/frontend/deterministic-tests/src/tests/same-doc-id-collapse-on-local-create-after-remote-create.test.ts new file mode 100644 index 00000000..dee3a9ad --- /dev/null +++ b/frontend/deterministic-tests/src/tests/same-doc-id-collapse-on-local-create-after-remote-create.test.ts @@ -0,0 +1,121 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const sameDocIdCollapseOnLocalCreateAfterRemoteCreateTest: TestDefinition = + { + description: + "Client B creates X with content C2; the server commits and " + + "broadcasts. Client A's WS is paused so the RemoteCreate buffers. " + + "Server is then paused so A's about-to-POST LocalCreate will " + + "hang. A creates X with content C1: file lands on disk, " + + "LocalCreate enqueues, drain starts the POST, the POST stalls " + + "at the paused server. A's WS is resumed: the buffered " + + "RemoteCreate for doc-X is delivered to A and enqueues behind " + + "the in-flight LocalCreate. Per the lazy-paths model, when " + + "the RemoteCreate is processed it observes that path X is " + + "occupied locally by A's pending-create bytes, so it tracks " + + "doc-X with `localPath = undefined` / `remoteRelativePath = " + + "X` and does NOT fetch content. The server is then resumed: " + + "A's LocalCreate POST returns. The server, finding X already " + + "taken by doc-X, replies with doc-X's existing documentId " + + "(typically a MergingUpdate carrying the merged bytes). A's " + + "processCreate handler detects that response.documentId " + + "matches the no-localPath record built from the RemoteCreate " + + "and collapses the two: it sets localPath = X on that " + + "record, writes the merged bytes, and resolves the pending " + + "create promise. Final state: exactly one file at X on both " + + "clients, both pointing at doc-X's documentId, content " + + "carrying both contributions, and no conflict-- " + + "stash anywhere.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + // Buffer broadcasts to client 0 (A) so client 1's create + // doesn't reach A's WS handler until we say so. + { type: "pause-websocket", client: 0 }, + + // Client 1 (B) commits doc-X at path X with content C2. + // The server commits, broadcasts (broadcast queued at A's + // paused WS). + { + type: "create", + client: 1, + path: "X.md", + content: "from-client-1 " + }, + { type: "sync", client: 1 }, + + // Pause the server so A's upcoming LocalCreate POST hangs. + // This holds A's drain on the in-flight POST while we + // release the WS so the RemoteCreate enqueues behind it. + { type: "pause-server" }, + + // Client 0 (A) creates X locally with content C1. The + // file lands on A's disk; LocalCreate enqueues; drain + // starts the POST; POST stalls at the paused server. + { + type: "create", + client: 0, + path: "X.md", + content: "from-client-0 " + }, + + // Release A's WS. The buffered RemoteCreate for doc-X is + // delivered to A and enqueues behind the in-flight + // LocalCreate. Whichever of (RemoteCreate processed first + // → no-localPath record, then LocalCreate POST returns + // with merging response that collapses) or (LocalCreate + // POST returns first with merging response that creates + // the canonical record, then RemoteCreate finds the doc + // already tracked by id and no-ops) actually plays out + // depends on the fine-grained interleaving the runtime + // produces, but both paths are required to converge to + // the same single-record same-docId state. + { type: "resume-websocket", client: 0 }, + + // Resume the server: A's LocalCreate POST completes. + // Server returns doc-X's existing documentId (MergingUpdate + // with merged content). processCreate runs the collapse + // path. + { type: "resume-server" }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state.assertFileCount(1); + state.assertFileExists("X.md"); + // Server-side merge of the two text creates must + // carry both contributions through to the + // converged file. + state.assertContains( + "X.md", + "from-client-0", + "from-client-1" + ); + // The lazy-paths collapse path must not leave a + // conflict-- stash on either client. + for (const path of state.files.keys()) { + if (path.startsWith("conflict-")) { + throw new Error( + `Unexpected conflict-uuid stash on a converged client: ${path}` + ); + } + } + for (const perClient of state.clientFiles) { + for (const path of perClient.keys()) { + if (path.startsWith("conflict-")) { + throw new Error( + `Unexpected conflict-uuid stash on a per-client view: ${path}` + ); + } + } + } + } + } + ] + }; diff --git a/frontend/deterministic-tests/src/tests/self-merge-pending-rename-aliases-second-create.test.ts b/frontend/deterministic-tests/src/tests/self-merge-pending-rename-aliases-second-create.test.ts new file mode 100644 index 00000000..ac8ed3ed --- /dev/null +++ b/frontend/deterministic-tests/src/tests/self-merge-pending-rename-aliases-second-create.test.ts @@ -0,0 +1,152 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const selfMergePendingRenameAliasesSecondCreateTest: TestDefinition = { + description: + "Single client makes two distinct creates that briefly share a path. " + + "Client 0 POSTs the first create at primary.md while the server is " + + "paused. While that POST is in flight: a second create is queued at " + + "staging.md, primary.md is renamed to moved.md (rewriting the in- " + + "flight create's event.path to moved.md and pushing a rename " + + "LocalUpdate at the queue tail), and staging.md is renamed onto the " + + "now-vacated primary.md slot (rewriting the second create's " + + "event.path to primary.md and pushing another rename LocalUpdate). " + + "Client 0's WS is paused throughout, so its watermark stays at 0. " + + "On resume the first POST commits Doc-X at primary.md (creation_vuid " + + "= N). The drain then processes the second LocalCreate (POST " + + "relativePath=primary.md, last_seen=0); the server's path-based " + + "dedup sees N > 0 and merges the second create into Doc-X " + + "(MergingUpdate). The buggy behaviour: processCreate's resolveCreate " + + "calls upsertRecord with localPath=primary.md, but the existing " + + "record (from the first create) already holds localPath=moved.md, " + + "and upsertRecord's `existing.localPath !== undefined` guard " + + "silently drops the new claim. The file at primary.md is left " + + "orphaned: tracked by no record, never broadcast, never deleted. " + + "After the user's renames the expected user-visible state is two " + + "distinct files at moved.md and primary.md — both clients must " + + "converge to that.", + clients: 2, + steps: [ + // Both clients online so the WS connection is established before + // the test starts pausing things. + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + // Pause client 0's WS so its MinCovered watermark stays at 0 + // through the whole bug sequence. The merge condition the + // server is going to fire is `creation_vuid > last_seen`; with + // a non-zero gap the same-device second create gets merged + // into the same-device first create. + { type: "pause-websocket", client: 0 }, + + // Client 1 commits a doc to push the server's vuid above 0. + // Without this filler, Doc-X's create vuid could be 1 and + // client 0's last_seen.add(1) would advance min to 1, killing + // the watermark gap that triggers the merge. + { + type: "create", + client: 1, + path: "filler.md", + content: "filler-content " + }, + { type: "sync", client: 1 }, + + // Pause the server so client 0's first create POST hangs in + // flight, giving us a deterministic window in which to enqueue + // the second create and the renames. + { type: "pause-server" }, + + // First create — Doc-X. The wire-loop drains it, captures + // requestPath = event.path = "primary.md", reads the bytes, + // sends the POST, and stalls on the response. + { + type: "create", + client: 0, + path: "primary.md", + content: "primary content " + }, + + // Make sure the POST is actually on the wire with + // relativePath="primary.md" before we rewrite event.path. + // Without this delay the rename can win the race, the POST + // goes out with relativePath="moved.md", and the server-side + // path-collision merge never fires. + { type: "sleep", ms: 100 }, + + // Second create at a staging path. The wire-loop is still + // blocked on Doc-X's POST, so this LocalCreate just queues at + // index 1. + { + type: "create", + client: 0, + path: "staging.md", + content: "secondary content " + }, + + // Rename Doc-X's path. enqueue's pending-create branch + // rewrites Doc-X's event.path in place (moved.md) and pushes + // a LocalUpdate(rename, originalPath=moved.md) at the END of + // the queue. Note the ordering: this LocalUpdate is enqueued + // AFTER the staging LocalCreate above. That ordering is + // load-bearing — it is what makes the second create's POST + // drain (and trigger the server-side merge) before Doc-X's + // rename PUT moves the doc away from primary.md on the + // server. + { + type: "rename", + client: 0, + oldPath: "primary.md", + newPath: "moved.md" + }, + + // Rename the staging file onto Doc-X's now-vacated primary.md + // slot. enqueue rewrites the staging LocalCreate's event.path + // to primary.md and pushes a LocalUpdate(rename, + // originalPath=primary.md) at the queue tail. After this the + // disk has: moved.md = Doc-X's bytes, primary.md = Doc-Y's + // bytes. + { + type: "rename", + client: 0, + oldPath: "staging.md", + newPath: "primary.md" + }, + + // Let everything fly: server processes the queued POSTs; + // client 0 catches up on broadcasts. + { type: "resume-server" }, + { type: "resume-websocket", client: 0 }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + // The user did two distinct creates (Doc-X and Doc-Y); + // both contents must survive on both clients. + state.assertFileCount(3); + state.assertFileExists("filler.md"); + state.assertFileExists("moved.md"); + state.assertFileExists("primary.md"); + + // After the renames the user expects: + // - moved.md = the file that was originally created + // at primary.md (Doc-X's content). + // - primary.md = the file that was originally created + // at staging.md (Doc-Y's content). + state.assertContains("moved.md", "primary content"); + state.assertContains("primary.md", "secondary content"); + + // No content cross-contamination: each contribution + // should land in exactly one of the user-visible + // files. Under the bug, the orphan at primary.md + // carries Doc-X's content (because Doc-Y's PUT was + // aliased onto Doc-X's record and read Doc-X's bytes + // from moved.md), so this catches the leak too. + state.assertContentInAtMostOneFile("primary content"); + state.assertContentInAtMostOneFile("secondary content"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/sequential-create-duplicate-content.test.ts b/frontend/deterministic-tests/src/tests/sequential-create-duplicate-content.test.ts new file mode 100644 index 00000000..611e1ae3 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/sequential-create-duplicate-content.test.ts @@ -0,0 +1,43 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const sequentialCreateDuplicateContentTest: TestDefinition = { + description: + "Client 0 creates A.md, syncs, then creates B.md with identical content. Both files must remain as separate documents on both clients.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "A.md", + content: "identical content here" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("A.md", "identical content here"); + } + }, + + { + type: "create", + client: 0, + path: "B.md", + content: "identical content here" + }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(2) + .assertContent("A.md", "identical content here") + .assertContent("B.md", "identical content here"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/server-pause-both-clients-create.test.ts b/frontend/deterministic-tests/src/tests/server-pause-both-clients-create.test.ts new file mode 100644 index 00000000..f99cf92d --- /dev/null +++ b/frontend/deterministic-tests/src/tests/server-pause-both-clients-create.test.ts @@ -0,0 +1,42 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const serverPauseBothClientsCreateTest: TestDefinition = { + description: + "Client 0 creates a file, then the server is paused. Client 1 creates a different file while the server is paused. After the server resumes, both files should exist on both clients.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "create", + client: 0, + path: "alpha.md", + content: "from client 0" + }, + { type: "pause-server" }, + + { + type: "create", + client: 1, + path: "beta.md", + content: "from client 1" + }, + + { type: "resume-server" }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContains("alpha.md", "from client 0").assertContains( + "beta.md", + "from client 1" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/server-pause-both-edit-same-file.test.ts b/frontend/deterministic-tests/src/tests/server-pause-both-edit-same-file.test.ts new file mode 100644 index 00000000..ff8cf194 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/server-pause-both-edit-same-file.test.ts @@ -0,0 +1,68 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const serverPauseBothEditSameFileTest: TestDefinition = { + description: + "Both clients edit different sections of the same file while the server is paused. After resuming and converging, client 0 makes another edit to verify further updates still work correctly.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "shared.md", + content: "line 1: original\nline 2: original\nline 3: original" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "pause-server" }, + + { + type: "update", + client: 0, + path: "shared.md", + content: + "line 1: edited by client 0\nline 2: original\nline 3: original" + }, + { + type: "update", + client: 1, + path: "shared.md", + content: + "line 1: original\nline 2: original\nline 3: edited by client 1" + }, + + { type: "resume-server" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContains( + "shared.md", + "edited by client 0", + "edited by client 1" + ); + } + }, + + { + type: "update", + client: 0, + path: "shared.md", + content: "post-merge edit from client 0" + }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContains( + "shared.md", + "post-merge edit from client 0" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/server-pause-delete-recreate.test.ts b/frontend/deterministic-tests/src/tests/server-pause-delete-recreate.test.ts new file mode 100644 index 00000000..5ac97f0d --- /dev/null +++ b/frontend/deterministic-tests/src/tests/server-pause-delete-recreate.test.ts @@ -0,0 +1,38 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const serverPauseDeleteRecreateTest: TestDefinition = { + description: + "Client 1 deletes a file and syncs. The server is paused, then client 0 creates at the same path. After the server resumes, both clients should have the recreated file.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "original" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "delete", client: 1, path: "A.md" }, + { type: "barrier" }, + + { type: "pause-server" }, + + { + type: "create", + client: 0, + path: "A.md", + content: "recreated during contention" + }, + + { type: "resume-server" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(1) + .assertContent("A.md", "recreated during contention"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/server-pause-rename-edit-resume.test.ts b/frontend/deterministic-tests/src/tests/server-pause-rename-edit-resume.test.ts new file mode 100644 index 00000000..b1739135 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/server-pause-rename-edit-resume.test.ts @@ -0,0 +1,50 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const serverPauseRenameEditResumeTest: TestDefinition = { + description: + "Client 0 creates A.md and syncs. Server is paused. Client 0 " + + "renames A.md to B.md and edits B.md. Server resumes. Both the " + + "rename and edit should propagate to Client 1.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { + type: "create", + client: 0, + path: "A.md", + content: "original content" + }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("A.md", "original content"); + } + }, + + { type: "pause-server" }, + + { type: "rename", client: 0, oldPath: "A.md", newPath: "B.md" }, + { + type: "update", + client: 0, + path: "B.md", + content: "edited after rename during pause" + }, + + { type: "resume-server" }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1) + .assertFileNotExists("A.md") + .assertContent("B.md", "edited after rename during pause"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/server-pause-update-and-create.test.ts b/frontend/deterministic-tests/src/tests/server-pause-update-and-create.test.ts new file mode 100644 index 00000000..2389ccf5 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/server-pause-update-and-create.test.ts @@ -0,0 +1,54 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const serverPauseUpdateAndCreateTest: TestDefinition = { + description: + "Client 0 updates a shared file while client 1 creates a new file, both during a server pause. After the server resumes, both operations should complete and propagate to both clients.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { + type: "create", + client: 0, + path: "shared.md", + content: "initial content" + }, + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent("shared.md", "initial content"); + } + }, + + { type: "pause-server" }, + + { + type: "update", + client: 0, + path: "shared.md", + content: "updated during pause" + }, + { + type: "create", + client: 1, + path: "new-file.md", + content: "created by client 1" + }, + + { type: "resume-server" }, + + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertContent( + "shared.md", + "updated during pause" + ).assertContent("new-file.md", "created by client 1"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/simultaneous-create-delete-same-path.test.ts b/frontend/deterministic-tests/src/tests/simultaneous-create-delete-same-path.test.ts new file mode 100644 index 00000000..7ec116ac --- /dev/null +++ b/frontend/deterministic-tests/src/tests/simultaneous-create-delete-same-path.test.ts @@ -0,0 +1,38 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const simultaneousCreateDeleteSamePathTest: TestDefinition = { + description: + "Client 0 creates A.md and syncs to both clients. Client 0 deletes A.md while " + + "Client 1 (offline) updates A.md with different content. When Client 1 reconnects, " + + "the update and delete must be reconciled. Both clients must converge.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "A.md", content: "original from 0" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 1 }, + + { type: "delete", client: 0, path: "A.md" }, + { type: "sync", client: 0 }, + + { + type: "update", + client: 1, + path: "A.md", + content: "modified by 1 while offline" + }, + + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(0); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/text-pending-create-not-displaced.test.ts b/frontend/deterministic-tests/src/tests/text-pending-create-not-displaced.test.ts new file mode 100644 index 00000000..28243525 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/text-pending-create-not-displaced.test.ts @@ -0,0 +1,36 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const textPendingCreateNotDisplacedTest: TestDefinition = { + description: + "Two clients each create a text file at the same path while offline. " + + "After syncing, the file should contain merged content from both clients.", + clients: 2, + steps: [ + { + type: "create", + client: 0, + path: "data.txt", + content: "text data from client-0" + }, + { + type: "create", + client: 1, + path: "data.txt", + content: "text data from client-1" + }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1) + .assertFileExists("data.txt") + .assertAnyFileContains("client-0", "client-1"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/three-client-rename-create-delete.test.ts b/frontend/deterministic-tests/src/tests/three-client-rename-create-delete.test.ts new file mode 100644 index 00000000..80478adc --- /dev/null +++ b/frontend/deterministic-tests/src/tests/three-client-rename-create-delete.test.ts @@ -0,0 +1,55 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const threeClientRenameCreateDeleteTest: TestDefinition = { + description: + "Client 0 renames X -> Y, Client 1 deletes X, Client 2 creates Y. " + + "All three operations happen while the other clients are offline. " + + "Tests that the system handles the three-way conflict and converges.", + clients: 3, + steps: [ + { + type: "create", + client: 0, + path: "X.md", + content: "original from A" + }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "enable-sync", client: 2 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + { type: "disable-sync", client: 2 }, + + { type: "rename", client: 0, oldPath: "X.md", newPath: "Y.md" }, + + { type: "delete", client: 1, path: "X.md" }, + + { + type: "create", + client: 2, + path: "Y.md", + content: "new from C" + }, + + { type: "enable-sync", client: 0 }, + { type: "sync", client: 0 }, + + { type: "enable-sync", client: 1 }, + { type: "sync", client: 1 }, + + { type: "enable-sync", client: 2 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileNotExists("X.md").assertAnyFileContains( + "new from C" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/update-does-not-survive-remote-delete.test.ts b/frontend/deterministic-tests/src/tests/update-does-not-survive-remote-delete.test.ts new file mode 100644 index 00000000..70a2fc8c --- /dev/null +++ b/frontend/deterministic-tests/src/tests/update-does-not-survive-remote-delete.test.ts @@ -0,0 +1,36 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const updateDoesNotSurvivesRemoteDeleteTest: TestDefinition = { + description: + "Client 0 deletes a file while client 1 edits it offline. Client 0 syncs the delete first, then client 1 reconnects. Deletes always win.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "doc.md", content: "original" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + + { type: "delete", client: 0, path: "doc.md" }, + { + type: "update", + client: 1, + path: "doc.md", + content: "edited by client 1" + }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(0); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/update-during-create-processing.test.ts b/frontend/deterministic-tests/src/tests/update-during-create-processing.test.ts new file mode 100644 index 00000000..ca53244e --- /dev/null +++ b/frontend/deterministic-tests/src/tests/update-during-create-processing.test.ts @@ -0,0 +1,42 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const updateDuringCreateProcessingTest: TestDefinition = { + description: + "Client 0 creates a file while the server is paused, then immediately updates it. After the server resumes, both clients should converge with the updated content.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "pause-server" }, + + { + type: "create", + client: 0, + path: "file.md", + content: "initial" + }, + + { + type: "update", + client: 0, + path: "file.md", + content: "updated during create" + }, + + { type: "resume-server" }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContent( + "file.md", + "updated during create" + ); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/user-parenthesized-file-not-deleted.test.ts b/frontend/deterministic-tests/src/tests/user-parenthesized-file-not-deleted.test.ts new file mode 100644 index 00000000..ef6cd771 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/user-parenthesized-file-not-deleted.test.ts @@ -0,0 +1,47 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const userParenthesizedFileNotDeletedTest: TestDefinition = { + description: + "A user-created file named 'Chapter (1).bin' alongside 'Chapter.bin' should not " + + "be mistakenly removed when another client creates a conflicting file.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + + { + type: "create", + client: 0, + path: "Chapter.bin", + content: "chapter one" + }, + { + type: "create", + client: 0, + path: "Chapter (1).bin", + content: "chapter one notes" + }, + + { type: "sync", client: 0 }, + + { + type: "create", + client: 1, + path: "Chapter.bin", + content: "chapter one notes" + }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (state: AssertableState): void => { + state + .assertFileCount(3) + .assertFileExists("Chapter.bin") + .assertFileExists("Chapter (1).bin") + .assertFileExists("Chapter (2).bin"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/watermark-advances-on-skip.test.ts b/frontend/deterministic-tests/src/tests/watermark-advances-on-skip.test.ts new file mode 100644 index 00000000..063faff4 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/watermark-advances-on-skip.test.ts @@ -0,0 +1,35 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const watermarkAdvancesOnSkipTest: TestDefinition = { + description: + "Both clients create the same file offline. After syncing, both disconnect and reconnect. The reconnect should not replay already-processed updates.", + clients: 2, + steps: [ + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + { type: "create", client: 0, path: "doc.md", content: "from client 0" }, + { type: "create", client: 1, path: "doc.md", content: "from client 1" }, + + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "disable-sync", client: 0 }, + { type: "disable-sync", client: 1 }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertFileExists("doc.md"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/tests/watermark-gap-remote-update-not-recorded.test.ts b/frontend/deterministic-tests/src/tests/watermark-gap-remote-update-not-recorded.test.ts new file mode 100644 index 00000000..ac9ba467 --- /dev/null +++ b/frontend/deterministic-tests/src/tests/watermark-gap-remote-update-not-recorded.test.ts @@ -0,0 +1,37 @@ +import type { AssertableState } from "../utils/assertable-state"; +import type { TestDefinition } from "../test-definition"; + +export const watermarkGapRemoteUpdateNotRecordedTest: TestDefinition = { + description: + "Client 0 sends two rapid updates. Client 1 processes both, then disconnects and reconnects. Both clients should still converge to the latest content after reconnect.", + clients: 2, + steps: [ + { type: "create", client: 0, path: "doc.md", content: "original" }, + { type: "enable-sync", client: 0 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { type: "update", client: 0, path: "doc.md", content: "update 1" }, + { type: "sync", client: 0 }, + { type: "update", client: 0, path: "doc.md", content: "update 2" }, + + { type: "barrier" }, + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContent("doc.md", "update 2"); + } + }, + + { type: "disable-sync", client: 1 }, + { type: "enable-sync", client: 1 }, + { type: "barrier" }, + + { + type: "assert-consistent", + verify: (s: AssertableState): void => { + s.assertFileCount(1).assertContent("doc.md", "update 2"); + } + } + ] +}; diff --git a/frontend/deterministic-tests/src/utils/assert.ts b/frontend/deterministic-tests/src/utils/assert.ts new file mode 100644 index 00000000..4e709060 --- /dev/null +++ b/frontend/deterministic-tests/src/utils/assert.ts @@ -0,0 +1,5 @@ +export function assert(value: boolean, message: string): asserts value { + if (!value) { + throw new Error(message); + } +} diff --git a/frontend/deterministic-tests/src/utils/assertable-state.ts b/frontend/deterministic-tests/src/utils/assertable-state.ts new file mode 100644 index 00000000..7c6f192c --- /dev/null +++ b/frontend/deterministic-tests/src/utils/assertable-state.ts @@ -0,0 +1,150 @@ +import type { ClientState } from "../test-definition"; + +export class AssertableState { + public readonly files: Map; + public readonly clientFiles: Map[]; + + public constructor(state: ClientState) { + this.files = state.files; + this.clientFiles = state.clientFiles; + } + + public assertFileCount(expected: number): this { + if (this.files.size !== expected) { + const keys = Array.from(this.files.keys()).join(", "); + throw new Error( + `Expected ${expected} file(s), got ${this.files.size}: [${keys}]` + ); + } + return this; + } + + public assertFileExists(path: string): this { + if (!this.files.has(path)) { + const keys = Array.from(this.files.keys()).join(", "); + throw new Error(`Expected "${path}" to exist. Files: [${keys}]`); + } + return this; + } + + public assertFileNotExists(path: string): this { + if (this.files.has(path)) { + const keys = Array.from(this.files.keys()).join(", "); + throw new Error( + `Expected "${path}" not to exist. Files: [${keys}]` + ); + } + return this; + } + + public assertContent(path: string, expected: string): this { + this.assertFileExists(path); + const actual = this.files.get(path) ?? ""; + if (actual !== expected) { + throw new Error( + `Expected "${path}" to have content "${expected}", got: "${actual}"` + ); + } + return this; + } + + public assertContains(path: string, ...substrings: string[]): this { + this.assertFileExists(path); + const content = this.files.get(path) ?? ""; + const missing = substrings.filter((s) => !content.includes(s)); + if (missing.length > 0) { + throw new Error( + `Expected "${path}" to contain ${missing.map((s) => `"${s}"`).join(", ")}. Content: "${content}"` + ); + } + return this; + } + + public assertContainsAny(path: string, ...substrings: string[]): this { + this.assertFileExists(path); + const content = this.files.get(path) ?? ""; + const found = substrings.some((s) => content.includes(s)); + if (!found) { + throw new Error( + `Expected "${path}" to contain at least one of ${substrings.map((s) => `"${s}"`).join(", ")}. Content: "${content}"` + ); + } + return this; + } + + public assertAnyFileContains(...substrings: string[]): this { + const allContent = Array.from(this.files.values()).join("\n"); + const missing = substrings.filter((s) => !allContent.includes(s)); + if (missing.length > 0) { + const dump = Array.from(this.files.entries()) + .map(([k, v]) => ` ${k}: "${v}"`) + .join("\n"); + throw new Error( + `Expected some file to contain ${missing.map((s) => `"${s}"`).join(", ")}.\nFiles:\n${dump}` + ); + } + return this; + } + + public assertNoFileContains(...substrings: string[]): this { + const offenders: { path: string; substring: string }[] = []; + for (const [path, content] of this.files) { + for (const s of substrings) { + if (content.includes(s)) { + offenders.push({ path, substring: s }); + } + } + } + if (offenders.length > 0) { + const dump = Array.from(this.files.entries()) + .map(([k, v]) => ` ${k}: "${v}"`) + .join("\n"); + throw new Error( + `Expected no file to contain ${substrings.map((s) => `"${s}"`).join(", ")}, but found ${offenders.map((o) => `"${o.substring}" in "${o.path}"`).join(", ")}.\nFiles:\n${dump}` + ); + } + return this; + } + + public assertSubstringCount( + path: string, + substring: string, + expected: number + ): this { + this.assertFileExists(path); + const content = this.files.get(path) ?? ""; + const actual = content.split(substring).length - 1; + if (actual !== expected) { + throw new Error( + `Expected "${substring}" to appear ${expected} time(s) in "${path}", found ${actual}. Content: "${content}"` + ); + } + return this; + } + + public assertContentInAtMostOneFile(substring: string): this { + const matches = Array.from(this.files.entries()).filter(([, content]) => + content.includes(substring) + ); + if (matches.length > 1) { + const dump = Array.from(this.files.entries()) + .map(([k, v]) => ` ${k}: "${v}"`) + .join("\n"); + throw new Error( + `Expected "${substring}" in at most 1 file, found in ${matches.length}: [${matches.map(([p]) => p).join(", ")}].\nFiles:\n${dump}` + ); + } + return this; + } + + public ifFileExists(path: string, fn: (state: this) => void): this { + if (this.files.has(path)) { + fn(this); + } + return this; + } + + public getContent(path: string): string { + return this.files.get(path) ?? ""; + } +} diff --git a/frontend/deterministic-tests/src/utils/find-free-port.ts b/frontend/deterministic-tests/src/utils/find-free-port.ts new file mode 100644 index 00000000..0734c1a9 --- /dev/null +++ b/frontend/deterministic-tests/src/utils/find-free-port.ts @@ -0,0 +1,29 @@ +import * as net from "node:net"; + +interface PortReservation { + port: number; + release: () => void; +} + +/** + * Find a free port and keep it reserved until the caller explicitly releases it. + */ +export async function findFreePort(): Promise { + return new Promise((resolve, reject) => { + const server = net.createServer(); + server.listen(0, "127.0.0.1", () => { + const addr = server.address(); + if (addr === null || typeof addr === "string") { + server.close(); + reject(new Error("Failed to get port from server")); + return; + } + const { port } = addr; + resolve({ + port, + release: () => server.close() + }); + }); + server.on("error", reject); + }); +} diff --git a/frontend/deterministic-tests/src/utils/sleep.ts b/frontend/deterministic-tests/src/utils/sleep.ts new file mode 100644 index 00000000..ff474799 --- /dev/null +++ b/frontend/deterministic-tests/src/utils/sleep.ts @@ -0,0 +1,3 @@ +export async function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/frontend/deterministic-tests/src/utils/with-timeout.ts b/frontend/deterministic-tests/src/utils/with-timeout.ts new file mode 100644 index 00000000..14ee3f27 --- /dev/null +++ b/frontend/deterministic-tests/src/utils/with-timeout.ts @@ -0,0 +1,15 @@ +export async function withTimeout( + promise: Promise, + timeoutMs: number, + message: string +): Promise { + let timeoutId: ReturnType | undefined = undefined; + const timeoutPromise = new Promise((_resolve, reject) => { + timeoutId = setTimeout(() => { + reject(new Error(message)); + }, timeoutMs); + }); + return Promise.race([promise, timeoutPromise]).finally(() => { + clearTimeout(timeoutId); + }); +} diff --git a/frontend/deterministic-tests/tsconfig.json b/frontend/deterministic-tests/tsconfig.json new file mode 100644 index 00000000..7558871d --- /dev/null +++ b/frontend/deterministic-tests/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "baseUrl": ".", + "strict": true, + "target": "ES2022", + "module": "CommonJS", + "esModuleInterop": true, + "lib": ["DOM", "ES2024"], + "moduleResolution": "node" + }, + "exclude": ["./dist"] +} diff --git a/frontend/deterministic-tests/webpack.config.js b/frontend/deterministic-tests/webpack.config.js new file mode 100644 index 00000000..6aee1547 --- /dev/null +++ b/frontend/deterministic-tests/webpack.config.js @@ -0,0 +1,30 @@ +const path = require("path"); +const webpack = require("webpack"); + +module.exports = { + entry: "./src/cli.ts", + target: "node", + mode: "production", + optimization: { + minimize: false + }, + module: { + rules: [ + { + test: /\.ts$/, + use: "ts-loader" + } + ] + }, + resolve: { + extensions: [".ts", ".js"] + }, + output: { + globalObject: "this", + filename: "cli.js", + path: path.resolve(__dirname, "dist") + }, + plugins: [ + new webpack.BannerPlugin({ banner: "#!/usr/bin/env node", raw: true }) + ] +}; diff --git a/frontend/package.json b/frontend/package.json index df167a5e..0dd9057d 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -5,6 +5,7 @@ "sync-client", "obsidian-plugin", "test-client", + "deterministic-tests", "local-client-cli" ], "prettier": { @@ -17,7 +18,7 @@ "build": "npm run build --workspaces", "dev": "concurrently --kill-others \"npm run dev -w sync-client\" \"npm run dev -w obsidian-plugin\"", "test": "npm run test --workspaces", - "lint": "eslint --fix sync-client obsidian-plugin test-client local-client-cli && prettier --write \"**/*.ts\"", + "lint": "eslint --fix sync-client obsidian-plugin test-client deterministic-tests local-client-cli && prettier --write \"**/*.ts\"", "update": "ncu -u -ws" }, "devDependencies": { From 40fbd42b92cf78581b7cc848cfb1f93423e21e9b Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Sat, 9 May 2026 11:17:21 +0100 Subject: [PATCH 13/17] Remove GH actions (#192) Reviewed-on: https://home.schmelczer.dev/git/git/andras/vault-link/pulls/192 Co-authored-by: Andras Schmelczer Co-committed-by: Andras Schmelczer --- .github/dependabot.yml | 27 ------ .github/workflows/check.yml | 36 -------- .github/workflows/deploy-docs.yml | 58 ------------- .github/workflows/e2e.yml | 72 ---------------- .github/workflows/publish-cli-docker.yml | 67 --------------- .github/workflows/publish-plugin.yml | 59 ------------- .github/workflows/publish-server-docker.yml | 92 --------------------- 7 files changed, 411 deletions(-) delete mode 100644 .github/dependabot.yml delete mode 100644 .github/workflows/check.yml delete mode 100644 .github/workflows/deploy-docs.yml delete mode 100644 .github/workflows/e2e.yml delete mode 100644 .github/workflows/publish-cli-docker.yml delete mode 100644 .github/workflows/publish-plugin.yml delete mode 100644 .github/workflows/publish-server-docker.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index 7d56669b..00000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,27 +0,0 @@ -# To get started with Dependabot version updates, you'll need to specify which -# package ecosystems to update and where the package manifests are located. -# Please see the documentation for all configuration options: -# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file - -version: 2 -updates: - - package-ecosystem: "npm" - directories: ["/frontend", "/docs"] - schedule: - interval: "daily" - - - package-ecosystem: "docker" - directories: ["**"] - schedule: - interval: "daily" - - - package-ecosystem: "cargo" - directories: ["**"] - schedule: - interval: "daily" - - # Disable this for security reasons - # - package-ecosystem: "github-actions" - # directories: ["**"] - # schedule: - # interval: "daily" diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml deleted file mode 100644 index fc1b1c99..00000000 --- a/.github/workflows/check.yml +++ /dev/null @@ -1,36 +0,0 @@ -name: Check - -on: - push: - branches: ["main"] - pull_request: - branches: ["main"] - workflow_dispatch: - -env: - CARGO_TERM_COLOR: always - RUSTFLAGS: "-Dwarnings" - -jobs: - build: - runs-on: self-hosted - - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Setup Node.js environment - uses: actions/setup-node@v4.2.0 - with: - node-version: "25.x" - check-latest: true - - - name: Setup Rust toolchain - uses: dtolnay/rust-toolchain@stable - with: - toolchain: "1.92.0" - components: clippy, rustfmt - - - name: Lint & test - run: scripts/check.sh diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml deleted file mode 100644 index bb25e463..00000000 --- a/.github/workflows/deploy-docs.yml +++ /dev/null @@ -1,58 +0,0 @@ -name: Deploy Documentation - -on: - push: - branches: - - main - paths: - - "docs/**" - - ".github/workflows/deploy-docs.yml" - workflow_dispatch: - -permissions: - contents: read - pages: write - id-token: write - -concurrency: - group: pages - cancel-in-progress: false - -jobs: - build: - runs-on: self-hosted - - steps: - - name: Checkout - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Setup Node.js environment - uses: actions/setup-node@v4.2.0 - with: - node-version: "25.x" - check-latest: true - - - name: Setup Pages - uses: actions/configure-pages@v4 - - - name: Build docs - run: scripts/build-docs.sh - - - name: Upload artifact - uses: actions/upload-pages-artifact@v3 - with: - path: docs/.vitepress/dist - - deploy: - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - needs: build - runs-on: self-hosted - name: Deploy - steps: - - name: Deploy to GitHub Pages - id: deployment - uses: actions/deploy-pages@v4 diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml deleted file mode 100644 index 98dbfc1f..00000000 --- a/.github/workflows/e2e.yml +++ /dev/null @@ -1,72 +0,0 @@ -name: E2E tests - -on: - push: - branches: ["main"] - pull_request: - branches: ["main"] - schedule: - - cron: "0 * * * *" - workflow_dispatch: - -concurrency: - group: e2e-tests - cancel-in-progress: false - -env: - RUSTFLAGS: "-Dwarnings" - -jobs: - build: - runs-on: self-hosted - - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Setup Node.js environment - uses: actions/setup-node@v4.2.0 - with: - node-version: "25.x" - check-latest: true - - - name: Setup Rust toolchain - uses: dtolnay/rust-toolchain@stable - with: - toolchain: "1.92.0" - components: clippy, rustfmt - - - name: Setup rust - run: | - which sqlx || cargo install sqlx-cli - cd sync-server - sqlx database create --database-url sqlite://db.sqlite3 - sqlx migrate run --source src/app_state/database/migrations --database-url sqlite://db.sqlite3 - - - name: E2E tests - run: | - cd sync-server - cargo run config-e2e.yml --color never & - SERVER_PID=$! - cd .. - - scripts/e2e.sh 8 - EXIT_CODE=$? - - kill $SERVER_PID 2>/dev/null || true - wait $SERVER_PID 2>/dev/null || true - - exit $EXIT_CODE - - - name: Upload e2e logs - if: always() - uses: actions/upload-artifact@v4 - with: - name: e2e-logs - path: logs/ - retention-days: 30 - - - name: Cleanup - if: always() - run: scripts/clean-up.sh diff --git a/.github/workflows/publish-cli-docker.yml b/.github/workflows/publish-cli-docker.yml deleted file mode 100644 index 10a7e8ba..00000000 --- a/.github/workflows/publish-cli-docker.yml +++ /dev/null @@ -1,67 +0,0 @@ -name: Publish CLI - -on: - push: - branches: ["main"] - tags: ["*"] - pull_request: - branches: ["main"] - -env: - REGISTRY: ghcr.io - IMAGE_NAME: ${{ github.repository }}-cli - -jobs: - publish-docker: - runs-on: self-hosted - - permissions: - contents: read - packages: write - id-token: write - - steps: - - name: Checkout repository - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Install cosign - uses: sigstore/cosign-installer@59acb6260d9c0ba8f4a2f9d9b48431a222b68e20 #v3.5.0 - with: - cosign-release: "v2.2.4" - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0 - - - name: Log into registry ${{ env.REGISTRY }} - uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0 - with: - registry: ${{ env.REGISTRY }} - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Extract Docker metadata - id: meta - uses: docker/metadata-action@96383f45573cb7f253c731d3b3ab81c87ef81934 # v5.0.0 - with: - images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - - - name: Build and push Docker image - id: build-and-push - uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # v5.0.0 - with: - context: frontend - file: frontend/local-client-cli/Dockerfile - platforms: linux/amd64 - push: true - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha - cache-to: type=gha,mode=max - - - name: Sign the published Docker image - env: - TAGS: ${{ steps.meta.outputs.tags }} - DIGEST: ${{ steps.build-and-push.outputs.digest }} - run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST} diff --git a/.github/workflows/publish-plugin.yml b/.github/workflows/publish-plugin.yml deleted file mode 100644 index 452bc601..00000000 --- a/.github/workflows/publish-plugin.yml +++ /dev/null @@ -1,59 +0,0 @@ -name: Publish Obsidian plugin - -on: - push: - tags: ["*"] - -env: - CARGO_TERM_COLOR: always - -jobs: - publish-plugin: - runs-on: self-hosted - - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Setup Node.js environment - uses: actions/setup-node@v4.2.0 - with: - node-version: "25.x" - check-latest: true - - - name: Build plugin - run: | - cd frontend - npm ci - npm run build - - - name: Setup Rust toolchain - uses: dtolnay/rust-toolchain@stable - with: - toolchain: "1.92.0" - components: clippy, rustfmt - - - name: Install cross-compilation tools - run: | - apt update - apt install -y gcc-aarch64-linux-gnu musl-tools gcc-mingw-w64-x86-64 - - - name: Build Linux and Windows binaries - run: ./scripts/build-sync-server-binaries.sh - - - name: Create release - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - tag="${GITHUB_REF#refs/tags/}" - - mkdir -p release - cp frontend/obsidian-plugin/dist/* release/ - cp sync-server/artifacts/sync-server-* release/ - cd release - - gh release create "$tag" \ - --title="$tag" \ - --draft \ - * diff --git a/.github/workflows/publish-server-docker.yml b/.github/workflows/publish-server-docker.yml deleted file mode 100644 index 4a97a9e6..00000000 --- a/.github/workflows/publish-server-docker.yml +++ /dev/null @@ -1,92 +0,0 @@ -name: Publish server Docker image - -on: - push: - branches: ["main"] - tags: ["*"] - pull_request: - branches: ["main"] - -env: - # Use docker.io for Docker Hub if empty - REGISTRY: ghcr.io - # github.repository as / - IMAGE_NAME: ${{ github.repository }} - -jobs: - publish-docker: - runs-on: self-hosted - - permissions: - contents: read - packages: write - # This is used to complete the identity challenge - # with sigstore/fulcio. - id-token: write - - steps: - - name: Checkout repository - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - # Install the cosign tool - # https://github.com/sigstore/cosign-installer - - name: Install cosign - if: github.ref_type == 'tag' - uses: sigstore/cosign-installer@59acb6260d9c0ba8f4a2f9d9b48431a222b68e20 #v3.5.0 - with: - cosign-release: "v2.2.4" - - # Set up BuildKit Docker container builder to be able to build - # multi-platform images and export cache - # https://github.com/docker/setup-buildx-action - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0 - - # Login against a Docker registry - # https://github.com/docker/login-action - - name: Log into registry ${{ env.REGISTRY }} - if: github.ref_type == 'tag' - uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0 - with: - registry: ${{ env.REGISTRY }} - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - # Extract metadata (tags, labels) for Docker - # https://github.com/docker/metadata-action - - name: Extract Docker metadata - id: meta - uses: docker/metadata-action@96383f45573cb7f253c731d3b3ab81c87ef81934 # v5.0.0 - with: - images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - - # Build and push Docker image with Buildx - # https://github.com/docker/build-push-action - - name: Build and push Docker image - id: build-and-push - uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # v5.0.0 - with: - context: sync-server - platforms: linux/amd64,linux/arm64 - push: ${{ github.ref_type == 'tag' }} - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha - cache-to: type=gha,mode=max - - # Sign the resulting Docker image digest. - # This will only write to the public Rekor transparency log when the Docker - # repository is public to avoid leaking data. If you would like to publish - # transparency data even for private images, pass --force to cosign below. - # https://github.com/sigstore/cosign - - name: Sign the published Docker image - if: ${{ github.ref_type == 'tag' }} - env: - # https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions#using-an-intermediate-environment-variable - TAGS: ${{ steps.meta.outputs.tags }} - DIGEST: ${{ steps.build-and-push.outputs.digest }} - # This step uses the identity token to provision an ephemeral certificate - # against the sigstore community Fulcio instance. - run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST} From 682dc7449722ebee2ce08365dc0ab6dfaad28f33 Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Sat, 9 May 2026 13:41:51 +0100 Subject: [PATCH 14/17] Update local-client-cli and obsidian-plugin Pulls the local-client-cli and obsidian-plugin changes from asch/fix-everything onto a fresh branch off main. --- frontend/local-client-cli/Dockerfile | 4 +- frontend/local-client-cli/README.md | 50 ++-- frontend/local-client-cli/package.json | 16 +- frontend/local-client-cli/src/args.test.ts | 226 +++++++++++++++++- frontend/local-client-cli/src/args.ts | 183 ++++++++++---- frontend/local-client-cli/src/cli.ts | 174 ++++++++------ frontend/local-client-cli/src/file-watcher.ts | 72 ++---- frontend/local-client-cli/src/healthcheck.ts | 1 + .../src/logger-formatter.test.ts | 50 ++++ .../local-client-cli/src/logger-formatter.ts | 19 +- .../local-client-cli/src/node-filesystem.ts | 90 +++---- .../local-client-cli/src/path-utils.test.ts | 60 +++++ frontend/local-client-cli/src/path-utils.ts | 15 ++ frontend/local-client-cli/tsconfig.json | 4 +- frontend/local-client-cli/webpack.config.js | 54 ++--- frontend/obsidian-plugin/README.md | 26 +- frontend/obsidian-plugin/package.json | 22 +- .../obsidian-plugin/src/vault-link-plugin.ts | 32 ++- .../src/views/cursors/file-explorer.ts | 6 +- .../views/cursors/remote-cursors-plugin.ts | 5 +- .../src/views/settings/settings-tab.ts | 55 +---- .../status-description/status-description.ts | 2 +- frontend/obsidian-plugin/tsconfig.json | 9 +- frontend/obsidian-plugin/webpack.config.js | 2 +- 24 files changed, 741 insertions(+), 436 deletions(-) create mode 100644 frontend/local-client-cli/src/logger-formatter.test.ts create mode 100644 frontend/local-client-cli/src/path-utils.test.ts create mode 100644 frontend/local-client-cli/src/path-utils.ts diff --git a/frontend/local-client-cli/Dockerfile b/frontend/local-client-cli/Dockerfile index 695ab587..0dfa7055 100644 --- a/frontend/local-client-cli/Dockerfile +++ b/frontend/local-client-cli/Dockerfile @@ -1,4 +1,4 @@ -FROM node:22-slim AS builder +FROM node:25-slim AS builder WORKDIR /build @@ -7,7 +7,7 @@ COPY . . RUN npm ci RUN npm run build -FROM node:22-alpine +FROM node:25-alpine LABEL org.opencontainers.image.title="VaultLink Local CLI" LABEL org.opencontainers.image.description="Standalone CLI for VaultLink sync client" diff --git a/frontend/local-client-cli/README.md b/frontend/local-client-cli/README.md index 0585bacc..e91322f9 100644 --- a/frontend/local-client-cli/README.md +++ b/frontend/local-client-cli/README.md @@ -47,24 +47,25 @@ vaultlink \ ### Required -| Option | Description | -|--------|-------------| -| `-l, --local-path ` | Local directory to sync | -| `-r, --remote-uri ` | Remote server WebSocket URI (ws:// or wss://) | -| `-t, --token ` | Authentication token | -| `-v, --vault-name ` | Vault name on server | +| Option | Description | +| ------------------------- | --------------------------------------------- | +| `-l, --local-path ` | Local directory to sync | +| `-r, --remote-uri ` | Remote server WebSocket URI (ws:// or wss://) | +| `-t, --token ` | Authentication token | +| `-v, --vault-name ` | Vault name on server | ### Optional -| Option | Default | Description | -|--------|---------|-------------| -| `--sync-concurrency ` | `1` | Concurrent sync operations | -| `--max-file-size-mb ` | `10` | Maximum file size in MB | -| `--ignore-pattern ` | - | Glob pattern to ignore (repeatable) | -| `--websocket-retry-interval-ms ` | `3500` | WebSocket reconnection interval | -| `--log-level ` | `INFO` | Log level: DEBUG, INFO, WARNING, ERROR | -| `-h, --help` | - | Show help | -| `-V, --version` | - | Show version | +| Option | Default | Description | +| ------------------------------------ | ------- | ----------------------------------------------- | +| `--max-file-size-mb ` | `10` | Maximum file size in MB | +| `--ignore-pattern ` | - | Glob pattern to ignore (repeatable) | +| `--websocket-retry-interval-ms ` | `3500` | WebSocket reconnection interval | +| `--log-level ` | `INFO` | Log level: DEBUG, INFO, WARNING, ERROR | +| `--line-endings ` | `auto` | Line ending style: auto, lf, crlf | +| `-q, --quiet` | - | Suppress startup banner for non-interactive use | +| `-h, --help` | - | Show help | +| `-V, --version` | - | Show version | ### Auto-Ignored Patterns @@ -74,22 +75,32 @@ vaultlink \ ### Examples Basic usage: + ```bash vaultlink -l ./vault -r wss://sync.example.com -t token123 -v default ``` With ignore patterns: + ```bash vaultlink -l ./vault -r wss://sync.example.com -t token123 -v default \ - --ignore-pattern "*.tmp" \ + --ignore-pattern "**/*.tmp" \ --ignore-pattern ".DS_Store" \ --ignore-pattern "node_modules/**" ``` -With debug logging: +With debug logging and quiet startup: + ```bash vaultlink -l ./vault -r wss://sync.example.com -t token123 -v default \ - --log-level DEBUG + --log-level DEBUG --quiet +``` + +Force LF line endings (useful for cross-platform vaults): + +```bash +vaultlink -l ./vault -r wss://sync.example.com -t token123 -v default \ + --line-endings lf ``` ## Docker Deployment @@ -176,6 +187,7 @@ services: ## Development Build: + ```bash npm run build # or from the parent folder, run @@ -183,11 +195,13 @@ docker build -f local-client-cli/Dockerfile . ``` Test: + ```bash npm test ``` Docker build: + ```bash cd frontend docker build -f local-client-cli/Dockerfile -t vault-link-cli:test . diff --git a/frontend/local-client-cli/package.json b/frontend/local-client-cli/package.json index cade4990..a862b297 100644 --- a/frontend/local-client-cli/package.json +++ b/frontend/local-client-cli/package.json @@ -11,18 +11,16 @@ "build": "webpack --mode production", "test": "tsx --test 'src/**/*.test.ts'" }, - "dependencies": { - "commander": "^14.0.2", - "watcher": "^2.3.1" - }, "devDependencies": { - "@types/node": "^24.8.1", + "commander": "^14.0.2", + "watcher": "^2.3.1", + "@types/node": "^25.0.2", "sync-client": "file:../sync-client", - "ts-loader": "^9.5.2", + "ts-loader": "^9.5.4", "tslib": "2.8.1", - "tsx": "^4.20.6", - "typescript": "5.8.3", - "webpack": "^5.99.9", + "tsx": "^4.21.0", + "typescript": "5.9.3", + "webpack": "^5.103.0", "webpack-cli": "^6.0.1" } } diff --git a/frontend/local-client-cli/src/args.test.ts b/frontend/local-client-cli/src/args.test.ts index eb195538..c075d193 100644 --- a/frontend/local-client-cli/src/args.test.ts +++ b/frontend/local-client-cli/src/args.test.ts @@ -55,13 +55,10 @@ test("parseArgs - parse with optional arguments", () => { "mytoken", "-v", "default", - "--sync-concurrency", - "5", "--max-file-size-mb", "20" ]); - assert.equal(args.syncConcurrency, 5); assert.equal(args.maxFileSizeMB, 20); }); @@ -228,3 +225,226 @@ test("parseArgs - throws on invalid log level", () => { ]); }, /Invalid log level/); }); + +test("parseArgs - reads required options from environment variables", () => { + process.env.VAULTLINK_LOCAL_PATH = "/env/path"; + process.env.VAULTLINK_REMOTE_URI = "https://env.example.com"; + process.env.VAULTLINK_TOKEN = "env-token"; + process.env.VAULTLINK_VAULT_NAME = "env-vault"; + + try { + const args = parseArgs(["node", "cli.js"]); + assert.equal(args.localPath, "/env/path"); + assert.equal(args.remoteUri, "https://env.example.com"); + assert.equal(args.token, "env-token"); + assert.equal(args.vaultName, "env-vault"); + } finally { + delete process.env.VAULTLINK_LOCAL_PATH; + delete process.env.VAULTLINK_REMOTE_URI; + delete process.env.VAULTLINK_TOKEN; + delete process.env.VAULTLINK_VAULT_NAME; + } +}); + +test("parseArgs - CLI arguments take precedence over environment variables", () => { + process.env.VAULTLINK_TOKEN = "env-token"; + + try { + const args = parseArgs([ + "node", + "cli.js", + "-l", + "/path/to/vault", + "-r", + "https://sync.example.com", + "-t", + "cli-token", + "-v", + "default" + ]); + assert.equal(args.token, "cli-token"); + } finally { + delete process.env.VAULTLINK_TOKEN; + } +}); + +test("parseArgs - reads log level from environment variable", () => { + process.env.VAULTLINK_LOG_LEVEL = "DEBUG"; + + try { + const args = parseArgs([ + "node", + "cli.js", + "-l", + "/path/to/vault", + "-r", + "https://sync.example.com", + "-t", + "mytoken", + "-v", + "default" + ]); + assert.equal(args.logLevel, LogLevel.DEBUG); + } finally { + delete process.env.VAULTLINK_LOG_LEVEL; + } +}); + +test("parseArgs - quiet defaults to false", () => { + const args = parseArgs([ + "node", + "cli.js", + "-l", + "/path/to/vault", + "-r", + "https://sync.example.com", + "-t", + "mytoken", + "-v", + "default" + ]); + + assert.equal(args.quiet, false); +}); + +test("parseArgs - parse --quiet flag", () => { + const args = parseArgs([ + "node", + "cli.js", + "-l", + "/path/to/vault", + "-r", + "https://sync.example.com", + "-t", + "mytoken", + "-v", + "default", + "--quiet" + ]); + + assert.equal(args.quiet, true); +}); + +test("parseArgs - parse -q short flag", () => { + const args = parseArgs([ + "node", + "cli.js", + "-l", + "/path/to/vault", + "-r", + "https://sync.example.com", + "-t", + "mytoken", + "-v", + "default", + "-q" + ]); + + assert.equal(args.quiet, true); +}); + +test("parseArgs - line-endings defaults to auto", () => { + const args = parseArgs([ + "node", + "cli.js", + "-l", + "/path/to/vault", + "-r", + "https://sync.example.com", + "-t", + "mytoken", + "-v", + "default" + ]); + + assert.equal(args.lineEndings, "auto"); +}); + +test("parseArgs - parse --line-endings lf", () => { + const args = parseArgs([ + "node", + "cli.js", + "-l", + "/path/to/vault", + "-r", + "https://sync.example.com", + "-t", + "mytoken", + "-v", + "default", + "--line-endings", + "lf" + ]); + + assert.equal(args.lineEndings, "lf"); +}); + +test("parseArgs - parse --line-endings crlf", () => { + const args = parseArgs([ + "node", + "cli.js", + "-l", + "/path/to/vault", + "-r", + "https://sync.example.com", + "-t", + "mytoken", + "-v", + "default", + "--line-endings", + "crlf" + ]); + + assert.equal(args.lineEndings, "crlf"); +}); + +test("parseArgs - throws on invalid remote URI protocol", () => { + assert.throws(() => { + parseArgs([ + "node", + "cli.js", + "-l", + "/path/to/vault", + "-r", + "ftp://sync.example.com", + "-t", + "mytoken", + "-v", + "default" + ]); + }, /Invalid remote URI/); +}); + +test("parseArgs - accepts http:// remote URI", () => { + const args = parseArgs([ + "node", + "cli.js", + "-l", + "/path/to/vault", + "-r", + "http://localhost:3000", + "-t", + "mytoken", + "-v", + "default" + ]); + + assert.equal(args.remoteUri, "http://localhost:3000"); +}); + +test("parseArgs - accepts wss:// remote URI", () => { + const args = parseArgs([ + "node", + "cli.js", + "-l", + "/path/to/vault", + "-r", + "wss://sync.example.com", + "-t", + "mytoken", + "-v", + "default" + ]); + + assert.equal(args.remoteUri, "wss://sync.example.com"); +}); diff --git a/frontend/local-client-cli/src/args.ts b/frontend/local-client-cli/src/args.ts index 615b9d71..442c4817 100644 --- a/frontend/local-client-cli/src/args.ts +++ b/frontend/local-client-cli/src/args.ts @@ -1,21 +1,26 @@ -import { Command } from "commander"; +import { Command, Option } from "commander"; import packageJson from "../package.json"; import { LogLevel } from "sync-client"; -export interface CliArgs { +type LineEndingMode = "auto" | "lf" | "crlf"; + +interface CliArgs { remoteUri: string; token: string; vaultName: string; localPath: string; - syncConcurrency?: number; maxFileSizeMB?: number; ignorePatterns?: string[]; webSocketRetryIntervalMs?: number; logLevel: LogLevel; health?: string; enableTelemetry?: boolean; + quiet: boolean; + lineEndings: LineEndingMode; } +const VALID_PROTOCOLS = ["http://", "https://", "ws://", "wss://"]; + export function parseArgs(argv: string[]): CliArgs { const program = new Command(); @@ -25,41 +30,83 @@ export function parseArgs(argv: string[]): CliArgs { "VaultLink Local CLI - Sync your vault to the local filesystem" ) .version(packageJson.version) - .option("-l, --local-path ", "Local directory path to sync") - .option("-r, --remote-uri ", "Remote server URI") - .option("-t, --token ", "Authentication token") - .option("-v, --vault-name ", "Vault name") - .option( - "--sync-concurrency ", - "[OPTIONAL] Number of concurrent sync operations", - parseInt + .addOption( + new Option( + "-l, --local-path ", + "Local directory path to sync" + ).env("VAULTLINK_LOCAL_PATH") ) - .option( - "--max-file-size-mb ", - "[OPTIONAL] Maximum file size in MB", - parseInt + .addOption( + new Option("-r, --remote-uri ", "Remote server URI").env( + "VAULTLINK_REMOTE_URI" + ) ) - .option( - "--ignore-pattern ", - "[OPTIONAL] Patterns to ignore (can be specified multiple times)" + .addOption( + new Option("-t, --token ", "Authentication token").env( + "VAULTLINK_TOKEN" + ) ) - .option( - "--websocket-retry-interval-ms ", - "[OPTIONAL] WebSocket retry interval in milliseconds", - parseInt + .addOption( + new Option("-v, --vault-name ", "Vault name").env( + "VAULTLINK_VAULT_NAME" + ) ) - .option( - "--log-level ", - "[OPTIONAL] Log level (DEBUG, INFO, WARNING, ERROR)", - "INFO" + .addOption( + new Option( + "--max-file-size-mb ", + "[OPTIONAL] Maximum file size in MB" + ) + .argParser(parseInt) + .env("VAULTLINK_MAX_FILE_SIZE_MB") ) - .option( - "--health ", - "[OPTIONAL] Path to health status file for Docker healthcheck" + .addOption( + new Option( + "--ignore-pattern ", + "[OPTIONAL] Patterns to ignore (can be specified multiple times)" + ).env("VAULTLINK_IGNORE_PATTERNS") ) - .option( - "--enable-telemetry", - "[OPTIONAL] Enable telemetry (disabled by default)" + .addOption( + new Option( + "--websocket-retry-interval-ms ", + "[OPTIONAL] WebSocket retry interval in milliseconds" + ) + .argParser(parseInt) + .env("VAULTLINK_WEBSOCKET_RETRY_INTERVAL_MS") + ) + .addOption( + new Option( + "--log-level ", + "[OPTIONAL] Log level (DEBUG, INFO, WARNING, ERROR)" + ) + .default("INFO") + .env("VAULTLINK_LOG_LEVEL") + ) + .addOption( + new Option( + "--health ", + "[OPTIONAL] Path to health status file for Docker healthcheck" + ).env("VAULTLINK_HEALTH") + ) + .addOption( + new Option( + "--enable-telemetry", + "[OPTIONAL] Enable telemetry (disabled by default)" + ).env("VAULTLINK_ENABLE_TELEMETRY") + ) + .addOption( + new Option( + "-q, --quiet", + "[OPTIONAL] Suppress startup banner for non-interactive use" + ).env("VAULTLINK_QUIET") + ) + .addOption( + new Option( + "--line-endings ", + "[OPTIONAL] Line ending style: auto (platform default), lf, crlf" + ) + .default("auto") + .choices(["auto", "lf", "crlf"]) + .env("VAULTLINK_LINE_ENDINGS") ) .addHelpText( "after", @@ -67,9 +114,13 @@ export function parseArgs(argv: string[]): CliArgs { Examples: $ vaultlink -l ./my-vault -r https://sync.example.com -t mytoken -v default $ vaultlink -l ./my-vault -r https://sync.example.com -t mytoken -v default \\ - --ignore-pattern ".git/**" --ignore-pattern "*.tmp" + --ignore-pattern ".git/**" --ignore-pattern "**/*.tmp" $ vaultlink -l ./my-vault -r https://sync.example.com -t mytoken -v default \\ - --log-level DEBUG + --log-level DEBUG --quiet + +Environment variables: + All options can be configured via VAULTLINK_ prefixed environment variables. + CLI arguments take precedence over environment variables. ` ); @@ -81,7 +132,6 @@ Examples: const remoteUri = opts.remoteUri as string | undefined; const token = opts.token as string | undefined; const vaultName = opts.vaultName as string | undefined; - const syncConcurrency = opts.syncConcurrency as number | undefined; const maxFileSizeMb = opts.maxFileSizeMb as number | undefined; const ignorePattern = opts.ignorePattern as string[] | undefined; const websocketRetryIntervalMs = opts.websocketRetryIntervalMs as @@ -90,22 +140,39 @@ Examples: const logLevelStr = (opts.logLevel as string | undefined) ?? "INFO"; const health = opts.health as string | undefined; const enableTelemetry = opts.enableTelemetry as boolean | undefined; + const quiet = (opts.quiet as boolean | undefined) ?? false; + const lineEndingsStr = (opts.lineEndings as string | undefined) ?? "auto"; /* eslint-enable @typescript-eslint/no-unsafe-type-assertion */ - if (localPath === undefined) { + const requireOption = (value: T | undefined, name: string): T => { + if (value === undefined) { + const option = program.options.find( + (o) => o.attributeName() === name + ); + const envHint = + option?.envVar !== undefined + ? ` (or set ${option.envVar})` + : ""; + throw new Error( + `required option '${option?.flags ?? name}' not specified${envHint}` + ); + } + return value; + }; + + const requiredLocalPath = requireOption(localPath, "localPath"); + const requiredRemoteUri = requireOption(remoteUri, "remoteUri"); + const requiredToken = requireOption(token, "token"); + const requiredVaultName = requireOption(vaultName, "vaultName"); + + // Validate remote URI protocol + if ( + !VALID_PROTOCOLS.some((prefix) => requiredRemoteUri.startsWith(prefix)) + ) { throw new Error( - "required option '-l, --local-path ' not specified" + `Invalid remote URI '${requiredRemoteUri}'. Must start with ${VALID_PROTOCOLS.join(", ")}` ); } - if (remoteUri === undefined) { - throw new Error("required option '--remote-uri ' not specified"); - } - if (token === undefined) { - throw new Error("required option '--token ' not specified"); - } - if (vaultName === undefined) { - throw new Error("required option '--vault-name ' not specified"); - } // Validate and parse log level const logLevelUpper = logLevelStr.toUpperCase(); @@ -120,17 +187,29 @@ Examples: } const logLevel = logLevelUpper; + const validLineEndings: readonly string[] = ["auto", "lf", "crlf"]; + const isLineEndingMode = (value: string): value is LineEndingMode => { + return validLineEndings.includes(value); + }; + if (!isLineEndingMode(lineEndingsStr)) { + throw new Error( + `Invalid line endings mode '${lineEndingsStr}'. Valid values are: ${validLineEndings.join(", ")}` + ); + } + const lineEndings = lineEndingsStr; + return { - localPath, - remoteUri, - token, - vaultName, - syncConcurrency, + localPath: requiredLocalPath, + remoteUri: requiredRemoteUri, + token: requiredToken, + vaultName: requiredVaultName, maxFileSizeMB: maxFileSizeMb, ignorePatterns: ignorePattern, webSocketRetryIntervalMs: websocketRetryIntervalMs, logLevel, health, - enableTelemetry + enableTelemetry, + quiet, + lineEndings }; } diff --git a/frontend/local-client-cli/src/cli.ts b/frontend/local-client-cli/src/cli.ts index 48fd8954..e06fda47 100644 --- a/frontend/local-client-cli/src/cli.ts +++ b/frontend/local-client-cli/src/cli.ts @@ -5,24 +5,27 @@ import type { NetworkConnectionStatus } from "sync-client"; import { SyncClient, DEFAULT_SETTINGS, + Logger, LogLevel, + type LogLine, type SyncSettings, type StoredDatabase } from "sync-client"; import { parseArgs } from "./args"; import { NodeFileSystemOperations } from "./node-filesystem"; import { FileWatcher } from "./file-watcher"; -import { formatLogLine, colorize, styleText } from "./logger-formatter"; +import { formatLogLine } from "./logger-formatter"; import packageJson from "../package.json"; function writeHealthStatus( + logger: Logger, filePath: string, connectionStatus: NetworkConnectionStatus ): void { try { fsSync.writeFileSync(filePath, JSON.stringify(connectionStatus)); } catch (error) { - console.error( + logger.error( `Failed to write health status to ${filePath}: ${error instanceof Error ? error.message : String(error)}` ); } @@ -35,12 +38,37 @@ const LOG_LEVEL_ORDER = { [LogLevel.ERROR]: 3 }; +function createLogHandler(minLevel: LogLevel): (logLine: LogLine) => void { + return (logLine: LogLine): void => { + if (LOG_LEVEL_ORDER[logLine.level] >= LOG_LEVEL_ORDER[minLevel]) { + // eslint-disable-next-line no-console + console.log(formatLogLine(logLine)); + } + }; +} + const HEALTH_CHECK_INTERVAL_MS = 30 * 1000; +const PROGRESS_LOG_INTERVAL_MS = 2000; + +function resolveLineEndings(mode: "auto" | "lf" | "crlf"): string { + switch (mode) { + case "lf": + return "\n"; + case "crlf": + return "\r\n"; + case "auto": + return process.platform === "win32" ? "\r\n" : "\n"; + } +} async function main(): Promise { const args = parseArgs(process.argv); const absolutePath = path.resolve(args.localPath); + const logger = new Logger(); + const logHandler = createLogHandler(args.logLevel); + logger.onLogEmitted.add(logHandler); + if (!fsSync.existsSync(absolutePath)) { fsSync.mkdirSync(absolutePath, { recursive: true }); } @@ -48,36 +76,25 @@ async function main(): Promise { try { const stats = await fs.stat(absolutePath); if (!stats.isDirectory()) { - console.error( - colorize(`Error: ${absolutePath} is not a directory`, "red") - ); + logger.error(`${absolutePath} is not a directory`); process.exit(1); } } catch (error) { - console.error( - colorize( - `Error: Cannot access directory ${absolutePath}: ${error instanceof Error ? error.message : String(error)}`, - "red" - ) + logger.error( + `Cannot access directory ${absolutePath}: ${error instanceof Error ? error.message : String(error)}` ); process.exit(1); } - console.log( - styleText("VaultLink Local CLI", "bold", "cyan") + - colorize(` v${packageJson.version}`, "dim") - ); - console.log(colorize("=".repeat(50), "dim")); - console.log( - `${colorize("Local path:", "dim")} ${colorize(absolutePath, "green")}` - ); - console.log( - `${colorize("Remote URI:", "dim")} ${colorize(args.remoteUri, "cyan")}` - ); - console.log( - `${colorize("Vault name:", "dim")} ${colorize(args.vaultName, "green")}` - ); - console.log(""); + if (!args.quiet) { + logger.info(`VaultLink Local CLI v${packageJson.version}`); + logger.info(`Local path: ${absolutePath}`); + logger.info(`Remote URI: ${args.remoteUri}`); + logger.info(`Vault name: ${args.vaultName}`); + if (args.lineEndings !== "auto") { + logger.info(`Line endings: ${args.lineEndings.toUpperCase()}`); + } + } const dataDir = path.join(absolutePath, ".vaultlink"); const dataFile = path.join(dataDir, "sync-data.json"); @@ -97,8 +114,6 @@ async function main(): Promise { remoteUri: args.remoteUri, token: args.token, vaultName: args.vaultName, - syncConcurrency: - args.syncConcurrency ?? DEFAULT_SETTINGS.syncConcurrency, maxFileSizeMB: args.maxFileSizeMB ?? DEFAULT_SETTINGS.maxFileSizeMB, ignorePatterns, webSocketRetryIntervalMs: @@ -119,12 +134,7 @@ async function main(): Promise { // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion database = JSON.parse(content) as Partial; } catch { - console.error( - colorize( - `Cannot read data file at ${dataFile}`, - "yellow" - ) - ); + logger.warn(`Cannot read data file at ${dataFile}`); } return { @@ -133,23 +143,27 @@ async function main(): Promise { }; }, save: async ({ database: persistedDatabase }) => { - // settings can't be updated when running with this CLI await fs.writeFile( dataFile, JSON.stringify(persistedDatabase, null, 2) ); } }, - nativeLineEndings: process.platform === "win32" ? "\r\n" : "\n" + nativeLineEndings: resolveLineEndings(args.lineEndings) }); if (args.health !== undefined) { const healthFile = args.health; - const healthInterval = setInterval(() => { + const writeHealth = (): void => { void client.checkConnection().then((status) => { - writeHealthStatus(healthFile, status); + writeHealthStatus(client.logger, healthFile, status); }); - }, HEALTH_CHECK_INTERVAL_MS); + }; + writeHealth(); + const healthInterval = setInterval( + writeHealth, + HEALTH_CHECK_INTERVAL_MS + ); const clearHealthInterval = (): void => { clearInterval(healthInterval); }; @@ -158,17 +172,10 @@ async function main(): Promise { process.on("exit", clearHealthInterval); } - // Add colored log formatter with level filtering - client.logger.onLogEmitted.add((logLine) => { - // Only show messages at or above the configured log level - if (LOG_LEVEL_ORDER[logLine.level] >= LOG_LEVEL_ORDER[args.logLevel]) { - console.log(formatLogLine(logLine)); - } - }); - + client.logger.onLogEmitted.add(logHandler); client.logger.info("Starting sync client"); - const fileWatcher = new FileWatcher(absolutePath, client); + const fileWatcher = new FileWatcher(absolutePath, client, ignorePatterns); client.onWebSocketStatusChanged.add(() => { const isConnected = client.isWebSocketConnected; @@ -177,26 +184,54 @@ async function main(): Promise { ); }); + let syncBatchSize = 0; + let totalSyncOps = 0; + let lastProgressLogTime = 0; + client.onRemainingOperationsCountChanged.add((remaining) => { + if (remaining > syncBatchSize) { + syncBatchSize = remaining; + } + if (remaining === 0) { - client.logger.info("All sync operations completed"); + if (syncBatchSize > 0) { + totalSyncOps += syncBatchSize; + client.logger.info( + `Sync batch complete (${syncBatchSize} operations)` + ); + syncBatchSize = 0; + } } else { - client.logger.info(`${remaining} sync operations remaining`); + const now = Date.now(); + if (now - lastProgressLogTime >= PROGRESS_LOG_INTERVAL_MS) { + client.logger.info( + `Syncing: ${remaining} operations remaining` + ); + lastProgressLogTime = now; + } } }); + let isShuttingDown = false; const gracefulShutdown = async (signal: string): Promise => { - console.log( - colorize( - `\n${signal} received. Shutting down gracefully...`, - "yellow" - ) - ); + if (isShuttingDown) { + return; + } + isShuttingDown = true; + + client.logger.info(`${signal} received, shutting down gracefully`); fileWatcher.stop(); await client.waitUntilFinished(); await client.destroy(); - console.log(colorize("Shutdown complete", "green")); + + if (totalSyncOps > 0) { + client.logger.info( + `Shutdown complete (${totalSyncOps} operations synced)` + ); + } else { + client.logger.info("Shutdown complete"); + } process.exit(0); }; @@ -210,27 +245,21 @@ async function main(): Promise { try { const connectionStatus = await client.checkConnection(); if (!connectionStatus.isSuccessful) { - console.error( - colorize( - `Error: Cannot connect to server: ${connectionStatus.serverMessage}`, - "red" - ) + client.logger.error( + `Cannot connect to server: ${connectionStatus.serverMessage}` ); process.exit(1); } - console.log(`${colorize("✓", "green")} Server connection successful`); - console.log(colorize("Press Ctrl+C to stop", "dim")); - console.log(""); + if (!args.quiet) { + client.logger.info("Server connection successful"); + } await client.start(); fileWatcher.start(); } catch (error) { - console.error( - colorize( - `Fatal error: ${error instanceof Error ? error.message : String(error)}`, - "red" - ) + client.logger.error( + `Fatal error: ${error instanceof Error ? error.message : String(error)}` ); fileWatcher.stop(); @@ -240,11 +269,10 @@ async function main(): Promise { } main().catch((error: unknown) => { + // Last-resort handler before the logger exists + // eslint-disable-next-line no-console console.error( - colorize( - `Unexpected error: ${error instanceof Error ? error.message : String(error)}`, - "red" - ) + `Unexpected error: ${error instanceof Error ? error.message : String(error)}` ); process.exit(1); }); diff --git a/frontend/local-client-cli/src/file-watcher.ts b/frontend/local-client-cli/src/file-watcher.ts index e781d18f..c273a412 100644 --- a/frontend/local-client-cli/src/file-watcher.ts +++ b/frontend/local-client-cli/src/file-watcher.ts @@ -1,15 +1,20 @@ import Watcher from "watcher"; import * as path from "path"; import type { SyncClient, RelativePath } from "sync-client"; +import { toUnixPath, matchesGlob } from "./path-utils"; export class FileWatcher { private watcher: Watcher | undefined; private isRunning = false; + private readonly ignorePatterns: string[]; public constructor( private readonly basePath: string, - private readonly client: SyncClient - ) {} + private readonly client: SyncClient, + ignorePatterns: string[] = [] + ) { + this.ignorePatterns = ignorePatterns; + } public start(): void { if (this.isRunning) { @@ -22,7 +27,8 @@ export class FileWatcher { recursive: true, renameDetection: true, renameTimeout: 125, - ignoreInitial: true + ignoreInitial: true, + ignore: (filePath: string): boolean => this.shouldIgnore(filePath) }); this.watcher.on("add", (filePath: string) => { @@ -56,66 +62,32 @@ export class FileWatcher { this.client.logger.info("File watcher stopped"); } + private shouldIgnore(filePath: string): boolean { + const rel = toUnixPath(path.relative(this.basePath, filePath)); + return this.ignorePatterns.some((pattern) => matchesGlob(rel, pattern)); + } + private handleCreate(relativePath: RelativePath): void { - this.client - .syncLocallyCreatedFile(relativePath) - .catch((err: unknown) => { - this.client.logger.error( - `Failed to sync created file ${relativePath}: ${this.formatError(err)}` - ); - }); + this.client.syncLocallyCreatedFile(relativePath); } private handleChange(relativePath: RelativePath): void { - this.client - .syncLocallyUpdatedFile({ relativePath }) - .catch((err: unknown) => { - this.client.logger.error( - `Failed to sync updated file ${relativePath}: ${this.formatError(err)}` - ); - }); + this.client.syncLocallyUpdatedFile({ relativePath }); } private handleDelete(relativePath: RelativePath): void { - this.client - .syncLocallyDeletedFile(relativePath) - .catch((err: unknown) => { - this.client.logger.error( - `Failed to sync deleted file ${relativePath}: ${this.formatError(err)}` - ); - }); + this.client.syncLocallyDeletedFile(relativePath); } private handleRename(oldPath: RelativePath, newPath: RelativePath): void { this.client.logger.info(`File renamed: ${oldPath} -> ${newPath}`); - this.client - .syncLocallyUpdatedFile({ - oldPath, - relativePath: newPath - }) - .catch((err: unknown) => { - this.client.logger.error( - `Failed to sync renamed file ${oldPath} -> ${newPath}: ${this.formatError(err)}` - ); - }); + this.client.syncLocallyUpdatedFile({ + oldPath, + relativePath: newPath + }); } private toRelativePath(absolutePath: string): RelativePath { - const relative = path.relative(this.basePath, absolutePath); - return this.toUnixPath(relative); - } - - /** - * Convert a native platform path to forward slashes - */ - private toUnixPath(nativePath: string): string { - if (path.sep === "\\") { - return nativePath.replace(/\\/g, "/"); - } - return nativePath; - } - - private formatError(err: unknown): string { - return err instanceof Error ? err.message : String(err); + return toUnixPath(path.relative(this.basePath, absolutePath)); } } diff --git a/frontend/local-client-cli/src/healthcheck.ts b/frontend/local-client-cli/src/healthcheck.ts index 2dd9e721..d7211c88 100644 --- a/frontend/local-client-cli/src/healthcheck.ts +++ b/frontend/local-client-cli/src/healthcheck.ts @@ -1,4 +1,5 @@ #!/usr/bin/env node +/* eslint-disable no-console */ /** * Healthcheck script for Docker container diff --git a/frontend/local-client-cli/src/logger-formatter.test.ts b/frontend/local-client-cli/src/logger-formatter.test.ts new file mode 100644 index 00000000..f3078242 --- /dev/null +++ b/frontend/local-client-cli/src/logger-formatter.test.ts @@ -0,0 +1,50 @@ +import { test } from "node:test"; +import * as assert from "node:assert/strict"; +import { formatLogLine } from "./logger-formatter"; +import { LogLevel } from "sync-client"; + +test("formatLogLine - includes level and message", () => { + const logLine = { + timestamp: new Date("2024-01-15T10:30:45.123Z"), + level: LogLevel.INFO, + message: "Test message" + }; + + const result = formatLogLine(logLine); + assert.ok(result.includes("INFO")); + assert.ok(result.includes("Test message")); +}); + +test("formatLogLine - ERROR level messages contain bold escape", () => { + const logLine = { + timestamp: new Date("2024-01-15T10:30:45.123Z"), + level: LogLevel.ERROR, + message: "Error occurred" + }; + + const result = formatLogLine(logLine); + assert.ok(result.includes("\x1b[1m")); +}); + +test("formatLogLine - highlights file paths in quotes", () => { + const logLine = { + timestamp: new Date("2024-01-15T10:30:45.123Z"), + level: LogLevel.INFO, + message: 'Syncing "notes/test.md"' + }; + + const result = formatLogLine(logLine); + assert.ok(result.includes("\x1b[35m")); +}); + +test("formatLogLine - highlights standalone numbers but not numbers in versions", () => { + const logLine = { + timestamp: new Date("2024-01-15T10:30:45.123Z"), + level: LogLevel.INFO, + message: "Listed 42 files from v1.2.3" + }; + + const result = formatLogLine(logLine); + assert.ok(result.includes("\x1b[36m42\x1b[0m")); + assert.ok(!result.includes("\x1b[36m1\x1b[0m.")); +}); diff --git a/frontend/local-client-cli/src/logger-formatter.ts b/frontend/local-client-cli/src/logger-formatter.ts index 9f237103..b98415b6 100644 --- a/frontend/local-client-cli/src/logger-formatter.ts +++ b/frontend/local-client-cli/src/logger-formatter.ts @@ -1,36 +1,21 @@ import { LogLevel, type LogLine } from "sync-client"; -// ANSI color codes -export const colors = { +const colors = { reset: "\x1b[0m", bold: "\x1b[1m", - dim: "\x1b[2m", - // Foreground colors red: "\x1b[31m", green: "\x1b[32m", yellow: "\x1b[33m", - blue: "\x1b[34m", magenta: "\x1b[35m", cyan: "\x1b[36m", gray: "\x1b[90m" } as const; -export function colorize(text: string, color: keyof typeof colors): string { +function colorize(text: string, color: keyof typeof colors): string { return `${colors[color]}${text}${colors.reset}`; } -/** - * Helper function to apply multiple color modifiers to text - */ -export function styleText( - text: string, - ...modifiers: (keyof typeof colors)[] -): string { - const prefix = modifiers.map((m) => colors[m]).join(""); - return `${prefix}${text}${colors.reset}`; -} - function formatTimestamp(date: Date): string { const [time] = date.toTimeString().split(" "); const ms = date.getMilliseconds().toString().padStart(3, "0"); diff --git a/frontend/local-client-cli/src/node-filesystem.ts b/frontend/local-client-cli/src/node-filesystem.ts index 3da8fc3a..7b736c22 100644 --- a/frontend/local-client-cli/src/node-filesystem.ts +++ b/frontend/local-client-cli/src/node-filesystem.ts @@ -6,6 +6,7 @@ import type { RelativePath, TextWithCursors } from "sync-client"; +import { toUnixPath } from "./path-utils"; export class NodeFileSystemOperations implements FileSystemOperations { public constructor(private readonly basePath: string) {} @@ -14,18 +15,12 @@ export class NodeFileSystemOperations implements FileSystemOperations { directory: RelativePath | undefined ): Promise { const files: RelativePath[] = []; - await this.walkDirectory( - directory !== undefined ? this.toNativePath(directory) : "", - files - ); + await this.walkDirectory(directory ?? "", files); return files; } public async read(relativePath: RelativePath): Promise { - const fullPath = path.join( - this.basePath, - this.toNativePath(relativePath) - ); + const fullPath = path.join(this.basePath, relativePath); try { return await fs.readFile(fullPath); } catch (error) { @@ -39,15 +34,12 @@ export class NodeFileSystemOperations implements FileSystemOperations { relativePath: RelativePath, content: Uint8Array ): Promise { - const fullPath = path.join( - this.basePath, - this.toNativePath(relativePath) - ); + const fullPath = path.join(this.basePath, relativePath); const dir = path.dirname(fullPath); try { await fs.mkdir(dir, { recursive: true }); - await fs.writeFile(fullPath, content); + await this.atomicWrite(fullPath, content); } catch (error) { throw new Error( `Failed to write file ${fullPath}: ${error instanceof Error ? error.message : String(error)}` @@ -59,15 +51,12 @@ export class NodeFileSystemOperations implements FileSystemOperations { relativePath: RelativePath, updater: (current: TextWithCursors) => TextWithCursors ): Promise { - const fullPath = path.join( - this.basePath, - this.toNativePath(relativePath) - ); + const fullPath = path.join(this.basePath, relativePath); try { const currentContent = await fs.readFile(fullPath, "utf-8"); const result = updater({ text: currentContent, cursors: [] }); - await fs.writeFile(fullPath, result.text, "utf-8"); + await this.atomicWrite(fullPath, result.text, "utf-8"); return result.text; } catch (error) { throw new Error( @@ -77,10 +66,7 @@ export class NodeFileSystemOperations implements FileSystemOperations { } public async getFileSize(relativePath: RelativePath): Promise { - const fullPath = path.join( - this.basePath, - this.toNativePath(relativePath) - ); + const fullPath = path.join(this.basePath, relativePath); try { const stats = await fs.stat(fullPath); return stats.size; @@ -92,10 +78,7 @@ export class NodeFileSystemOperations implements FileSystemOperations { } public async exists(relativePath: RelativePath): Promise { - const fullPath = path.join( - this.basePath, - this.toNativePath(relativePath) - ); + const fullPath = path.join(this.basePath, relativePath); try { await fs.access(fullPath); return true; @@ -105,10 +88,7 @@ export class NodeFileSystemOperations implements FileSystemOperations { } public async createDirectory(relativePath: RelativePath): Promise { - const fullPath = path.join( - this.basePath, - this.toNativePath(relativePath) - ); + const fullPath = path.join(this.basePath, relativePath); try { await fs.mkdir(fullPath, { recursive: false }); } catch (error) { @@ -119,10 +99,7 @@ export class NodeFileSystemOperations implements FileSystemOperations { } public async delete(relativePath: RelativePath): Promise { - const fullPath = path.join( - this.basePath, - this.toNativePath(relativePath) - ); + const fullPath = path.join(this.basePath, relativePath); try { await fs.unlink(fullPath); } catch (error) { @@ -136,14 +113,8 @@ export class NodeFileSystemOperations implements FileSystemOperations { oldPath: RelativePath, newPath: RelativePath ): Promise { - const oldFullPath = path.join( - this.basePath, - this.toNativePath(oldPath) - ); - const newFullPath = path.join( - this.basePath, - this.toNativePath(newPath) - ); + const oldFullPath = path.join(this.basePath, oldPath); + const newFullPath = path.join(this.basePath, newPath); const newDir = path.dirname(newFullPath); try { @@ -156,6 +127,19 @@ export class NodeFileSystemOperations implements FileSystemOperations { } } + private async atomicWrite( + fullPath: string, + content: Uint8Array | string, + encoding?: BufferEncoding + ): Promise { + const tmpPath = fullPath + ".tmp"; + await fs.writeFile(tmpPath, content, encoding); + const fd = await fs.open(tmpPath, "r"); + await fd.datasync(); + await fd.close(); + await fs.rename(tmpPath, fullPath); + } + private async walkDirectory( relativePath: string, files: RelativePath[] @@ -179,28 +163,8 @@ export class NodeFileSystemOperations implements FileSystemOperations { await this.walkDirectory(entryRelativePath, files); } else if (entry.isFile()) { // Always return forward slashes - files.push(this.toUnixPath(entryRelativePath)); + files.push(toUnixPath(entryRelativePath)); } } } - - /** - * Convert a forward-slash path to native platform path separators - */ - private toNativePath(relativePath: string): string { - if (path.sep === "\\") { - return relativePath.replace(/\//g, "\\"); - } - return relativePath; - } - - /** - * Convert a native platform path to forward slashes - */ - private toUnixPath(nativePath: string): string { - if (path.sep === "\\") { - return nativePath.replace(/\\/g, "/"); - } - return nativePath; - } } diff --git a/frontend/local-client-cli/src/path-utils.test.ts b/frontend/local-client-cli/src/path-utils.test.ts new file mode 100644 index 00000000..13d33e6e --- /dev/null +++ b/frontend/local-client-cli/src/path-utils.test.ts @@ -0,0 +1,60 @@ +import { test } from "node:test"; +import * as assert from "node:assert/strict"; +import { matchesGlob, toUnixPath } from "./path-utils"; + +test("matchesGlob - exact match", () => { + assert.equal(matchesGlob(".DS_Store", ".DS_Store"), true); + assert.equal(matchesGlob("other", ".DS_Store"), false); +}); + +test("matchesGlob - dir/** matches directory and contents", () => { + assert.equal(matchesGlob(".git", ".git/**"), true); + assert.equal(matchesGlob(".git/config", ".git/**"), true); + assert.equal(matchesGlob(".git/refs/heads/main", ".git/**"), true); + assert.equal(matchesGlob(".gitignore", ".git/**"), false); +}); + +test("matchesGlob - * matches within a single segment", () => { + assert.equal(matchesGlob("foo.tmp", "*.tmp"), true); + assert.equal(matchesGlob("bar.tmp", "*.tmp"), true); + assert.equal(matchesGlob("foo.md", "*.tmp"), false); + assert.equal(matchesGlob("dir/foo.tmp", "*.tmp"), false); +}); + +test("matchesGlob - **/*.ext matches at any depth", () => { + assert.equal(matchesGlob("foo.tmp", "**/*.tmp"), true); + assert.equal(matchesGlob("dir/foo.tmp", "**/*.tmp"), true); + assert.equal(matchesGlob("a/b/c/foo.tmp", "**/*.tmp"), true); + assert.equal(matchesGlob("foo.md", "**/*.tmp"), false); +}); + +test("matchesGlob - ? matches single character", () => { + assert.equal(matchesGlob("a.md", "?.md"), true); + assert.equal(matchesGlob("ab.md", "?.md"), false); + assert.equal(matchesGlob(".md", "?.md"), false); +}); + +test("matchesGlob - dots are literal", () => { + assert.equal(matchesGlob(".DS_Store", ".DS_Store"), true); + assert.equal(matchesGlob("xDS_Store", ".DS_Store"), false); +}); + +test("matchesGlob - node_modules/** matches directory tree", () => { + assert.equal(matchesGlob("node_modules", "node_modules/**"), true); + assert.equal(matchesGlob("node_modules/foo", "node_modules/**"), true); + assert.equal( + matchesGlob("node_modules/foo/bar/baz.js", "node_modules/**"), + true + ); + assert.equal(matchesGlob("not_node_modules", "node_modules/**"), false); +}); + +test("matchesGlob - **/ prefix matches zero or more segments", () => { + assert.equal(matchesGlob("test.log", "**/test.log"), true); + assert.equal(matchesGlob("dir/test.log", "**/test.log"), true); + assert.equal(matchesGlob("a/b/test.log", "**/test.log"), true); +}); + +test("toUnixPath - forward slashes unchanged", () => { + assert.equal(toUnixPath("foo/bar/baz"), "foo/bar/baz"); +}); diff --git a/frontend/local-client-cli/src/path-utils.ts b/frontend/local-client-cli/src/path-utils.ts new file mode 100644 index 00000000..dd89fa67 --- /dev/null +++ b/frontend/local-client-cli/src/path-utils.ts @@ -0,0 +1,15 @@ +import * as path from "path"; + +// Convert a native platform path to forward slashes (no-op on non-Windows) +export function toUnixPath(nativePath: string): string { + return nativePath.split(path.sep).join(path.posix.sep); +} + +// Match a file path against a glob pattern +// Extends path.matchesGlob so that "dir/**" also matches the directory itself +export function matchesGlob(filePath: string, pattern: string): boolean { + if (pattern.endsWith("/**") && filePath === pattern.slice(0, -3)) { + return true; + } + return path.matchesGlob(filePath, pattern); +} diff --git a/frontend/local-client-cli/tsconfig.json b/frontend/local-client-cli/tsconfig.json index 25f249c9..b07ec41a 100644 --- a/frontend/local-client-cli/tsconfig.json +++ b/frontend/local-client-cli/tsconfig.json @@ -18,7 +18,5 @@ "declarationMap": true, "sourceMap": true }, - "exclude": [ - "dist" - ] + "exclude": ["dist"] } diff --git a/frontend/local-client-cli/webpack.config.js b/frontend/local-client-cli/webpack.config.js index f8f48534..9226b9dc 100644 --- a/frontend/local-client-cli/webpack.config.js +++ b/frontend/local-client-cli/webpack.config.js @@ -2,32 +2,32 @@ const path = require("path"); const webpack = require("webpack"); module.exports = { - entry: { - cli: "./src/cli.ts", - healthcheck: "./src/healthcheck.ts" - }, - target: "node", - mode: "production", - optimization: { - minimize: false - }, - module: { - rules: [ - { - test: /\.ts$/, - use: "ts-loader" - } - ] - }, - resolve: { - extensions: [".ts", ".js"] - }, - output: { - globalObject: "this", - filename: "[name].js", - path: path.resolve(__dirname, "dist") - }, - plugins: [ - new webpack.BannerPlugin({ banner: "#!/usr/bin/env node", raw: true }) + entry: { + cli: "./src/cli.ts", + healthcheck: "./src/healthcheck.ts" + }, + target: "node", + mode: "production", + optimization: { + minimize: false + }, + module: { + rules: [ + { + test: /\.ts$/, + use: "ts-loader" + } ] + }, + resolve: { + extensions: [".ts", ".js"] + }, + output: { + globalObject: "this", + filename: "[name].js", + path: path.resolve(__dirname, "dist") + }, + plugins: [ + new webpack.BannerPlugin({ banner: "#!/usr/bin/env node", raw: true }) + ] }; diff --git a/frontend/obsidian-plugin/README.md b/frontend/obsidian-plugin/README.md index 93c2cba7..68e10a83 100644 --- a/frontend/obsidian-plugin/README.md +++ b/frontend/obsidian-plugin/README.md @@ -8,6 +8,7 @@ The repo depends on the latest plugin API (obsidian.d.ts) in TypeScript Definiti **Note:** The Obsidian API is still in early alpha and is subject to change at any time! This sample plugin demonstrates some of the basic functionality the plugin API can do. + - Adds a ribbon icon, which shows a Notice when clicked. - Adds a command "Open Sample Modal" which opens a Modal. - Adds a plugin setting tab to the settings page. @@ -57,31 +58,6 @@ Quick starting guide for new plugin devs: - Copy over `main.js`, `styles.css`, `manifest.json` to your vault `VaultFolder/.obsidian/plugins/your-plugin-id/`. - -## Funding URL - -You can include funding URLs where people who use your plugin can financially support it. - -The simple way is to set the `fundingUrl` field to your link in your `manifest.json` file: - -```json -{ - "fundingUrl": "https://buymeacoffee.com" -} -``` - -If you have multiple URLs, you can also do: - -```json -{ - "fundingUrl": { - "Buy Me a Coffee": "https://buymeacoffee.com", - "GitHub Sponsor": "https://github.com/sponsors", - "Patreon": "https://www.patreon.com/" - } -} -``` - ## API Documentation See https://github.com/obsidianmd/obsidian-api diff --git a/frontend/obsidian-plugin/package.json b/frontend/obsidian-plugin/package.json index b7ae4909..d24e537b 100644 --- a/frontend/obsidian-plugin/package.json +++ b/frontend/obsidian-plugin/package.json @@ -13,25 +13,25 @@ "author": "", "license": "MIT", "devDependencies": { - "@types/node": "^24.8.1", + "@types/node": "^25.0.2", "css-loader": "^7.1.2", "date-fns": "^4.1.0", "file-loader": "^6.2.0", - "fs-extra": "^11.3.0", - "mini-css-extract-plugin": "^2.9.2", - "obsidian": "1.10.2", - "reconcile-text": "^0.8.0", + "fs-extra": "^11.3.2", + "mini-css-extract-plugin": "^2.9.4", + "obsidian": "1.11.0", + "reconcile-text": "^0.11.0", "resolve-url-loader": "^5.0.0", - "sass": "^1.91.0", + "sass": "^1.96.0", "sass-loader": "^16.0.6", "sync-client": "file:../sync-client", - "terser-webpack-plugin": "^5.3.14", - "ts-loader": "^9.5.2", + "terser-webpack-plugin": "^5.3.16", + "ts-loader": "^9.5.4", "tslib": "2.8.1", - "tsx": "^4.20.6", - "typescript": "5.8.3", + "tsx": "^4.21.0", + "typescript": "5.9.3", "url": "^0.11.4", - "webpack": "^5.99.9", + "webpack": "^5.103.0", "webpack-cli": "^6.0.1" } } diff --git a/frontend/obsidian-plugin/src/vault-link-plugin.ts b/frontend/obsidian-plugin/src/vault-link-plugin.ts index 7d91b9f5..e222796b 100644 --- a/frontend/obsidian-plugin/src/vault-link-plugin.ts +++ b/frontend/obsidian-plugin/src/vault-link-plugin.ts @@ -135,14 +135,14 @@ export default class VaultLinkPlugin extends Plugin { nativeLineEndings: Platform.isWin ? "\r\n" : "\n", ...(IS_DEBUG_BUILD ? { - fetch: debugging.slowFetchFactory(1), - webSocket: debugging.slowWebSocketFactory(1, new Logger()) - } + fetch: debugging.slowFetchFactory(1), + webSocket: debugging.slowWebSocketFactory(1, new Logger()) + } : {}) }); if (IS_DEBUG_BUILD) { - debugging.logToConsole(client); + debugging.logToConsole(client.logger); } return client; @@ -231,9 +231,9 @@ export default class VaultLinkPlugin extends Plugin { } } ), - this.app.vault.on("create", async (file: TAbstractFile) => { + this.app.vault.on("create", (file: TAbstractFile) => { if (file instanceof TFile) { - await client.syncLocallyCreatedFile(file.path); + client.syncLocallyCreatedFile(file.path); } }), this.app.vault.on("modify", async (file: TAbstractFile) => { @@ -241,14 +241,14 @@ export default class VaultLinkPlugin extends Plugin { await this.rateLimitedUpdate(file.path, client); } }), - this.app.vault.on("delete", async (file: TAbstractFile) => { - await client.syncLocallyDeletedFile(file.path); + this.app.vault.on("delete", (file: TAbstractFile) => { + client.syncLocallyDeletedFile(file.path); }), this.app.vault.on( "rename", - async (file: TAbstractFile, oldPath: string) => { + (file: TAbstractFile, oldPath: string) => { if (file instanceof TFile) { - await client.syncLocallyUpdatedFile({ + client.syncLocallyUpdatedFile({ oldPath, relativePath: file.path }); @@ -267,13 +267,11 @@ export default class VaultLinkPlugin extends Plugin { if (!this.rateLimitedUpdatesPerFile.has(path)) { this.rateLimitedUpdatesPerFile.set( path, - rateLimit( - async () => - client.syncLocallyUpdatedFile({ - relativePath: path - }), - MIN_WAIT_BETWEEN_UPDATES_IN_MS - ) + rateLimit(async () => { + client.syncLocallyUpdatedFile({ + relativePath: path + }); + }, MIN_WAIT_BETWEEN_UPDATES_IN_MS) ); } await this.rateLimitedUpdatesPerFile.get(path)?.(); diff --git a/frontend/obsidian-plugin/src/views/cursors/file-explorer.ts b/frontend/obsidian-plugin/src/views/cursors/file-explorer.ts index 3088c640..409402a4 100644 --- a/frontend/obsidian-plugin/src/views/cursors/file-explorer.ts +++ b/frontend/obsidian-plugin/src/views/cursors/file-explorer.ts @@ -14,7 +14,9 @@ export function renderCursorsInFileExplorer( app: App ): void { const fileExplorers = app.workspace.getLeavesOfType("file-explorer"); - if (fileExplorers.length == 0) return; + if (fileExplorers.length == 0) { + return; + } const [fileExplorer] = fileExplorers; @@ -34,7 +36,7 @@ export function renderCursorsInFileExplorer( (parent) => { cursors.forEach((cursor) => { cursor.documentsWithCursors.forEach((document) => { - if (document.relative_path.startsWith(key)) { + if (document.relativePath.startsWith(key)) { parent.appendChild( createSpan({ text: cursor.userName, diff --git a/frontend/obsidian-plugin/src/views/cursors/remote-cursors-plugin.ts b/frontend/obsidian-plugin/src/views/cursors/remote-cursors-plugin.ts index 1191d9a2..4200a72a 100644 --- a/frontend/obsidian-plugin/src/views/cursors/remote-cursors-plugin.ts +++ b/frontend/obsidian-plugin/src/views/cursors/remote-cursors-plugin.ts @@ -61,7 +61,7 @@ export class RemoteCursorsPluginValue implements PluginValue { return clientCursors.flatMap((cursor) => cursor.cursors.map((span) => ({ name: client.userName, - path: cursor.relative_path, + path: cursor.relativePath, deviceId: client.deviceId, isOutdated: client.isOutdated, span: { ...span } @@ -132,7 +132,8 @@ export class RemoteCursorsPluginValue implements PluginValue { ] ) }, - edited + edited, + "Markdown" ); reconciled.cursors.forEach(({ id, position }) => { diff --git a/frontend/obsidian-plugin/src/views/settings/settings-tab.ts b/frontend/obsidian-plugin/src/views/settings/settings-tab.ts index 213c0d2c..5a5823c2 100644 --- a/frontend/obsidian-plugin/src/views/settings/settings-tab.ts +++ b/frontend/obsidian-plugin/src/views/settings/settings-tab.ts @@ -266,9 +266,8 @@ export class SyncSettingsTab extends PluginSettingTab { new Notice("Checking connection to the server..."); new Notice( - ( - await this.syncClient.checkConnection() - ).serverMessage + (await this.syncClient.checkConnection()) + .serverMessage ); await this.statusDescription.updateConnectionState(); } else { @@ -351,22 +350,6 @@ export class SyncSettingsTab extends PluginSettingTab { }) ); - new Setting(containerEl) - .setName("Sync concurrency") - .setDesc( - "How many concurrent sync operations to run. Setting this value higher may increase the overall performance, however, it will require more memory as well. If you notice frequent crashes, especially on mobile, set this to 1." - ) - .addSlider((text) => - text - .setLimits(1, 16, 1) - .setDynamicTooltip() - .setInstant(false) - .setValue(this.syncClient.getSettings().syncConcurrency) - .onChange(async (value) => - this.syncClient.setSetting("syncConcurrency", value) - ) - ); - new Setting(containerEl) .setName("Maximum file size to be uploaded (MB)") .setDesc( @@ -484,40 +467,6 @@ export class SyncSettingsTab extends PluginSettingTab { ); }) ); - - new Setting(containerEl) - .setName("Minimum save interval (ms)") - .setDesc( - "The minimum time between saving settings and database to disk, in milliseconds. Lower values save more frequently but may impact performance." - ) - .addText((input) => - input - .setValue( - this.syncClient - .getSettings() - .minimumSaveIntervalMs.toString() - ) - .onChange(async (value) => { - if (value === "") { - return; - } - let parsedValue = Number.parseInt(value, 10); - if (Number.isNaN(parsedValue) || parsedValue < 0) { - parsedValue = - this.syncClient.getSettings() - .minimumSaveIntervalMs; - } - - if (value !== parsedValue.toString()) { - input.setValue(parsedValue.toString()); - } - - return this.syncClient.setSetting( - "minimumSaveIntervalMs", - parsedValue - ); - }) - ); } private setStatusDescriptionSubscription( diff --git a/frontend/obsidian-plugin/src/views/status-description/status-description.ts b/frontend/obsidian-plugin/src/views/status-description/status-description.ts index 53fea486..6d8d74fe 100644 --- a/frontend/obsidian-plugin/src/views/status-description/status-description.ts +++ b/frontend/obsidian-plugin/src/views/status-description/status-description.ts @@ -88,7 +88,7 @@ export class StatusDescription { text: ` and has indexed approximately ` }); container.createSpan({ - text: `${this.syncClient.documentCount}`, + text: `${this.syncClient.syncedDocumentCount}`, cls: "number" }); container.createSpan({ diff --git a/frontend/obsidian-plugin/tsconfig.json b/frontend/obsidian-plugin/tsconfig.json index 81af03a7..7ec2a9cd 100644 --- a/frontend/obsidian-plugin/tsconfig.json +++ b/frontend/obsidian-plugin/tsconfig.json @@ -6,12 +6,7 @@ "strict": true, "moduleResolution": "bundler", "allowSyntheticDefaultImports": true, - "lib": [ - "DOM", - "ES2024" - ] + "lib": ["DOM", "ES2024"] }, - "exclude": [ - "./dist" - ] + "exclude": ["./dist"] } diff --git a/frontend/obsidian-plugin/webpack.config.js b/frontend/obsidian-plugin/webpack.config.js index b749b20d..794f30de 100644 --- a/frontend/obsidian-plugin/webpack.config.js +++ b/frontend/obsidian-plugin/webpack.config.js @@ -46,7 +46,7 @@ module.exports = (env, argv) => ({ const source = path.resolve(__dirname, "dist"); const destinations = [ "/volumes/syncthing/Desktop/test/test/.obsidian/plugins/vault-link", - "/volumes/syncthing/Desktop/test/test2/.obsidian/plugins/vault-link", + "/volumes/syncthing/Desktop/test/test2/.obsidian/plugins/vault-link" // "/home/andras/obsidian-test/.obsidian/plugins/vault-link" ]; destinations.forEach((destination) => { From 201f9aeaee5b90fbdc97f8d900c98c9ff44bd6d2 Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Sat, 9 May 2026 13:46:48 +0100 Subject: [PATCH 15/17] Remove clutter --- frontend/local-client-cli/src/args.test.ts | 237 --------------------- 1 file changed, 237 deletions(-) diff --git a/frontend/local-client-cli/src/args.test.ts b/frontend/local-client-cli/src/args.test.ts index c075d193..fdf0b6c8 100644 --- a/frontend/local-client-cli/src/args.test.ts +++ b/frontend/local-client-cli/src/args.test.ts @@ -150,25 +150,6 @@ test("parseArgs - default log level is INFO", () => { assert.equal(args.logLevel, LogLevel.INFO); }); -test("parseArgs - parse DEBUG log level", () => { - const args = parseArgs([ - "node", - "cli.js", - "-l", - "/path/to/vault", - "-r", - "https://sync.example.com", - "-t", - "mytoken", - "-v", - "default", - "--log-level", - "DEBUG" - ]); - - assert.equal(args.logLevel, LogLevel.DEBUG); -}); - test("parseArgs - parse ERROR log level", () => { const args = parseArgs([ "node", @@ -188,43 +169,6 @@ test("parseArgs - parse ERROR log level", () => { assert.equal(args.logLevel, LogLevel.ERROR); }); -test("parseArgs - log level is case insensitive", () => { - const args = parseArgs([ - "node", - "cli.js", - "-l", - "/path/to/vault", - "-r", - "https://sync.example.com", - "-t", - "mytoken", - "-v", - "default", - "--log-level", - "debug" - ]); - - assert.equal(args.logLevel, LogLevel.DEBUG); -}); - -test("parseArgs - throws on invalid log level", () => { - assert.throws(() => { - parseArgs([ - "node", - "cli.js", - "-l", - "/path/to/vault", - "-r", - "https://sync.example.com", - "-t", - "mytoken", - "-v", - "default", - "--log-level", - "INVALID" - ]); - }, /Invalid log level/); -}); test("parseArgs - reads required options from environment variables", () => { process.env.VAULTLINK_LOCAL_PATH = "/env/path"; @@ -267,184 +211,3 @@ test("parseArgs - CLI arguments take precedence over environment variables", () delete process.env.VAULTLINK_TOKEN; } }); - -test("parseArgs - reads log level from environment variable", () => { - process.env.VAULTLINK_LOG_LEVEL = "DEBUG"; - - try { - const args = parseArgs([ - "node", - "cli.js", - "-l", - "/path/to/vault", - "-r", - "https://sync.example.com", - "-t", - "mytoken", - "-v", - "default" - ]); - assert.equal(args.logLevel, LogLevel.DEBUG); - } finally { - delete process.env.VAULTLINK_LOG_LEVEL; - } -}); - -test("parseArgs - quiet defaults to false", () => { - const args = parseArgs([ - "node", - "cli.js", - "-l", - "/path/to/vault", - "-r", - "https://sync.example.com", - "-t", - "mytoken", - "-v", - "default" - ]); - - assert.equal(args.quiet, false); -}); - -test("parseArgs - parse --quiet flag", () => { - const args = parseArgs([ - "node", - "cli.js", - "-l", - "/path/to/vault", - "-r", - "https://sync.example.com", - "-t", - "mytoken", - "-v", - "default", - "--quiet" - ]); - - assert.equal(args.quiet, true); -}); - -test("parseArgs - parse -q short flag", () => { - const args = parseArgs([ - "node", - "cli.js", - "-l", - "/path/to/vault", - "-r", - "https://sync.example.com", - "-t", - "mytoken", - "-v", - "default", - "-q" - ]); - - assert.equal(args.quiet, true); -}); - -test("parseArgs - line-endings defaults to auto", () => { - const args = parseArgs([ - "node", - "cli.js", - "-l", - "/path/to/vault", - "-r", - "https://sync.example.com", - "-t", - "mytoken", - "-v", - "default" - ]); - - assert.equal(args.lineEndings, "auto"); -}); - -test("parseArgs - parse --line-endings lf", () => { - const args = parseArgs([ - "node", - "cli.js", - "-l", - "/path/to/vault", - "-r", - "https://sync.example.com", - "-t", - "mytoken", - "-v", - "default", - "--line-endings", - "lf" - ]); - - assert.equal(args.lineEndings, "lf"); -}); - -test("parseArgs - parse --line-endings crlf", () => { - const args = parseArgs([ - "node", - "cli.js", - "-l", - "/path/to/vault", - "-r", - "https://sync.example.com", - "-t", - "mytoken", - "-v", - "default", - "--line-endings", - "crlf" - ]); - - assert.equal(args.lineEndings, "crlf"); -}); - -test("parseArgs - throws on invalid remote URI protocol", () => { - assert.throws(() => { - parseArgs([ - "node", - "cli.js", - "-l", - "/path/to/vault", - "-r", - "ftp://sync.example.com", - "-t", - "mytoken", - "-v", - "default" - ]); - }, /Invalid remote URI/); -}); - -test("parseArgs - accepts http:// remote URI", () => { - const args = parseArgs([ - "node", - "cli.js", - "-l", - "/path/to/vault", - "-r", - "http://localhost:3000", - "-t", - "mytoken", - "-v", - "default" - ]); - - assert.equal(args.remoteUri, "http://localhost:3000"); -}); - -test("parseArgs - accepts wss:// remote URI", () => { - const args = parseArgs([ - "node", - "cli.js", - "-l", - "/path/to/vault", - "-r", - "wss://sync.example.com", - "-t", - "mytoken", - "-v", - "default" - ]); - - assert.equal(args.remoteUri, "wss://sync.example.com"); -}); From 6647a4e63234435e57ebc779befb0c258c99802e Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Sat, 9 May 2026 14:17:52 +0100 Subject: [PATCH 16/17] Improvements --- frontend/local-client-cli/src/args.ts | 80 +++++++++++-------- frontend/local-client-cli/src/cli.ts | 45 ++++++----- .../local-client-cli/src/node-filesystem.ts | 28 +++++-- frontend/local-client-cli/src/path-utils.ts | 10 ++- frontend/obsidian-plugin/webpack.config.js | 1 - 5 files changed, 104 insertions(+), 60 deletions(-) diff --git a/frontend/local-client-cli/src/args.ts b/frontend/local-client-cli/src/args.ts index 442c4817..34d839b1 100644 --- a/frontend/local-client-cli/src/args.ts +++ b/frontend/local-client-cli/src/args.ts @@ -2,7 +2,8 @@ import { Command, Option } from "commander"; import packageJson from "../package.json"; import { LogLevel } from "sync-client"; -type LineEndingMode = "auto" | "lf" | "crlf"; +export const LINE_ENDING_MODES = ["auto", "lf", "crlf"] as const; +export type LineEndingMode = (typeof LINE_ENDING_MODES)[number]; interface CliArgs { remoteUri: string; @@ -21,6 +22,35 @@ interface CliArgs { const VALID_PROTOCOLS = ["http://", "https://", "ws://", "wss://"]; +const REQUIRED_OPTIONS = { + localPath: { + flags: "-l, --local-path ", + env: "VAULTLINK_LOCAL_PATH" + }, + remoteUri: { + flags: "-r, --remote-uri ", + env: "VAULTLINK_REMOTE_URI" + }, + token: { flags: "-t, --token ", env: "VAULTLINK_TOKEN" }, + vaultName: { + flags: "-v, --vault-name ", + env: "VAULTLINK_VAULT_NAME" + } +} as const; + +function requireOption( + value: T | undefined, + name: keyof typeof REQUIRED_OPTIONS +): T { + if (value === undefined) { + const { flags, env } = REQUIRED_OPTIONS[name]; + throw new Error( + `required option '${flags}' not specified (or set ${env})` + ); + } + return value; +} + export function parseArgs(argv: string[]): CliArgs { const program = new Command(); @@ -32,23 +62,25 @@ export function parseArgs(argv: string[]): CliArgs { .version(packageJson.version) .addOption( new Option( - "-l, --local-path ", + REQUIRED_OPTIONS.localPath.flags, "Local directory path to sync" - ).env("VAULTLINK_LOCAL_PATH") + ).env(REQUIRED_OPTIONS.localPath.env) ) .addOption( - new Option("-r, --remote-uri ", "Remote server URI").env( - "VAULTLINK_REMOTE_URI" - ) + new Option( + REQUIRED_OPTIONS.remoteUri.flags, + "Remote server URI" + ).env(REQUIRED_OPTIONS.remoteUri.env) ) .addOption( - new Option("-t, --token ", "Authentication token").env( - "VAULTLINK_TOKEN" - ) + new Option( + REQUIRED_OPTIONS.token.flags, + "Authentication token" + ).env(REQUIRED_OPTIONS.token.env) ) .addOption( - new Option("-v, --vault-name ", "Vault name").env( - "VAULTLINK_VAULT_NAME" + new Option(REQUIRED_OPTIONS.vaultName.flags, "Vault name").env( + REQUIRED_OPTIONS.vaultName.env ) ) .addOption( @@ -105,7 +137,7 @@ export function parseArgs(argv: string[]): CliArgs { "[OPTIONAL] Line ending style: auto (platform default), lf, crlf" ) .default("auto") - .choices(["auto", "lf", "crlf"]) + .choices([...LINE_ENDING_MODES]) .env("VAULTLINK_LINE_ENDINGS") ) .addHelpText( @@ -144,22 +176,6 @@ Environment variables: const lineEndingsStr = (opts.lineEndings as string | undefined) ?? "auto"; /* eslint-enable @typescript-eslint/no-unsafe-type-assertion */ - const requireOption = (value: T | undefined, name: string): T => { - if (value === undefined) { - const option = program.options.find( - (o) => o.attributeName() === name - ); - const envHint = - option?.envVar !== undefined - ? ` (or set ${option.envVar})` - : ""; - throw new Error( - `required option '${option?.flags ?? name}' not specified${envHint}` - ); - } - return value; - }; - const requiredLocalPath = requireOption(localPath, "localPath"); const requiredRemoteUri = requireOption(remoteUri, "remoteUri"); const requiredToken = requireOption(token, "token"); @@ -187,13 +203,11 @@ Environment variables: } const logLevel = logLevelUpper; - const validLineEndings: readonly string[] = ["auto", "lf", "crlf"]; - const isLineEndingMode = (value: string): value is LineEndingMode => { - return validLineEndings.includes(value); - }; + const isLineEndingMode = (value: string): value is LineEndingMode => + (LINE_ENDING_MODES as readonly string[]).includes(value); if (!isLineEndingMode(lineEndingsStr)) { throw new Error( - `Invalid line endings mode '${lineEndingsStr}'. Valid values are: ${validLineEndings.join(", ")}` + `Invalid line endings mode '${lineEndingsStr}'. Valid values are: ${LINE_ENDING_MODES.join(", ")}` ); } const lineEndings = lineEndingsStr; diff --git a/frontend/local-client-cli/src/cli.ts b/frontend/local-client-cli/src/cli.ts index e06fda47..31c81d5c 100644 --- a/frontend/local-client-cli/src/cli.ts +++ b/frontend/local-client-cli/src/cli.ts @@ -7,12 +7,12 @@ import { DEFAULT_SETTINGS, Logger, LogLevel, - type LogLine, + LogLine, type SyncSettings, type StoredDatabase } from "sync-client"; -import { parseArgs } from "./args"; -import { NodeFileSystemOperations } from "./node-filesystem"; +import { parseArgs, type LineEndingMode } from "./args"; +import { NodeFileSystemOperations, VAULTLINK_DIR } from "./node-filesystem"; import { FileWatcher } from "./file-watcher"; import { formatLogLine } from "./logger-formatter"; import packageJson from "../package.json"; @@ -50,7 +50,7 @@ function createLogHandler(minLevel: LogLevel): (logLine: LogLine) => void { const HEALTH_CHECK_INTERVAL_MS = 30 * 1000; const PROGRESS_LOG_INTERVAL_MS = 2000; -function resolveLineEndings(mode: "auto" | "lf" | "crlf"): string { +function resolveLineEndings(mode: LineEndingMode): string { switch (mode) { case "lf": return "\n"; @@ -65,9 +65,13 @@ async function main(): Promise { const args = parseArgs(process.argv); const absolutePath = path.resolve(args.localPath); - const logger = new Logger(); const logHandler = createLogHandler(args.logLevel); - logger.onLogEmitted.add(logHandler); + // Boot-time messages are emitted directly through logHandler before the + // SyncClient (and its Logger) exist; afterwards every log line flows + // through client.logger. + const emitBoot = (level: LogLevel, message: string): void => { + logHandler(new LogLine(level, message)); + }; if (!fsSync.existsSync(absolutePath)) { fsSync.mkdirSync(absolutePath, { recursive: true }); @@ -76,27 +80,31 @@ async function main(): Promise { try { const stats = await fs.stat(absolutePath); if (!stats.isDirectory()) { - logger.error(`${absolutePath} is not a directory`); + emitBoot(LogLevel.ERROR, `${absolutePath} is not a directory`); process.exit(1); } } catch (error) { - logger.error( + emitBoot( + LogLevel.ERROR, `Cannot access directory ${absolutePath}: ${error instanceof Error ? error.message : String(error)}` ); process.exit(1); } if (!args.quiet) { - logger.info(`VaultLink Local CLI v${packageJson.version}`); - logger.info(`Local path: ${absolutePath}`); - logger.info(`Remote URI: ${args.remoteUri}`); - logger.info(`Vault name: ${args.vaultName}`); + emitBoot(LogLevel.INFO, `VaultLink Local CLI v${packageJson.version}`); + emitBoot(LogLevel.INFO, `Local path: ${absolutePath}`); + emitBoot(LogLevel.INFO, `Remote URI: ${args.remoteUri}`); + emitBoot(LogLevel.INFO, `Vault name: ${args.vaultName}`); if (args.lineEndings !== "auto") { - logger.info(`Line endings: ${args.lineEndings.toUpperCase()}`); + emitBoot( + LogLevel.INFO, + `Line endings: ${args.lineEndings.toUpperCase()}` + ); } } - const dataDir = path.join(absolutePath, ".vaultlink"); + const dataDir = path.join(absolutePath, VAULTLINK_DIR); const dataFile = path.join(dataDir, "sync-data.json"); await fs.mkdir(dataDir, { recursive: true }); @@ -105,8 +113,7 @@ async function main(): Promise { const ignorePatterns = [ ...(args.ignorePatterns ?? []), - ".vaultlink/**", - ".git/**" + `${VAULTLINK_DIR}/**` ]; const settings: SyncSettings = { @@ -134,7 +141,10 @@ async function main(): Promise { // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion database = JSON.parse(content) as Partial; } catch { - logger.warn(`Cannot read data file at ${dataFile}`); + emitBoot( + LogLevel.WARNING, + `Cannot read data file at ${dataFile}` + ); } return { @@ -269,7 +279,6 @@ async function main(): Promise { } main().catch((error: unknown) => { - // Last-resort handler before the logger exists // eslint-disable-next-line no-console console.error( `Unexpected error: ${error instanceof Error ? error.message : String(error)}` diff --git a/frontend/local-client-cli/src/node-filesystem.ts b/frontend/local-client-cli/src/node-filesystem.ts index 7b736c22..08db361e 100644 --- a/frontend/local-client-cli/src/node-filesystem.ts +++ b/frontend/local-client-cli/src/node-filesystem.ts @@ -1,6 +1,7 @@ import * as fs from "fs/promises"; import type { Dirent } from "fs"; import * as path from "path"; +import { randomUUID } from "crypto"; import type { FileSystemOperations, RelativePath, @@ -8,6 +9,11 @@ import type { } from "sync-client"; import { toUnixPath } from "./path-utils"; +// VaultLink's per-vault metadata directory. Holds the persisted sync database +// and the tmp files atomicWrite renames into place; the matching `${VAULTLINK_DIR}/**` +// ignore pattern keeps everything in here invisible to the file watcher. +export const VAULTLINK_DIR = ".vaultlink"; + export class NodeFileSystemOperations implements FileSystemOperations { public constructor(private readonly basePath: string) {} @@ -132,12 +138,22 @@ export class NodeFileSystemOperations implements FileSystemOperations { content: Uint8Array | string, encoding?: BufferEncoding ): Promise { - const tmpPath = fullPath + ".tmp"; - await fs.writeFile(tmpPath, content, encoding); - const fd = await fs.open(tmpPath, "r"); - await fd.datasync(); - await fd.close(); - await fs.rename(tmpPath, fullPath); + const tmpDir = path.join(this.basePath, VAULTLINK_DIR); + await fs.mkdir(tmpDir, { recursive: true }); + const tmpPath = path.join(tmpDir, `atomic-write-${randomUUID()}.tmp`); + try { + await fs.writeFile(tmpPath, content, encoding); + const fd = await fs.open(tmpPath, "r"); + try { + await fd.datasync(); + } finally { + await fd.close(); + } + await fs.rename(tmpPath, fullPath); + } catch (error) { + await fs.unlink(tmpPath).catch(() => undefined); + throw error; + } } private async walkDirectory( diff --git a/frontend/local-client-cli/src/path-utils.ts b/frontend/local-client-cli/src/path-utils.ts index dd89fa67..1ead144c 100644 --- a/frontend/local-client-cli/src/path-utils.ts +++ b/frontend/local-client-cli/src/path-utils.ts @@ -5,8 +5,14 @@ export function toUnixPath(nativePath: string): string { return nativePath.split(path.sep).join(path.posix.sep); } -// Match a file path against a glob pattern -// Extends path.matchesGlob so that "dir/**" also matches the directory itself +// Match a file path against a glob pattern. +// +// Behaves like Node's path.matchesGlob with one extension: `dir/**` matches +// the directory `dir` itself, not only its descendants. The watcher feeds us +// a directory's relative path (e.g. ".git") at the same time it's about to +// recurse into it, and the natural way for users to write the ignore pattern +// is `.git/**` — under stdlib semantics that pattern would let the directory +// through and only block its children, defeating the prune. export function matchesGlob(filePath: string, pattern: string): boolean { if (pattern.endsWith("/**") && filePath === pattern.slice(0, -3)) { return true; diff --git a/frontend/obsidian-plugin/webpack.config.js b/frontend/obsidian-plugin/webpack.config.js index 794f30de..12844fd7 100644 --- a/frontend/obsidian-plugin/webpack.config.js +++ b/frontend/obsidian-plugin/webpack.config.js @@ -47,7 +47,6 @@ module.exports = (env, argv) => ({ const destinations = [ "/volumes/syncthing/Desktop/test/test/.obsidian/plugins/vault-link", "/volumes/syncthing/Desktop/test/test2/.obsidian/plugins/vault-link" - // "/home/andras/obsidian-test/.obsidian/plugins/vault-link" ]; destinations.forEach((destination) => { fs.copy(source, destination) From d99e249fa53a771b0665b9a8cb84ee89d775f412 Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Sat, 9 May 2026 14:20:36 +0100 Subject: [PATCH 17/17] Durable rename --- .../local-client-cli/src/node-filesystem.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/frontend/local-client-cli/src/node-filesystem.ts b/frontend/local-client-cli/src/node-filesystem.ts index 08db361e..ba95ab6a 100644 --- a/frontend/local-client-cli/src/node-filesystem.ts +++ b/frontend/local-client-cli/src/node-filesystem.ts @@ -15,7 +15,7 @@ import { toUnixPath } from "./path-utils"; export const VAULTLINK_DIR = ".vaultlink"; export class NodeFileSystemOperations implements FileSystemOperations { - public constructor(private readonly basePath: string) {} + public constructor(private readonly basePath: string) { } public async listFilesRecursively( directory: RelativePath | undefined @@ -150,12 +150,27 @@ export class NodeFileSystemOperations implements FileSystemOperations { await fd.close(); } await fs.rename(tmpPath, fullPath); + await this.syncDirectory(path.dirname(fullPath)); } catch (error) { await fs.unlink(tmpPath).catch(() => undefined); throw error; } } + // Make the rename durable by fsync'ing the destination's parent directory. + // Skipped on Windows: fsync on a directory handle isn't supported there + private async syncDirectory(dir: string): Promise { + if (process.platform === "win32") { + return; + } + const fd = await fs.open(dir, "r"); + try { + await fd.sync(); + } finally { + await fd.close(); + } + } + private async walkDirectory( relativePath: string, files: RelativePath[]