diff --git a/.cairn/baseline.json b/.cairn/baseline.json
index 923bca3bc3..3646b363c8 100644
--- a/.cairn/baseline.json
+++ b/.cairn/baseline.json
@@ -1,65 +1,58 @@
-{
- "R1 obc-app board-inputs": 1,
- "R1 obc-app card-storage": 5,
- "R1 obc-app device-link": 1,
- "R1 obc-app discovery": 10,
- "R1 obc-app firmware-update": 1,
- "R1 obc-app navigation": 11,
- "R1 obc-app ride-recording": 8,
- "R1 obc-app rider-interface": 87,
- "R1 obc-data-steps content": 3,
- "R1 obc-data-steps device-map-baking": 3,
- "R1 obc-data-steps planner-map-baking": 2,
- "R1 obc-data-steps source-preparation": 7,
- "R1 obc-fw-nrf54l board-support": 26,
- "R2 content host host/": 1,
- "R2 content host tools/": 1,
- "R2 data-engine host host/": 1,
- "R2 data-engine host tools/": 1,
- "R2 device-link host host/": 1,
- "R2 device-link host sim/": 1,
- "R2 device-map-baking host host/": 1,
- "R2 device-map-baking host tools/": 1,
- "R2 map-assembly web builder/wasm/": 1,
- "R2 map-assembly web builder/web/": 1,
- "R2 planner-map-baking host host/": 1,
- "R2 planner-map-baking host tools/": 1,
- "R2 repository-tooling host firmware/tools/": 1,
- "R2 repository-tooling host host/": 1,
- "R2 repository-tooling host tools/": 1,
- "R2 routing host planner/": 1,
- "R2 routing host tools/": 1,
- "R2 search host host/": 1,
- "R2 search host planner/": 1,
- "R2 search host tools/": 1,
- "R2 source-preparation host host/": 1,
- "R2 source-preparation host tools/": 1,
- "R2 trailview host host/": 1,
- "R2 trailview host tools/": 1,
- "R3 companion-ios": 48450,
- "R3 device-firmware": 13702,
- "R3 device-map-builder": 17788,
- "R3 obc-data": 2006,
- "R3 planner-tile-server": 636,
- "R3 simulators": 15003,
- "R3 trailview-page": 63,
- "R3 web-planner": 13,
- "R3 website": 2008,
- "R4 content": 8,
- "R4 data-engine": 5,
- "R4 device-map-baking": 1,
- "R4 planner-map-baking": 17,
- "R4 routing": 1,
- "R4 search": 2,
- "R4 source-preparation": 3,
- "R4 trailview": 13,
- "cycle card-storage -> device-link": 1,
- "cycle content -> device-map-baking": 1,
- "cycle content -> map-reading": 1,
- "cycle device-link -> card-storage": 1,
- "cycle device-map-baking -> content": 1,
- "cycle device-map-baking -> map-reading": 1,
- "cycle device-map-baking -> source-preparation": 1,
- "cycle map-reading -> device-map-baking": 1,
- "cycle source-preparation -> map-reading": 1
-}
+[
+ "R1 obc-app board-inputs",
+ "R1 obc-app card-storage",
+ "R1 obc-app device-link",
+ "R1 obc-app discovery",
+ "R1 obc-app firmware-update",
+ "R1 obc-app navigation",
+ "R1 obc-app ride-recording",
+ "R1 obc-app rider-interface",
+ "R1 obc-data-steps content",
+ "R1 obc-data-steps device-map-baking",
+ "R1 obc-data-steps planner-map-baking",
+ "R1 obc-data-steps source-preparation",
+ "R1 obc-fw-nrf54l board-support",
+ "R4 content",
+ "R4 data-engine",
+ "R4 device-map-baking",
+ "R4 planner-map-baking",
+ "R4 routing",
+ "R4 search",
+ "R4 source-preparation",
+ "R4 trailview",
+ "cycle card-storage -> device-link",
+ "cycle content -> device-map-baking",
+ "cycle content -> map-reading",
+ "cycle device-link -> card-storage",
+ "cycle device-link -> device-map-builder",
+ "cycle device-link -> firmware-update",
+ "cycle device-link -> map-assembly",
+ "cycle device-map-baking -> content",
+ "cycle device-map-baking -> map-reading",
+ "cycle device-map-baking -> source-preparation",
+ "cycle device-map-builder -> device-link",
+ "cycle device-map-builder -> firmware-update",
+ "cycle device-map-builder -> map-assembly",
+ "cycle device-map-builder -> map-style",
+ "cycle device-map-builder -> route-planning",
+ "cycle device-map-builder -> trailview",
+ "cycle firmware-update -> device-link",
+ "cycle host-runtime -> card-storage",
+ "cycle map-assembly -> card-storage",
+ "cycle map-assembly -> device-link",
+ "cycle map-assembly -> device-map-builder",
+ "cycle map-assembly -> host-runtime",
+ "cycle map-assembly -> map-style",
+ "cycle map-assembly -> route-planning",
+ "cycle map-reading -> device-map-baking",
+ "cycle map-style -> device-map-builder",
+ "cycle map-style -> map-assembly",
+ "cycle route-planning -> device-map-builder",
+ "cycle route-planning -> map-assembly",
+ "cycle route-planning -> trailview",
+ "cycle source-preparation -> map-reading",
+ "cycle trailview -> route-planning",
+ "dependency search -> device-map-builder",
+ "test dependency route-planning -> planner-map-baking",
+ "test dependency trailview -> device-map-builder"
+]
diff --git a/.cairn/config.json b/.cairn/config.json
index 93d8ab12cf..181b5769f4 100644
--- a/.cairn/config.json
+++ b/.cairn/config.json
@@ -1,15 +1,10 @@
{
"docs": "docs/design",
"baseline": ".cairn/baseline.json",
- "specs": "specs",
"leaf_lines": 4000,
"leaf_files": 60,
"skill": {"path": "tools/cairn/skill/cairn", "router_tokens": 2000, "reference_tokens": 2000},
"tests": ["**/tests/**", "tests.rs", "*_tests.rs", "*_test.py", "*Tests.swift", "*.test.ts"],
- "size": {
- "S": {"systems": 1, "lines": 500},
- "M": {"systems": 3, "lines": 1500}
- },
"sources": {
"extensions": [".rs", ".ts", ".svelte", ".py", ".swift", ".wgsl", ".js", ".mjs", ".sh", ".h", ".c"],
"files": ["tools/obc"]
@@ -17,19 +12,11 @@
"adapters": {
"cargo": {
"ignore": ["**/vendor/**"]
+ },
+ "imports": {
+ "extensions": [".ts", ".svelte", ".js", ".mjs"]
}
},
- "runtimes": {
- "firmware/": "device",
- "firmware/tools/": "host",
- "host/": "host",
- "planner/": "host",
- "sim/": "host",
- "tools/": "host",
- "builder/web/": "web",
- "builder/wasm/": "web",
- "companion-ios/": "ios"
- },
"tooling": {
"path": "tools/",
"area": "Tooling"
@@ -42,25 +29,10 @@
"code-review": { "tier": "strong", "effort": "high" },
"doc-peanut": { "tier": "balanced", "effort": "medium" },
"doc-hay": { "tier": "balanced", "effort": "medium" },
- "implementer": { "tier": "inherit" },
- "drift": { "tier": "balanced", "effort": "low" }
+ "implementer": { "tier": "inherit" }
},
"tiers": {
"claude-code": { "strong": "opus", "balanced": "sonnet", "fast": "haiku" },
- "api": { "strong": "claude-opus", "balanced": "claude-sonnet", "fast": "claude-haiku" },
"codex": { "strong": "gpt-6-astra", "balanced": "gpt-6.1-sol", "fast": "gpt-6-luna" }
- },
- "report": {
- "budget_usd": 5,
- "max_input_chars": 40000,
- "max_tokens": 8000,
- "timeout_minutes": 180,
- "ignore": ["*.lock", "package-lock.json", "*.svg", "*.webp", "*.bin", "*.raw", "*.step", "*.stp",
- "*.kicad_mod", "*.kicad_pcb", "*.kicad_sch", "*.gpx", "*.sha256"],
- "batch_prices": {
- "claude-opus-5-5": { "input": 2, "output": 10, "cache_read": 0.1 },
- "claude-sonnet-5-5": { "input": 1, "output": 5, "cache_read": 0.05 },
- "claude-haiku-5-5": { "input": 0.05, "output": 0.25, "cache_read": 0.005 }
- }
}
}
diff --git a/.claude/launch.json b/.claude/launch.json
index 49410ac402..adc89e47dd 100644
--- a/.claude/launch.json
+++ b/.claude/launch.json
@@ -21,13 +21,6 @@
"cwd": "builder/web",
"port": 5173
},
- {
- "name": "web-builder-desktop",
- "runtimeExecutable": "npm",
- "runtimeArgs": ["run", "dev", "--", "--mode", "desktop", "--port", "5173"],
- "cwd": "builder/web",
- "port": 5173
- },
{
"name": "data-page",
"runtimeExecutable": "tools/obc",
diff --git a/.github/workflows/bake.yml b/.github/workflows/bake.yml
index c16686dd6e..d590278a3c 100644
--- a/.github/workflows/bake.yml
+++ b/.github/workflows/bake.yml
@@ -1,7 +1,7 @@
name: Bake
-# Build catalog cells once, centrally, so the website and desktop app can select,
-# download, and assemble the same verified inputs.
+# Build catalog cells once, centrally, so the website can select, download, and
+# assemble the same verified inputs.
#
# ── READ THIS BEFORE ADDING A COUNTRY TO THE MATRIX ────────────────────────────────
#
diff --git a/.github/workflows/cairn-report.yml b/.github/workflows/cairn-report.yml
index 57e61a045b..c755bb74a4 100644
--- a/.github/workflows/cairn-report.yml
+++ b/.github/workflows/cairn-report.yml
@@ -1,7 +1,7 @@
name: cairn report
-# The weekly report on skipped pull requests, size estimates, the ratchet and drift. It replaces the body of the open issue
-# labelled cairn-report. Only this workflow's environment holds the Anthropic API key.
+# The weekly report on skipped pull requests, the ratchet and the approved system docs to check. It replaces the body of
+# the open issue labelled cairn-report.
on:
schedule:
@@ -20,13 +20,11 @@ permissions:
jobs:
report:
runs-on: ubuntu-24.04
- environment: cairn-report
- # The batch may take up to `report.timeout_minutes` in .cairn/config.json.
- timeout-minutes: 200
+ timeout-minutes: 10
steps:
- uses: actions/checkout@v4
with:
- # Step 1 reads the history since each approved doc last changed.
+ # The report reads the history since each approved doc last changed.
fetch-depth: 0
persist-credentials: false
# The Rust adapter reads `cargo metadata`; the report builds nothing.
@@ -37,5 +35,4 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
- ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
- run: python3 tools/cairn/cairn.py report --publish --drift
+ run: python3 tools/cairn/cairn.py report --publish
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 29b0a3ab13..caf936acda 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -21,12 +21,7 @@ name: CI
# board crate; its job adds a flash-size guard against the 32 KB slot.
# * obc-builder-bridge is a workspace library and the builder's shared WASM core.
# The wasm-bridges job gates its production size and hands the same bytes to frontend jobs.
-# * obc-desktop (#906) is the third excluded + standalone crate: a Tauri app, so it brings a
-# platform webview with it (WebKitGTK on Linux) and would otherwise put those headers in
-# every renderer test's way. The shell embeds the frontend, so both halves are built there.
-# The planner artifact verifier also needs the locked Node reader dependencies.
-# It is the only **three-OS matrix** in this file because it is the artifact a user installs.
-# * `--locked` everywhere so a stale Cargo.lock (any of the four) fails CI.
+# * `--locked` everywhere so a stale Cargo.lock (any of them) fails CI.
on:
workflow_call:
@@ -220,9 +215,6 @@ jobs:
echo "::group::obc-boot (workspace-excluded)"
cargo fmt --check --manifest-path firmware/obc-boot/Cargo.toml || rc=1
echo "::endgroup::"
- echo "::group::obc-desktop (workspace-excluded)"
- cargo fmt --check --manifest-path builder/desktop/Cargo.toml || rc=1
- echo "::endgroup::"
exit $rc
# Blocking clippy on the host workspace: -D warnings from day one (the baseline is clean).
@@ -689,10 +681,6 @@ jobs:
run: cargo deny --manifest-path firmware/obc-boot/Cargo.toml --all-features --config tools/licenses/deny.toml check
- name: cargo-deny (obc-sensor-sim)
run: cargo deny --manifest-path firmware/obc-sensor-sim/Cargo.toml --all-features --config tools/licenses/deny.toml check
- # The desktop shell is the one artifact a *user* installs, so its tree is the
- # one where a bad licence or a live advisory matters most.
- - name: cargo-deny (obc-desktop app)
- run: cargo deny --manifest-path builder/desktop/Cargo.toml --all-features --config tools/licenses/deny.toml check
# deny.toml skips the repository's own crates, so it cannot see obc-data reach one.
- name: obc-data depends on no GPL crate
run: python3 tools/check_obc_data_licence.py
@@ -1030,9 +1018,8 @@ jobs:
# The web builder's Svelte frontend: type-check, unit tests, production builds.
#
- # One source tree, three hosts (#895): `npm run build` is the local FastAPI one,
- # `build:web` the static hosted site and `build:desktop` the Tauri shell. All three
- # are built here — a host that stops compiling is otherwise invisible until someone
+ # One source tree, two hosts: `npm run build` is the local FastAPI one and
+ # `build:web` the static hosted site. Both are built here — a host that stops compiling is otherwise invisible until someone
# tries to ship it. The *contents* of the web bundle (no job polling, no style
# editor) are asserted by vitest, which builds and inspects the emitted chunks.
#
@@ -1063,8 +1050,7 @@ jobs:
with:
name: obc-ground-plan-bridge-pkg
path: builder/web/src/lib/trailview/plan/pkg
- # The device the USB suites run against. The desktop-frontend job does not download it: that
- # job only builds the shipped bundle, which must not contain this package at all.
+ # The device the USB suites run against. The shipped bundle must not contain this package.
- uses: actions/download-artifact@v4
with:
name: obc-flat-device-pkg
@@ -1082,7 +1068,7 @@ jobs:
run: |
rm -f "$RUNNER_TEMP/web-builder-junit.xml"
npm run test:components -- --reporter=default --reporter=junit --outputFile="$RUNNER_TEMP/web-builder-junit.xml"
- - name: production builds (dev + web + desktop hosts)
+ - name: production builds (dev + web hosts)
run: npm run build:all
# naga is the WGSL front end of Firefox; Chrome's Tint compiles the same files in the TrailView smoke.
- name: Cache the WGSL validator
@@ -1135,6 +1121,11 @@ jobs:
with:
name: obc-ground-plan-bridge-pkg
path: builder/web/src/lib/trailview/plan/pkg
+ # The planner build of the browser tests holds the pretend device of `?fake-device`.
+ - uses: actions/download-artifact@v4
+ with:
+ name: obc-flat-device-pkg
+ path: builder/web/test-support/flat-device/pkg
- uses: actions/setup-node@v4
with:
node-version: "22"
@@ -1171,149 +1162,6 @@ jobs:
path: .artifacts/web-builder/
if-no-files-found: error
- desktop-frontend:
- needs: [selection, wasm-bridges]
- if: contains(fromJSON(needs.selection.outputs.jobs), 'desktop-frontend')
- runs-on: ubuntu-24.04
- steps:
- - uses: actions/checkout@v4
- with:
- ref: ${{ inputs.source_sha || github.sha }}
- persist-credentials: false
- - uses: actions/download-artifact@v4
- with:
- name: obc-builder-bridge-pkg
- path: builder/web/src/lib/core/pkg
- - uses: actions/download-artifact@v4
- with:
- name: obc-ground-plan-bridge-pkg
- path: builder/web/src/lib/trailview/plan/pkg
- - uses: actions/setup-node@v4
- with:
- node-version: 22
- cache: npm
- cache-dependency-path: builder/web/package-lock.json
- - name: Build the desktop bundle
- working-directory: builder/web
- run: |
- npm ci
- npm run build:desktop
- - uses: actions/upload-artifact@v4
- with:
- name: obc-desktop-frontend
- path: builder/web/dist/desktop
- retention-days: 1
-
- desktop:
- needs: [selection, desktop-frontend]
- if: contains(fromJSON(needs.selection.outputs.jobs), 'desktop')
- runs-on: ${{ matrix.os }}
- env:
- # Baked into packaged apps; a runtime variable can still override it for a
- # maintainer testing an unpublished tree.
- OBC_CATALOG_URL: ${{ vars.OBC_CATALOG_URL }}
- strategy:
- # One platform's failure must not hide another's.
- fail-fast: false
- matrix:
- include:
- - os: ubuntu-24.04
- slug: linux-x86_64
- exe: obc-desktop
- - os: macos-latest
- slug: macos-arm64
- exe: obc-desktop
- - os: windows-latest
- slug: windows-x86_64-msvc
- exe: obc-desktop.exe
- defaults:
- run:
- # Git Bash on the Windows runner, so the shared steps below are one script
- # rather than three. Nothing here needs a Windows-native shell.
- shell: bash
- steps:
- - uses: actions/checkout@v4
- with:
- ref: ${{ inputs.source_sha || github.sha }}
- persist-credentials: false
- - uses: actions-rust-lang/setup-rust-toolchain@v1
- with:
- cache: false
- - uses: Swatinem/rust-cache@v2
- with:
- workspaces: builder/desktop
- key: desktop-${{ matrix.slug }}
- # wry's Linux backend. macOS and Windows need nothing extra — which is most of
- # why Tauri was chosen over Electron (#906) — but Linux wants WebKitGTK.
- - name: Install the Linux webview deps
- if: runner.os == 'Linux'
- uses: ./.github/actions/apt-install
- with:
- packages: libwebkit2gtk-4.1-dev libsoup-3.0-dev libjavascriptcoregtk-4.1-dev libgtk-3-dev librsvg2-dev
- # The bundle the shell embeds, built once on Linux by `desktop-frontend` and
- # unpacked here. It is byte-identical on all three runners — a Vite build of the
- # same sources — so building it per-platform was three runs of `npm ci` and
- # three Node toolchains for one output. Landing it at the path tauri.conf.json's
- # `frontendDist` names is the whole integration; nothing here runs npm, and the
- # `beforeBuildCommand` in that file is never executed (there is no Tauri CLI in
- # this repo — see the note above about `custom-protocol`).
- - uses: actions/download-artifact@v4
- with:
- name: obc-desktop-frontend
- path: builder/web/dist/desktop
- # Order matters. `cargo test` never produces the plain binary — even with
- # --all-targets it builds bins as *test harnesses*, a different artifact — so the
- # `build` below is a full codegen + link either way. Running it first means the
- # normal lib it produces is already there for `test` to link against, instead of
- # `test` building one set of artifacts and `build` starting a second.
- - name: "obc-desktop: clippy"
- working-directory: builder/desktop
- run: cargo clippy --release --all-targets --locked -- -D warnings
- - name: "obc-desktop: build (release)"
- working-directory: builder/desktop
- run: cargo build --release --locked
- - uses: taiki-e/install-action@v2
- with:
- tool: cargo-nextest@0.9.143
- - name: "obc-desktop: test"
- id: desktop-tests
- working-directory: builder/desktop
- env:
- NEXTEST_PROFILE: ci
- run: |
- rm -f target/nextest/ci/junit.xml
- cargo nextest run --release --locked --config-file ../../.config/nextest.toml --no-tests fail
- - name: Upload native desktop test results
- if: ${{ !cancelled() && (steps.desktop-tests.outcome == 'success' || steps.desktop-tests.outcome == 'failure') }}
- uses: actions/upload-artifact@v4
- with:
- name: desktop-tests-${{ matrix.slug }}-${{ github.run_attempt }}
- path: builder/desktop/target/nextest/ci/junit.xml
- if-no-files-found: error
- # Recorded so an accidental native dependency or bundling regression is visible.
- - name: "obc-desktop: record the artifact size"
- working-directory: builder/desktop
- run: |
- bytes=$(wc -c < "target/release/${{ matrix.exe }}")
- echo "| ${{ matrix.slug }} | $bytes bytes |" >> "$GITHUB_STEP_SUMMARY"
- - uses: actions/upload-artifact@v4
- with:
- name: obc-desktop-${{ matrix.slug }}
- path: builder/desktop/target/release/${{ matrix.exe }}
- retention-days: 7
- # macOS ships two architectures and this crate is built on the Apple-silicon
- # runner, so cross-build the Intel slice to keep a future universal bundle open.
- #
- # Push events only: a second target triple is build-only insurance, not a
- # correctness gate on the app anyone runs.
- - name: "obc-desktop: the macOS Intel slice (build-only)"
- if: runner.os == 'macOS' && github.event_name == 'push'
- working-directory: builder/desktop
- run: |
- rustup target add x86_64-apple-darwin
- cargo build --release --locked --target x86_64-apple-darwin
- file target/x86_64-apple-darwin/release/obc-desktop
-
planner-search:
needs: selection
if: contains(fromJSON(needs.selection.outputs.jobs), 'planner-search')
@@ -1375,7 +1223,7 @@ jobs:
# publishes no plan, which fails this gate rather than silently passing.
ci:
if: always()
- needs: [selection, guards, cairn, fmt, clippy, test, ui-snapshots, builder-python, embedded, boot, device, deny, wasm, wasm-bridges, docs, ios-unit, ios-app, ios-release, web, web-browser, desktop-frontend, desktop, verification, planner-search]
+ needs: [selection, guards, cairn, fmt, clippy, test, ui-snapshots, builder-python, embedded, boot, device, deny, wasm, wasm-bridges, docs, ios-unit, ios-app, ios-release, web, web-browser, verification, planner-search]
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml
index 683eabdf7c..166cdd885d 100644
--- a/.github/workflows/deploy-site.yml
+++ b/.github/workflows/deploy-site.yml
@@ -156,8 +156,8 @@ jobs:
# VITE_SITE_BASE makes the builder's links to the docs and the landing relative:
# they are siblings inside this artifact, so naming them by absolute URL would be
- # the one place a domain move still bit us. Left unset everywhere else (dev
- # server, desktop app), where the site genuinely is somewhere else.
+ # the one place a domain move still bit us. Left unset everywhere else (the dev
+ # server), where the site genuinely is somewhere else.
- name: Build the static map builder
working-directory: builder/web
env:
diff --git a/.gitignore b/.gitignore
index e5373e6d3f..05a1dc13dc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -72,14 +72,13 @@ builder/web/src/lib/trailview/plan/pkg/
# virtualenv + the optional local maps drop. The tooling itself (everything in
# tools/ except obc.local) is committed.
tools/obc.local
-# Planner tile settings for a local desktop build (see builder/desktop/README.md).
+# Local Vite settings of the web builder.
builder/web/.env.local
.venv/
/maps/
# Web builder frontend: dependencies + the Vite build output (CI builds it).
# The dev host builds into builder/server/static/dist/ (what the FastAPI server
-# mounts); the static-web and desktop hosts into builder/web/dist// — see
-# #895. Both entries must keep matching vite.config.ts's outDirs: when they
+# mounts); the static-web host into builder/web/dist/web/. Both entries must keep matching vite.config.ts's outDirs: when they
# drifted apart, `npm run build` wrote to an unignored path and 640 KB of bundle
# got committed by accident (and the server mounted nothing).
node_modules/
diff --git a/AGENTS.md b/AGENTS.md
index e39e01518b..b894ea03a4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -19,7 +19,7 @@ The goal for this codebase is to make this a robust and extendable open source m
The layout table is in [README.md](README.md#repository-layout). The root Cargo workspace lists
its crates in `Cargo.toml`. Keep device-reachable dependencies in `firmware/`.
-The nRF54L board image, the bootloader, the Tauri desktop app and the sensor simulator are standalone Cargo roots; build
+The nRF54L board image, the bootloader and the sensor simulator are standalone Cargo roots; build
and test them from their own directories. The nearest README has the surface's setup;
`companion-ios/README.md` is the iOS on-ramp.
diff --git a/Cargo.lock b/Cargo.lock
index 1ab57cc9fd..44103dfbb3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3703,6 +3703,7 @@ dependencies = [
"js-sys",
"obc-bake",
"obc-draw",
+ "obc-fit",
"obc-flat-device",
"obc-formats",
"obc-host-core",
@@ -3853,6 +3854,10 @@ dependencies = [
"obcm-testkit",
]
+[[package]]
+name = "obc-fit"
+version = "0.1.0"
+
[[package]]
name = "obc-fixtures"
version = "0.1.0"
@@ -4157,6 +4162,7 @@ dependencies = [
"obc-ports",
"obc-reader",
"obcm-testkit",
+ "serde_json",
]
[[package]]
@@ -4258,7 +4264,6 @@ dependencies = [
"nusb",
"obc-flat-device",
"obc-link",
- "serde",
"tokio",
]
@@ -4954,6 +4959,7 @@ dependencies = [
"osmpbfreader",
"planner-router",
"postcard",
+ "rayon",
"rusqlite",
"serde_json",
"sha2 0.10.9",
diff --git a/Cargo.toml b/Cargo.toml
index f5afa4009c..e5229db09a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -25,6 +25,7 @@ members = [
"planner/router",
"planner/router-build",
"host/obc-file-source",
+ "host/obc-fit",
"host/obc-inspect",
"host/obc-fixtures",
"host/obc-pack",
@@ -56,14 +57,14 @@ members = [
"sim/phone/host",
"sim/desktop",
"sim/web-demo",
- # Product bridges. obc-desktop carries its own [workspace].
+ # Product bridges.
"planner/service",
"builder/wasm",
"builder/ground-plan-wasm",
]
# obc-fw-nrf54l is a standalone board crate (own target + .cargo/config.toml, own empty
# [workspace]); it's built on its own, not as part of this host workspace (which builds its
-# members for the host target). obc-boot, obc-desktop and obc-sensor-sim carry their own
+# members for the host target). obc-boot and obc-sensor-sim carry their own
# [workspace] tables, which excludes them automatically for the same reason.
exclude = ["firmware/obc-fw-nrf54l"]
resolver = "2"
@@ -97,6 +98,7 @@ obc-app = { path = "firmware/obc-app" }
obc-dem = { path = "host/obc-dem", default-features = false }
obc-dfu = { path = "firmware/obc-dfu" }
obc-file-source = { path = "host/obc-file-source" }
+obc-fit = { path = "host/obc-fit" }
obc-host-core = { path = "sim/host-core" }
obc-places = { path = "host/obc-places" }
obc-platform = { path = "firmware/obc-platform" }
diff --git a/README.md b/README.md
index 2213d4cbac..edc216081d 100644
--- a/README.md
+++ b/README.md
@@ -149,7 +149,7 @@ over BLE and USB. The custom PCB and enclosure are still under development. KiCa
| `host/` | Host tools, map bakers, fixtures, and test support |
| `planner/` | Router, build tools, service, search, and tile worker |
| `sim/` | Desktop, web and phone simulators, host core, replay, feeder and benchmarks |
-| `builder/` | Web and desktop builder, Rust/WASM core, USB transport, presets, and server |
+| `builder/` | Web builder, Rust/WASM core, USB transport, presets, and server |
| `companion-ios/` | SwiftUI companion app and shared iOS package |
| `specs/` | Normative binary, wire, and vector contracts |
| `fixtures/` | Scenario registry, source provenance, and fixture builders |
@@ -159,7 +159,7 @@ over BLE and USB. The custom PCB and enclosure are still under development. KiCa
| `tools/` | The `obc` command, repository tools, and verification console |
`Cargo.toml` lists the root workspace crates. The nRF54L board image,
-bootloader, Tauri desktop app, and sensor simulator are standalone Cargo roots. The
+bootloader, and sensor simulator are standalone Cargo roots. The
[architecture guide](https://openbikecomputer.com/docs/software/architecture/) explains the boundaries.
## Other open bike computers
diff --git a/builder/__init__.py b/builder/__init__.py
index 3f67f2b2d7..51a0a53899 100644
--- a/builder/__init__.py
+++ b/builder/__init__.py
@@ -1,8 +1,8 @@
"""The map builder.
-`app/` is the Svelte UI, shared by all three of its hosts — the static web
-tier, the Tauri desktop app, and the FastAPI dev server in `server/` (see
-`app/vite.config.ts`: one frontend, three hosts). None of them packs anything
+`app/` is the Svelte UI, shared by its two hosts — the static web tier and
+the FastAPI dev server in `server/` (see `app/vite.config.ts`: one frontend,
+two hosts). None of them packs anything
itself: they drive the native `obc-pack` packer (`host/obc-pack`) to build
OpenStreetMap extracts into `.obcm` maps for the OBC firmware.
diff --git a/builder/desktop/.gitignore b/builder/desktop/.gitignore
deleted file mode 100644
index f4a858a832..0000000000
--- a/builder/desktop/.gitignore
+++ /dev/null
@@ -1,5 +0,0 @@
-# `tauri-build` regenerates these from tauri.conf.json + capabilities/ on every
-# build. They are IDE aids (the `$schema` in capabilities/default.json points at
-# one), derived from committed inputs, and platform-specific — so committing them
-# would mean a diff every time someone builds on a different OS.
-/gen/
diff --git a/builder/desktop/Cargo.lock b/builder/desktop/Cargo.lock
deleted file mode 100644
index 6ff8b998aa..0000000000
--- a/builder/desktop/Cargo.lock
+++ /dev/null
@@ -1,5240 +0,0 @@
-# This file is automatically @generated by Cargo.
-# It is not intended for manual editing.
-version = 4
-
-[[package]]
-name = "adler2"
-version = "2.0.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
-
-[[package]]
-name = "aho-corasick"
-version = "1.1.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
-dependencies = [
- "memchr",
-]
-
-[[package]]
-name = "alloc-no-stdlib"
-version = "2.0.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
-
-[[package]]
-name = "alloc-stdlib"
-version = "0.2.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
-dependencies = [
- "alloc-no-stdlib",
-]
-
-[[package]]
-name = "android_system_properties"
-version = "0.1.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
-dependencies = [
- "libc",
-]
-
-[[package]]
-name = "anyhow"
-version = "1.0.104"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
-
-[[package]]
-name = "async-broadcast"
-version = "0.7.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
-dependencies = [
- "event-listener",
- "event-listener-strategy",
- "futures-core",
- "pin-project-lite",
-]
-
-[[package]]
-name = "async-channel"
-version = "2.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
-dependencies = [
- "concurrent-queue",
- "event-listener-strategy",
- "futures-core",
- "pin-project-lite",
-]
-
-[[package]]
-name = "async-executor"
-version = "1.14.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
-dependencies = [
- "async-task",
- "concurrent-queue",
- "fastrand",
- "futures-lite",
- "pin-project-lite",
- "slab",
-]
-
-[[package]]
-name = "async-io"
-version = "2.6.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"
-dependencies = [
- "autocfg",
- "cfg-if",
- "concurrent-queue",
- "futures-io",
- "futures-lite",
- "parking",
- "polling",
- "rustix",
- "slab",
- "windows-sys 0.61.2",
-]
-
-[[package]]
-name = "async-lock"
-version = "3.4.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
-dependencies = [
- "event-listener",
- "event-listener-strategy",
- "pin-project-lite",
-]
-
-[[package]]
-name = "async-process"
-version = "2.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"
-dependencies = [
- "async-channel",
- "async-io",
- "async-lock",
- "async-signal",
- "async-task",
- "blocking",
- "cfg-if",
- "event-listener",
- "futures-lite",
- "rustix",
-]
-
-[[package]]
-name = "async-recursion"
-version = "1.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "async-signal"
-version = "0.2.14"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"
-dependencies = [
- "async-io",
- "async-lock",
- "atomic-waker",
- "cfg-if",
- "futures-core",
- "futures-io",
- "rustix",
- "signal-hook-registry",
- "slab",
- "windows-sys 0.61.2",
-]
-
-[[package]]
-name = "async-task"
-version = "4.7.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
-
-[[package]]
-name = "async-trait"
-version = "0.1.91"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ae36dc4177970ef04fde5178d3e2429882def40e57a451f919c098f72baa6cec"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 3.0.3",
-]
-
-[[package]]
-name = "atk"
-version = "0.18.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b"
-dependencies = [
- "atk-sys",
- "glib",
- "libc",
-]
-
-[[package]]
-name = "atk-sys"
-version = "0.18.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086"
-dependencies = [
- "glib-sys",
- "gobject-sys",
- "libc",
- "system-deps",
-]
-
-[[package]]
-name = "atomic-waker"
-version = "1.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
-
-[[package]]
-name = "autocfg"
-version = "1.5.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
-
-[[package]]
-name = "base64"
-version = "0.21.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
-
-[[package]]
-name = "base64"
-version = "0.22.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
-
-[[package]]
-name = "bit-set"
-version = "0.8.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
-dependencies = [
- "bit-vec",
-]
-
-[[package]]
-name = "bit-vec"
-version = "0.8.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
-
-[[package]]
-name = "bitflags"
-version = "1.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
-
-[[package]]
-name = "bitflags"
-version = "2.13.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
-dependencies = [
- "serde_core",
-]
-
-[[package]]
-name = "block-buffer"
-version = "0.10.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
-dependencies = [
- "generic-array",
-]
-
-[[package]]
-name = "block2"
-version = "0.6.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
-dependencies = [
- "objc2",
-]
-
-[[package]]
-name = "blocking"
-version = "1.6.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21"
-dependencies = [
- "async-channel",
- "async-task",
- "futures-io",
- "futures-lite",
- "piper",
-]
-
-[[package]]
-name = "brotli"
-version = "8.0.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
-dependencies = [
- "alloc-no-stdlib",
- "alloc-stdlib",
- "brotli-decompressor",
-]
-
-[[package]]
-name = "brotli-decompressor"
-version = "5.0.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
-dependencies = [
- "alloc-no-stdlib",
- "alloc-stdlib",
-]
-
-[[package]]
-name = "bs58"
-version = "0.5.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4"
-dependencies = [
- "tinyvec",
-]
-
-[[package]]
-name = "bumpalo"
-version = "3.20.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
-
-[[package]]
-name = "bytemuck"
-version = "1.25.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
-
-[[package]]
-name = "byteorder"
-version = "1.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
-
-[[package]]
-name = "bytes"
-version = "1.12.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
-dependencies = [
- "serde",
-]
-
-[[package]]
-name = "cairo-rs"
-version = "0.18.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2"
-dependencies = [
- "bitflags 2.13.1",
- "cairo-sys-rs",
- "glib",
- "libc",
- "once_cell",
- "thiserror 1.0.69",
-]
-
-[[package]]
-name = "cairo-sys-rs"
-version = "0.18.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51"
-dependencies = [
- "glib-sys",
- "libc",
- "system-deps",
-]
-
-[[package]]
-name = "camino"
-version = "1.2.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5f2d30e4173c4026932d51d31d6b0613b1fd3014bf3f9f8943d4ba139c437ba0"
-dependencies = [
- "serde_core",
-]
-
-[[package]]
-name = "cargo-platform"
-version = "0.1.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea"
-dependencies = [
- "serde",
-]
-
-[[package]]
-name = "cargo_metadata"
-version = "0.19.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba"
-dependencies = [
- "camino",
- "cargo-platform",
- "semver",
- "serde",
- "serde_json",
- "thiserror 2.0.19",
-]
-
-[[package]]
-name = "cargo_toml"
-version = "0.22.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "374b7c592d9c00c1f4972ea58390ac6b18cbb6ab79011f3bdc90a0b82ca06b77"
-dependencies = [
- "serde",
- "toml 0.9.12+spec-1.1.0",
-]
-
-[[package]]
-name = "cc"
-version = "1.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5add81bb678e6cb321aff7fa0dc7689ad82b112dbc032cea19f91d6b8e3582b9"
-dependencies = [
- "find-msvc-tools",
- "shlex",
-]
-
-[[package]]
-name = "cesu8"
-version = "1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
-
-[[package]]
-name = "cfb"
-version = "0.7.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f"
-dependencies = [
- "byteorder",
- "fnv",
- "uuid",
-]
-
-[[package]]
-name = "cfg-expr"
-version = "0.15.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02"
-dependencies = [
- "smallvec",
- "target-lexicon",
-]
-
-[[package]]
-name = "cfg-if"
-version = "1.0.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
-
-[[package]]
-name = "chrono"
-version = "0.4.45"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
-dependencies = [
- "iana-time-zone",
- "num-traits",
- "serde",
- "windows-link 0.2.1",
-]
-
-[[package]]
-name = "combine"
-version = "4.6.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"
-dependencies = [
- "bytes",
- "memchr",
-]
-
-[[package]]
-name = "concurrent-queue"
-version = "2.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
-dependencies = [
- "crossbeam-utils",
-]
-
-[[package]]
-name = "cookie"
-version = "0.18.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747"
-dependencies = [
- "time",
- "version_check",
-]
-
-[[package]]
-name = "core-foundation"
-version = "0.10.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
-dependencies = [
- "core-foundation-sys",
- "libc",
-]
-
-[[package]]
-name = "core-foundation-sys"
-version = "0.8.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
-
-[[package]]
-name = "core-graphics"
-version = "0.25.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97"
-dependencies = [
- "bitflags 2.13.1",
- "core-foundation",
- "core-graphics-types",
- "foreign-types",
- "libc",
-]
-
-[[package]]
-name = "core-graphics-types"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"
-dependencies = [
- "bitflags 2.13.1",
- "core-foundation",
- "libc",
-]
-
-[[package]]
-name = "cpufeatures"
-version = "0.2.17"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
-dependencies = [
- "libc",
-]
-
-[[package]]
-name = "crc32fast"
-version = "1.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
-dependencies = [
- "cfg-if",
-]
-
-[[package]]
-name = "crossbeam-channel"
-version = "0.5.16"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d85363c37faeca707aef026efa9f3b34d077bce547e48f770770625c6013679e"
-dependencies = [
- "crossbeam-utils",
-]
-
-[[package]]
-name = "crossbeam-utils"
-version = "0.8.22"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
-
-[[package]]
-name = "crypto-common"
-version = "0.1.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
-dependencies = [
- "generic-array",
- "typenum",
-]
-
-[[package]]
-name = "cssparser"
-version = "0.36.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dae61cf9c0abb83bd659dab65b7e4e38d8236824c85f0f804f173567bda257d2"
-dependencies = [
- "cssparser-macros",
- "dtoa-short",
- "itoa",
- "phf",
- "smallvec",
-]
-
-[[package]]
-name = "cssparser-macros"
-version = "0.6.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331"
-dependencies = [
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "ctor"
-version = "0.8.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "352d39c2f7bef1d6ad73db6f5160efcaed66d94ef8c6c573a8410c00bf909a98"
-dependencies = [
- "ctor-proc-macro",
- "dtor",
-]
-
-[[package]]
-name = "ctor-proc-macro"
-version = "0.0.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1"
-
-[[package]]
-name = "darling"
-version = "0.23.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d"
-dependencies = [
- "darling_core",
- "darling_macro",
-]
-
-[[package]]
-name = "darling_core"
-version = "0.23.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0"
-dependencies = [
- "ident_case",
- "proc-macro2",
- "quote",
- "strsim",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "darling_macro"
-version = "0.23.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d"
-dependencies = [
- "darling_core",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "dbus"
-version = "0.9.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e"
-dependencies = [
- "libc",
- "libdbus-sys",
- "windows-sys 0.61.2",
-]
-
-[[package]]
-name = "deranged"
-version = "0.5.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
-dependencies = [
- "serde_core",
-]
-
-[[package]]
-name = "derive_more"
-version = "2.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
-dependencies = [
- "derive_more-impl",
-]
-
-[[package]]
-name = "derive_more-impl"
-version = "2.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
-dependencies = [
- "proc-macro2",
- "quote",
- "rustc_version",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "digest"
-version = "0.10.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
-dependencies = [
- "block-buffer",
- "crypto-common",
-]
-
-[[package]]
-name = "dirs"
-version = "6.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
-dependencies = [
- "dirs-sys",
-]
-
-[[package]]
-name = "dirs-sys"
-version = "0.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
-dependencies = [
- "libc",
- "option-ext",
- "redox_users",
- "windows-sys 0.59.0",
-]
-
-[[package]]
-name = "dispatch2"
-version = "0.3.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
-dependencies = [
- "bitflags 2.13.1",
- "block2",
- "libc",
- "objc2",
-]
-
-[[package]]
-name = "displaydoc"
-version = "0.2.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "dlopen2"
-version = "0.8.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5e2c5bd4158e66d1e215c49b837e11d62f3267b30c92f1d171c4d3105e3dc4d4"
-dependencies = [
- "dlopen2_derive",
- "libc",
- "once_cell",
- "winapi",
-]
-
-[[package]]
-name = "dlopen2_derive"
-version = "0.4.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0fbbb781877580993a8707ec48672673ec7b81eeba04cfd2310bd28c08e47c8f"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "dom_query"
-version = "0.27.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "521e380c0c8afb8d9a1e83a1822ee03556fc3e3e7dbc1fd30be14e37f9cb3f89"
-dependencies = [
- "bit-set",
- "cssparser",
- "foldhash",
- "html5ever",
- "precomputed-hash",
- "selectors",
- "tendril",
-]
-
-[[package]]
-name = "dpi"
-version = "0.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
-dependencies = [
- "serde",
-]
-
-[[package]]
-name = "dtoa"
-version = "1.0.11"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590"
-
-[[package]]
-name = "dtoa-short"
-version = "0.3.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87"
-dependencies = [
- "dtoa",
-]
-
-[[package]]
-name = "dtor"
-version = "0.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f1057d6c64987086ff8ed0fd3fbf377a6b7d205cc7715868cd401705f715cbe4"
-dependencies = [
- "dtor-proc-macro",
-]
-
-[[package]]
-name = "dtor-proc-macro"
-version = "0.0.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f678cf4a922c215c63e0de95eb1ff08a958a81d47e485cf9da1e27bf6305cfa5"
-
-[[package]]
-name = "dunce"
-version = "1.0.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
-
-[[package]]
-name = "dyn-clone"
-version = "1.0.20"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
-
-[[package]]
-name = "embed-resource"
-version = "3.0.11"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fbfdaacccebec3b28e4866b8973543c7647797db5ada1bdab552e48fe665fbbd"
-dependencies = [
- "cc",
- "memchr",
- "rustc_version",
- "toml 1.1.3+spec-1.1.0",
- "vswhom",
- "winreg",
-]
-
-[[package]]
-name = "embed_plist"
-version = "1.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"
-
-[[package]]
-name = "endi"
-version = "1.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
-
-[[package]]
-name = "enumflags2"
-version = "0.7.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"
-dependencies = [
- "enumflags2_derive",
- "serde",
-]
-
-[[package]]
-name = "enumflags2_derive"
-version = "0.7.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "equivalent"
-version = "1.0.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
-
-[[package]]
-name = "erased-serde"
-version = "0.4.10"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
-dependencies = [
- "serde",
- "serde_core",
- "typeid",
-]
-
-[[package]]
-name = "errno"
-version = "0.3.14"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
-dependencies = [
- "libc",
- "windows-sys 0.52.0",
-]
-
-[[package]]
-name = "event-listener"
-version = "5.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab"
-dependencies = [
- "concurrent-queue",
- "parking",
- "pin-project-lite",
-]
-
-[[package]]
-name = "event-listener-strategy"
-version = "0.5.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
-dependencies = [
- "event-listener",
- "pin-project-lite",
-]
-
-[[package]]
-name = "fastrand"
-version = "2.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
-
-[[package]]
-name = "fdeflate"
-version = "0.3.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
-dependencies = [
- "simd-adler32",
-]
-
-[[package]]
-name = "field-offset"
-version = "0.3.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f"
-dependencies = [
- "memoffset",
- "rustc_version",
-]
-
-[[package]]
-name = "find-msvc-tools"
-version = "0.1.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
-
-[[package]]
-name = "flate2"
-version = "1.1.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
-dependencies = [
- "crc32fast",
- "miniz_oxide",
-]
-
-[[package]]
-name = "fnv"
-version = "1.0.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
-
-[[package]]
-name = "foldhash"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
-
-[[package]]
-name = "foreign-types"
-version = "0.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"
-dependencies = [
- "foreign-types-macros",
- "foreign-types-shared",
-]
-
-[[package]]
-name = "foreign-types-macros"
-version = "0.2.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 3.0.3",
-]
-
-[[package]]
-name = "foreign-types-shared"
-version = "0.3.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
-
-[[package]]
-name = "form_urlencoded"
-version = "1.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
-dependencies = [
- "percent-encoding",
-]
-
-[[package]]
-name = "futures-channel"
-version = "0.3.33"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "262590f4fe6afeb0bc83be1daa64e52657fe185690a958af7f3ad0e92085c5ae"
-dependencies = [
- "futures-core",
-]
-
-[[package]]
-name = "futures-core"
-version = "0.3.33"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7"
-
-[[package]]
-name = "futures-executor"
-version = "0.3.33"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6754879cc9f2c66f88c6e5c35344bb0bdb0708b0352b1201815667c7eabc7458"
-dependencies = [
- "futures-core",
- "futures-task",
- "futures-util",
-]
-
-[[package]]
-name = "futures-io"
-version = "0.3.33"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4577ecaa3c4f96589d473f679a71b596316f6641bc350038b962a5daf0085d7a"
-
-[[package]]
-name = "futures-lite"
-version = "2.6.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"
-dependencies = [
- "fastrand",
- "futures-core",
- "futures-io",
- "parking",
- "pin-project-lite",
-]
-
-[[package]]
-name = "futures-macro"
-version = "0.3.33"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2d6d3cde68c518367be28956066ddfef33813991b77a55005a69dae04bf3b10b"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "futures-sink"
-version = "0.3.33"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e34418ac499d6305c2fb5ad0ed2f6ac998c5f8ca209b4510f7f94242c647e307"
-
-[[package]]
-name = "futures-task"
-version = "0.3.33"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109"
-
-[[package]]
-name = "futures-util"
-version = "0.3.33"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa"
-dependencies = [
- "futures-core",
- "futures-io",
- "futures-macro",
- "futures-sink",
- "futures-task",
- "memchr",
- "pin-project-lite",
- "slab",
-]
-
-[[package]]
-name = "gdk"
-version = "0.18.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691"
-dependencies = [
- "cairo-rs",
- "gdk-pixbuf",
- "gdk-sys",
- "gio",
- "glib",
- "libc",
- "pango",
-]
-
-[[package]]
-name = "gdk-pixbuf"
-version = "0.18.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec"
-dependencies = [
- "gdk-pixbuf-sys",
- "gio",
- "glib",
- "libc",
- "once_cell",
-]
-
-[[package]]
-name = "gdk-pixbuf-sys"
-version = "0.18.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7"
-dependencies = [
- "gio-sys",
- "glib-sys",
- "gobject-sys",
- "libc",
- "system-deps",
-]
-
-[[package]]
-name = "gdk-sys"
-version = "0.18.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7"
-dependencies = [
- "cairo-sys-rs",
- "gdk-pixbuf-sys",
- "gio-sys",
- "glib-sys",
- "gobject-sys",
- "libc",
- "pango-sys",
- "pkg-config",
- "system-deps",
-]
-
-[[package]]
-name = "gdkwayland-sys"
-version = "0.18.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69"
-dependencies = [
- "gdk-sys",
- "glib-sys",
- "gobject-sys",
- "libc",
- "pkg-config",
- "system-deps",
-]
-
-[[package]]
-name = "gdkx11"
-version = "0.18.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3caa00e14351bebbc8183b3c36690327eb77c49abc2268dd4bd36b856db3fbfe"
-dependencies = [
- "gdk",
- "gdkx11-sys",
- "gio",
- "glib",
- "libc",
- "x11",
-]
-
-[[package]]
-name = "gdkx11-sys"
-version = "0.18.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d"
-dependencies = [
- "gdk-sys",
- "glib-sys",
- "libc",
- "system-deps",
- "x11",
-]
-
-[[package]]
-name = "generic-array"
-version = "0.14.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
-dependencies = [
- "typenum",
- "version_check",
-]
-
-[[package]]
-name = "getrandom"
-version = "0.2.17"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
-dependencies = [
- "cfg-if",
- "libc",
- "wasi",
-]
-
-[[package]]
-name = "getrandom"
-version = "0.3.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
-dependencies = [
- "cfg-if",
- "libc",
- "r-efi 5.3.0",
- "wasip2",
-]
-
-[[package]]
-name = "getrandom"
-version = "0.4.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
-dependencies = [
- "cfg-if",
- "libc",
- "r-efi 6.0.0",
-]
-
-[[package]]
-name = "gio"
-version = "0.18.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73"
-dependencies = [
- "futures-channel",
- "futures-core",
- "futures-io",
- "futures-util",
- "gio-sys",
- "glib",
- "libc",
- "once_cell",
- "pin-project-lite",
- "smallvec",
- "thiserror 1.0.69",
-]
-
-[[package]]
-name = "gio-sys"
-version = "0.18.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2"
-dependencies = [
- "glib-sys",
- "gobject-sys",
- "libc",
- "system-deps",
- "winapi",
-]
-
-[[package]]
-name = "glib"
-version = "0.18.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5"
-dependencies = [
- "bitflags 2.13.1",
- "futures-channel",
- "futures-core",
- "futures-executor",
- "futures-task",
- "futures-util",
- "gio-sys",
- "glib-macros",
- "glib-sys",
- "gobject-sys",
- "libc",
- "memchr",
- "once_cell",
- "smallvec",
- "thiserror 1.0.69",
-]
-
-[[package]]
-name = "glib-macros"
-version = "0.18.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc"
-dependencies = [
- "heck 0.4.1",
- "proc-macro-crate 2.0.2",
- "proc-macro-error",
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "glib-sys"
-version = "0.18.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898"
-dependencies = [
- "libc",
- "system-deps",
-]
-
-[[package]]
-name = "glob"
-version = "0.3.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
-
-[[package]]
-name = "gobject-sys"
-version = "0.18.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44"
-dependencies = [
- "glib-sys",
- "libc",
- "system-deps",
-]
-
-[[package]]
-name = "gtk"
-version = "0.18.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a"
-dependencies = [
- "atk",
- "cairo-rs",
- "field-offset",
- "futures-channel",
- "gdk",
- "gdk-pixbuf",
- "gio",
- "glib",
- "gtk-sys",
- "gtk3-macros",
- "libc",
- "pango",
- "pkg-config",
-]
-
-[[package]]
-name = "gtk-sys"
-version = "0.18.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414"
-dependencies = [
- "atk-sys",
- "cairo-sys-rs",
- "gdk-pixbuf-sys",
- "gdk-sys",
- "gio-sys",
- "glib-sys",
- "gobject-sys",
- "libc",
- "pango-sys",
- "system-deps",
-]
-
-[[package]]
-name = "gtk3-macros"
-version = "0.18.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d"
-dependencies = [
- "proc-macro-crate 1.3.1",
- "proc-macro-error",
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "hashbrown"
-version = "0.12.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
-
-[[package]]
-name = "hashbrown"
-version = "0.17.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
-
-[[package]]
-name = "heck"
-version = "0.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
-
-[[package]]
-name = "heck"
-version = "0.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
-
-[[package]]
-name = "hermit-abi"
-version = "0.5.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
-
-[[package]]
-name = "hex"
-version = "0.4.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
-
-[[package]]
-name = "html5ever"
-version = "0.38.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1054432bae2f14e0061e33d23402fbaa67a921d319d56adc6bcf887ddad1cbc2"
-dependencies = [
- "log",
- "markup5ever",
-]
-
-[[package]]
-name = "http"
-version = "1.4.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425"
-dependencies = [
- "bytes",
- "itoa",
-]
-
-[[package]]
-name = "http-body"
-version = "1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
-dependencies = [
- "bytes",
- "http",
-]
-
-[[package]]
-name = "http-body-util"
-version = "0.1.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e9f41fd6a08e4d4ec69df65976da761afd5ad5e58a9d4acb46bd1c953a9e3ff2"
-dependencies = [
- "bytes",
- "futures-core",
- "http",
- "http-body",
- "pin-project-lite",
-]
-
-[[package]]
-name = "httparse"
-version = "1.10.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
-
-[[package]]
-name = "hyper"
-version = "1.11.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d22053281f852e11534f5198498373cbb59295120a20771d90f7ed1897490a72"
-dependencies = [
- "atomic-waker",
- "bytes",
- "futures-channel",
- "futures-core",
- "http",
- "http-body",
- "httparse",
- "itoa",
- "pin-project-lite",
- "smallvec",
- "tokio",
- "want",
-]
-
-[[package]]
-name = "hyper-util"
-version = "0.1.20"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
-dependencies = [
- "base64 0.22.1",
- "bytes",
- "futures-channel",
- "futures-util",
- "http",
- "http-body",
- "hyper",
- "ipnet",
- "libc",
- "percent-encoding",
- "pin-project-lite",
- "socket2",
- "tokio",
- "tower-service",
- "tracing",
-]
-
-[[package]]
-name = "iana-time-zone"
-version = "0.1.65"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
-dependencies = [
- "android_system_properties",
- "core-foundation-sys",
- "iana-time-zone-haiku",
- "js-sys",
- "log",
- "wasm-bindgen",
- "windows-core 0.62.2",
-]
-
-[[package]]
-name = "iana-time-zone-haiku"
-version = "0.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
-dependencies = [
- "cc",
-]
-
-[[package]]
-name = "ico"
-version = "0.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3e795dff5605e0f04bff85ca41b51a96b83e80b281e96231bcaaf1ac35103371"
-dependencies = [
- "byteorder",
- "png 0.17.16",
-]
-
-[[package]]
-name = "icu_collections"
-version = "2.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c"
-dependencies = [
- "displaydoc",
- "potential_utf",
- "utf8_iter",
- "yoke",
- "zerofrom",
- "zerovec",
-]
-
-[[package]]
-name = "icu_locale_core"
-version = "2.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29"
-dependencies = [
- "displaydoc",
- "litemap",
- "tinystr",
- "writeable",
- "zerovec",
-]
-
-[[package]]
-name = "icu_normalizer"
-version = "2.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4"
-dependencies = [
- "icu_collections",
- "icu_normalizer_data",
- "icu_properties",
- "icu_provider",
- "smallvec",
- "zerovec",
-]
-
-[[package]]
-name = "icu_normalizer_data"
-version = "2.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38"
-
-[[package]]
-name = "icu_properties"
-version = "2.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de"
-dependencies = [
- "icu_collections",
- "icu_locale_core",
- "icu_properties_data",
- "icu_provider",
- "zerotrie",
- "zerovec",
-]
-
-[[package]]
-name = "icu_properties_data"
-version = "2.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14"
-
-[[package]]
-name = "icu_provider"
-version = "2.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421"
-dependencies = [
- "displaydoc",
- "icu_locale_core",
- "writeable",
- "yoke",
- "zerofrom",
- "zerotrie",
- "zerovec",
-]
-
-[[package]]
-name = "ident_case"
-version = "1.0.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
-
-[[package]]
-name = "idna"
-version = "1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
-dependencies = [
- "idna_adapter",
- "smallvec",
- "utf8_iter",
-]
-
-[[package]]
-name = "idna_adapter"
-version = "1.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
-dependencies = [
- "icu_normalizer",
- "icu_properties",
-]
-
-[[package]]
-name = "indexmap"
-version = "1.9.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"
-dependencies = [
- "autocfg",
- "hashbrown 0.12.3",
- "serde",
-]
-
-[[package]]
-name = "indexmap"
-version = "2.14.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
-dependencies = [
- "equivalent",
- "hashbrown 0.17.1",
- "serde",
- "serde_core",
-]
-
-[[package]]
-name = "infer"
-version = "0.19.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a588916bfdfd92e71cacef98a63d9b1f0d74d6599980d11894290e7ddefffcf7"
-dependencies = [
- "cfb",
-]
-
-[[package]]
-name = "io-kit-sys"
-version = "0.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "06d3a048d09fbb6597dbf7c69f40d14df4a49487db1487191618c893fc3b1c26"
-dependencies = [
- "core-foundation-sys",
- "mach2",
-]
-
-[[package]]
-name = "ipnet"
-version = "2.12.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"
-
-[[package]]
-name = "is-docker"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3"
-dependencies = [
- "once_cell",
-]
-
-[[package]]
-name = "is-wsl"
-version = "0.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5"
-dependencies = [
- "is-docker",
- "once_cell",
-]
-
-[[package]]
-name = "itoa"
-version = "1.0.18"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
-
-[[package]]
-name = "javascriptcore-rs"
-version = "1.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc"
-dependencies = [
- "bitflags 1.3.2",
- "glib",
- "javascriptcore-rs-sys",
-]
-
-[[package]]
-name = "javascriptcore-rs-sys"
-version = "1.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124"
-dependencies = [
- "glib-sys",
- "gobject-sys",
- "libc",
- "system-deps",
-]
-
-[[package]]
-name = "jni"
-version = "0.21.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"
-dependencies = [
- "cesu8",
- "cfg-if",
- "combine",
- "jni-sys 0.3.1",
- "log",
- "thiserror 1.0.69",
- "walkdir",
- "windows-sys 0.45.0",
-]
-
-[[package]]
-name = "jni-sys"
-version = "0.3.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"
-dependencies = [
- "jni-sys 0.4.1",
-]
-
-[[package]]
-name = "jni-sys"
-version = "0.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
-dependencies = [
- "jni-sys-macros",
-]
-
-[[package]]
-name = "jni-sys-macros"
-version = "0.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
-dependencies = [
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "js-sys"
-version = "0.3.103"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102"
-dependencies = [
- "cfg-if",
- "futures-util",
- "wasm-bindgen",
-]
-
-[[package]]
-name = "json-patch"
-version = "3.0.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "863726d7afb6bc2590eeff7135d923545e5e964f004c2ccf8716c25e70a86f08"
-dependencies = [
- "jsonptr",
- "serde",
- "serde_json",
- "thiserror 1.0.69",
-]
-
-[[package]]
-name = "jsonptr"
-version = "0.6.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5dea2b27dd239b2556ed7a25ba842fe47fd602e7fc7433c2a8d6106d4d9edd70"
-dependencies = [
- "serde",
- "serde_json",
-]
-
-[[package]]
-name = "keyboard-types"
-version = "0.7.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a"
-dependencies = [
- "bitflags 2.13.1",
- "serde",
- "unicode-segmentation",
-]
-
-[[package]]
-name = "libappindicator"
-version = "0.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a"
-dependencies = [
- "glib",
- "gtk",
- "gtk-sys",
- "libappindicator-sys",
- "log",
-]
-
-[[package]]
-name = "libappindicator-sys"
-version = "0.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf"
-dependencies = [
- "gtk-sys",
- "libloading",
- "once_cell",
-]
-
-[[package]]
-name = "libc"
-version = "0.2.189"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
-
-[[package]]
-name = "libdbus-sys"
-version = "0.2.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043"
-dependencies = [
- "pkg-config",
-]
-
-[[package]]
-name = "libloading"
-version = "0.7.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f"
-dependencies = [
- "cfg-if",
- "winapi",
-]
-
-[[package]]
-name = "libredox"
-version = "0.1.18"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652"
-dependencies = [
- "libc",
-]
-
-[[package]]
-name = "linux-raw-sys"
-version = "0.12.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
-
-[[package]]
-name = "litemap"
-version = "0.8.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
-
-[[package]]
-name = "lock_api"
-version = "0.4.14"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
-dependencies = [
- "scopeguard",
-]
-
-[[package]]
-name = "log"
-version = "0.4.33"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
-
-[[package]]
-name = "mach2"
-version = "0.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6a1b95cd5421ec55b445b5ae102f5ea0e768de1f82bd3001e11f426c269c3aea"
-dependencies = [
- "libc",
-]
-
-[[package]]
-name = "markup5ever"
-version = "0.38.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8983d30f2915feeaaab2d6babdd6bc7e9ed1a00b66b5e6d74df19aa9c0e91862"
-dependencies = [
- "log",
- "tendril",
- "web_atoms",
-]
-
-[[package]]
-name = "memchr"
-version = "2.8.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
-
-[[package]]
-name = "memoffset"
-version = "0.9.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
-dependencies = [
- "autocfg",
-]
-
-[[package]]
-name = "mime"
-version = "0.3.17"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
-
-[[package]]
-name = "miniz_oxide"
-version = "0.8.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
-dependencies = [
- "adler2",
- "simd-adler32",
-]
-
-[[package]]
-name = "mio"
-version = "1.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"
-dependencies = [
- "libc",
- "wasi",
- "windows-sys 0.61.2",
-]
-
-[[package]]
-name = "muda"
-version = "0.19.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1dd04e60bc0b07438a6771710ee1698f98f6ebbc7f89b61264af1563b8aeb878"
-dependencies = [
- "crossbeam-channel",
- "dpi",
- "gtk",
- "keyboard-types",
- "objc2",
- "objc2-app-kit",
- "objc2-core-foundation",
- "objc2-foundation",
- "once_cell",
- "png 0.18.1",
- "serde",
- "thiserror 2.0.19",
- "windows-sys 0.60.2",
-]
-
-[[package]]
-name = "ndk"
-version = "0.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"
-dependencies = [
- "bitflags 2.13.1",
- "jni-sys 0.3.1",
- "log",
- "ndk-sys",
- "num_enum",
- "raw-window-handle",
- "thiserror 1.0.69",
-]
-
-[[package]]
-name = "ndk-sys"
-version = "0.6.0+11769913"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"
-dependencies = [
- "jni-sys 0.3.1",
-]
-
-[[package]]
-name = "new_debug_unreachable"
-version = "1.0.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
-
-[[package]]
-name = "num-conv"
-version = "0.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
-
-[[package]]
-name = "num-traits"
-version = "0.2.19"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
-dependencies = [
- "autocfg",
-]
-
-[[package]]
-name = "num_enum"
-version = "0.7.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"
-dependencies = [
- "num_enum_derive",
- "rustversion",
-]
-
-[[package]]
-name = "num_enum_derive"
-version = "0.7.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"
-dependencies = [
- "proc-macro-crate 3.5.0",
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "nusb"
-version = "0.2.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "baf1553b6f47685e4c658b2100a6d7262abdc73cb97f423453546ca020155ae9"
-dependencies = [
- "core-foundation",
- "core-foundation-sys",
- "futures-core",
- "io-kit-sys",
- "linux-raw-sys",
- "log",
- "once_cell",
- "rustix",
- "slab",
- "tokio",
- "windows-sys 0.60.2",
-]
-
-[[package]]
-name = "obc-crc"
-version = "0.1.0"
-
-[[package]]
-name = "obc-desktop"
-version = "0.1.0"
-dependencies = [
- "futures-core",
- "nusb",
- "obc-usb",
- "serde",
- "serde_json",
- "tauri",
- "tauri-build",
- "tauri-plugin-dialog",
- "tauri-plugin-opener",
- "tokio",
- "ureq",
- "url",
-]
-
-[[package]]
-name = "obc-link"
-version = "0.1.0"
-dependencies = [
- "obc-crc",
-]
-
-[[package]]
-name = "obc-usb"
-version = "0.1.0"
-dependencies = [
- "getrandom 0.4.3",
- "nusb",
- "obc-link",
- "serde",
- "tokio",
-]
-
-[[package]]
-name = "objc2"
-version = "0.6.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"
-dependencies = [
- "objc2-encode",
- "objc2-exception-helper",
-]
-
-[[package]]
-name = "objc2-app-kit"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
-dependencies = [
- "bitflags 2.13.1",
- "block2",
- "objc2",
- "objc2-core-foundation",
- "objc2-foundation",
-]
-
-[[package]]
-name = "objc2-cloud-kit"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c"
-dependencies = [
- "bitflags 2.13.1",
- "objc2",
- "objc2-foundation",
-]
-
-[[package]]
-name = "objc2-core-data"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"
-dependencies = [
- "objc2",
- "objc2-foundation",
-]
-
-[[package]]
-name = "objc2-core-foundation"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
-dependencies = [
- "bitflags 2.13.1",
- "dispatch2",
- "objc2",
-]
-
-[[package]]
-name = "objc2-core-graphics"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"
-dependencies = [
- "bitflags 2.13.1",
- "dispatch2",
- "objc2",
- "objc2-core-foundation",
- "objc2-io-surface",
-]
-
-[[package]]
-name = "objc2-core-image"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006"
-dependencies = [
- "objc2",
- "objc2-foundation",
-]
-
-[[package]]
-name = "objc2-core-location"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009"
-dependencies = [
- "objc2",
- "objc2-foundation",
-]
-
-[[package]]
-name = "objc2-core-text"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"
-dependencies = [
- "bitflags 2.13.1",
- "objc2",
- "objc2-core-foundation",
- "objc2-core-graphics",
-]
-
-[[package]]
-name = "objc2-encode"
-version = "4.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
-
-[[package]]
-name = "objc2-exception-helper"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c7a1c5fbb72d7735b076bb47b578523aedc40f3c439bea6dfd595c089d79d98a"
-dependencies = [
- "cc",
-]
-
-[[package]]
-name = "objc2-foundation"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
-dependencies = [
- "bitflags 2.13.1",
- "block2",
- "libc",
- "objc2",
- "objc2-core-foundation",
-]
-
-[[package]]
-name = "objc2-io-surface"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"
-dependencies = [
- "bitflags 2.13.1",
- "objc2",
- "objc2-core-foundation",
-]
-
-[[package]]
-name = "objc2-quartz-core"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"
-dependencies = [
- "bitflags 2.13.1",
- "objc2",
- "objc2-core-foundation",
- "objc2-foundation",
-]
-
-[[package]]
-name = "objc2-ui-kit"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"
-dependencies = [
- "bitflags 2.13.1",
- "block2",
- "objc2",
- "objc2-cloud-kit",
- "objc2-core-data",
- "objc2-core-foundation",
- "objc2-core-graphics",
- "objc2-core-image",
- "objc2-core-location",
- "objc2-core-text",
- "objc2-foundation",
- "objc2-quartz-core",
- "objc2-user-notifications",
-]
-
-[[package]]
-name = "objc2-user-notifications"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e"
-dependencies = [
- "objc2",
- "objc2-foundation",
-]
-
-[[package]]
-name = "objc2-web-kit"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f"
-dependencies = [
- "bitflags 2.13.1",
- "block2",
- "objc2",
- "objc2-app-kit",
- "objc2-core-foundation",
- "objc2-foundation",
-]
-
-[[package]]
-name = "once_cell"
-version = "1.21.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
-
-[[package]]
-name = "open"
-version = "5.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a0b3d059e795d52b8a72fef45658620edd4d9c359b338564aa14391ffa511ed5"
-dependencies = [
- "dunce",
- "is-wsl",
- "libc",
-]
-
-[[package]]
-name = "option-ext"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
-
-[[package]]
-name = "ordered-stream"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"
-dependencies = [
- "futures-core",
- "pin-project-lite",
-]
-
-[[package]]
-name = "pango"
-version = "0.18.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4"
-dependencies = [
- "gio",
- "glib",
- "libc",
- "once_cell",
- "pango-sys",
-]
-
-[[package]]
-name = "pango-sys"
-version = "0.18.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5"
-dependencies = [
- "glib-sys",
- "gobject-sys",
- "libc",
- "system-deps",
-]
-
-[[package]]
-name = "parking"
-version = "2.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
-
-[[package]]
-name = "parking_lot"
-version = "0.12.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
-dependencies = [
- "lock_api",
- "parking_lot_core",
-]
-
-[[package]]
-name = "parking_lot_core"
-version = "0.9.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
-dependencies = [
- "cfg-if",
- "libc",
- "redox_syscall",
- "smallvec",
- "windows-link 0.2.1",
-]
-
-[[package]]
-name = "percent-encoding"
-version = "2.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
-
-[[package]]
-name = "phf"
-version = "0.13.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
-dependencies = [
- "phf_macros",
- "phf_shared",
- "serde",
-]
-
-[[package]]
-name = "phf_codegen"
-version = "0.13.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1"
-dependencies = [
- "phf_generator",
- "phf_shared",
-]
-
-[[package]]
-name = "phf_generator"
-version = "0.13.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
-dependencies = [
- "fastrand",
- "phf_shared",
-]
-
-[[package]]
-name = "phf_macros"
-version = "0.13.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
-dependencies = [
- "phf_generator",
- "phf_shared",
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "phf_shared"
-version = "0.13.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"
-dependencies = [
- "siphasher",
-]
-
-[[package]]
-name = "pin-project-lite"
-version = "0.2.17"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
-
-[[package]]
-name = "piper"
-version = "0.2.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"
-dependencies = [
- "atomic-waker",
- "fastrand",
- "futures-io",
-]
-
-[[package]]
-name = "pkg-config"
-version = "0.3.33"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
-
-[[package]]
-name = "plist"
-version = "1.10.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85"
-dependencies = [
- "base64 0.22.1",
- "indexmap 2.14.0",
- "quick-xml",
- "serde",
- "time",
-]
-
-[[package]]
-name = "png"
-version = "0.17.16"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"
-dependencies = [
- "bitflags 1.3.2",
- "crc32fast",
- "fdeflate",
- "flate2",
- "miniz_oxide",
-]
-
-[[package]]
-name = "png"
-version = "0.18.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
-dependencies = [
- "bitflags 2.13.1",
- "crc32fast",
- "fdeflate",
- "flate2",
- "miniz_oxide",
-]
-
-[[package]]
-name = "polling"
-version = "3.11.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
-dependencies = [
- "cfg-if",
- "concurrent-queue",
- "hermit-abi",
- "pin-project-lite",
- "rustix",
- "windows-sys 0.61.2",
-]
-
-[[package]]
-name = "potential_utf"
-version = "0.1.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"
-dependencies = [
- "zerovec",
-]
-
-[[package]]
-name = "powerfmt"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
-
-[[package]]
-name = "precomputed-hash"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
-
-[[package]]
-name = "proc-macro-crate"
-version = "1.3.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919"
-dependencies = [
- "once_cell",
- "toml_edit 0.19.15",
-]
-
-[[package]]
-name = "proc-macro-crate"
-version = "2.0.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24"
-dependencies = [
- "toml_datetime 0.6.3",
- "toml_edit 0.20.2",
-]
-
-[[package]]
-name = "proc-macro-crate"
-version = "3.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
-dependencies = [
- "toml_edit 0.25.13+spec-1.1.0",
-]
-
-[[package]]
-name = "proc-macro-error"
-version = "1.0.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
-dependencies = [
- "proc-macro-error-attr",
- "proc-macro2",
- "quote",
- "syn 1.0.109",
- "version_check",
-]
-
-[[package]]
-name = "proc-macro-error-attr"
-version = "1.0.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
-dependencies = [
- "proc-macro2",
- "quote",
- "version_check",
-]
-
-[[package]]
-name = "proc-macro2"
-version = "1.0.107"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
-dependencies = [
- "unicode-ident",
-]
-
-[[package]]
-name = "quick-xml"
-version = "0.41.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"
-dependencies = [
- "memchr",
-]
-
-[[package]]
-name = "quote"
-version = "1.0.47"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
-dependencies = [
- "proc-macro2",
-]
-
-[[package]]
-name = "r-efi"
-version = "5.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
-
-[[package]]
-name = "r-efi"
-version = "6.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
-
-[[package]]
-name = "raw-window-handle"
-version = "0.6.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
-
-[[package]]
-name = "redox_syscall"
-version = "0.5.18"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
-dependencies = [
- "bitflags 2.13.1",
-]
-
-[[package]]
-name = "redox_users"
-version = "0.5.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac"
-dependencies = [
- "getrandom 0.2.17",
- "libredox",
- "thiserror 2.0.19",
-]
-
-[[package]]
-name = "ref-cast"
-version = "1.0.26"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "216e8f773d7923bcba9ceb86a86c93cabb3903a11872fc3f138c49630e50b96d"
-dependencies = [
- "ref-cast-impl",
-]
-
-[[package]]
-name = "ref-cast-impl"
-version = "1.0.26"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2c9283685feec7d69af75fb0e858d5e7378f33fe4fc699383b2916ab9273e03c"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 3.0.3",
-]
-
-[[package]]
-name = "regex"
-version = "1.13.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
-dependencies = [
- "aho-corasick",
- "memchr",
- "regex-automata",
- "regex-syntax",
-]
-
-[[package]]
-name = "regex-automata"
-version = "0.4.16"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8fcfdb36bda0c880c5931cdc7a2bcdc8ba4556847b9d912bca70bc94708711ad"
-dependencies = [
- "aho-corasick",
- "memchr",
- "regex-syntax",
-]
-
-[[package]]
-name = "regex-syntax"
-version = "0.8.11"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
-
-[[package]]
-name = "reqwest"
-version = "0.13.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3"
-dependencies = [
- "base64 0.22.1",
- "bytes",
- "futures-core",
- "futures-util",
- "http",
- "http-body",
- "http-body-util",
- "hyper",
- "hyper-util",
- "js-sys",
- "log",
- "percent-encoding",
- "pin-project-lite",
- "serde",
- "serde_json",
- "sync_wrapper",
- "tokio",
- "tokio-util",
- "tower",
- "tower-http",
- "tower-service",
- "url",
- "wasm-bindgen",
- "wasm-bindgen-futures",
- "wasm-streams",
- "web-sys",
-]
-
-[[package]]
-name = "rfd"
-version = "0.16.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a15ad77d9e70a92437d8f74c35d99b4e4691128df018833e99f90bcd36152672"
-dependencies = [
- "block2",
- "dispatch2",
- "glib-sys",
- "gobject-sys",
- "gtk-sys",
- "js-sys",
- "log",
- "objc2",
- "objc2-app-kit",
- "objc2-core-foundation",
- "objc2-foundation",
- "raw-window-handle",
- "wasm-bindgen",
- "wasm-bindgen-futures",
- "web-sys",
- "windows-sys 0.60.2",
-]
-
-[[package]]
-name = "ring"
-version = "0.17.14"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
-dependencies = [
- "cc",
- "cfg-if",
- "getrandom 0.2.17",
- "libc",
- "untrusted",
- "windows-sys 0.52.0",
-]
-
-[[package]]
-name = "rustc-hash"
-version = "2.1.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
-
-[[package]]
-name = "rustc_version"
-version = "0.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
-dependencies = [
- "semver",
-]
-
-[[package]]
-name = "rustix"
-version = "1.1.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
-dependencies = [
- "bitflags 2.13.1",
- "errno",
- "libc",
- "linux-raw-sys",
- "windows-sys 0.52.0",
-]
-
-[[package]]
-name = "rustls"
-version = "0.23.46"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
-dependencies = [
- "log",
- "once_cell",
- "ring",
- "rustls-pki-types",
- "rustls-webpki",
- "subtle",
- "zeroize",
-]
-
-[[package]]
-name = "rustls-pki-types"
-version = "1.15.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
-dependencies = [
- "zeroize",
-]
-
-[[package]]
-name = "rustls-webpki"
-version = "0.103.16"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
-dependencies = [
- "ring",
- "rustls-pki-types",
- "untrusted",
-]
-
-[[package]]
-name = "rustversion"
-version = "1.0.23"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
-
-[[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 = "schemars"
-version = "0.8.22"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615"
-dependencies = [
- "dyn-clone",
- "indexmap 1.9.3",
- "schemars_derive",
- "serde",
- "serde_json",
- "url",
- "uuid",
-]
-
-[[package]]
-name = "schemars"
-version = "0.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f"
-dependencies = [
- "dyn-clone",
- "ref-cast",
- "serde",
- "serde_json",
-]
-
-[[package]]
-name = "schemars"
-version = "1.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc"
-dependencies = [
- "dyn-clone",
- "ref-cast",
- "serde",
- "serde_json",
-]
-
-[[package]]
-name = "schemars_derive"
-version = "0.8.22"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d"
-dependencies = [
- "proc-macro2",
- "quote",
- "serde_derive_internals",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "scopeguard"
-version = "1.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
-
-[[package]]
-name = "selectors"
-version = "0.36.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c5d9c0c92a92d33f08817311cf3f2c29a3538a8240e94a6a3c622ce652d7e00c"
-dependencies = [
- "bitflags 2.13.1",
- "cssparser",
- "derive_more",
- "log",
- "new_debug_unreachable",
- "phf",
- "phf_codegen",
- "precomputed-hash",
- "rustc-hash",
- "servo_arc",
- "smallvec",
-]
-
-[[package]]
-name = "semver"
-version = "1.0.28"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
-dependencies = [
- "serde",
- "serde_core",
-]
-
-[[package]]
-name = "serde"
-version = "1.0.229"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
-dependencies = [
- "serde_core",
- "serde_derive",
-]
-
-[[package]]
-name = "serde-untagged"
-version = "0.1.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058"
-dependencies = [
- "erased-serde",
- "serde",
- "serde_core",
- "typeid",
-]
-
-[[package]]
-name = "serde_core"
-version = "1.0.229"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
-dependencies = [
- "serde_derive",
-]
-
-[[package]]
-name = "serde_derive"
-version = "1.0.229"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 3.0.3",
-]
-
-[[package]]
-name = "serde_derive_internals"
-version = "0.29.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "serde_json"
-version = "1.0.151"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
-dependencies = [
- "itoa",
- "memchr",
- "serde",
- "serde_core",
- "zmij",
-]
-
-[[package]]
-name = "serde_repr"
-version = "0.1.21"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 3.0.3",
-]
-
-[[package]]
-name = "serde_spanned"
-version = "0.6.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
-dependencies = [
- "serde",
-]
-
-[[package]]
-name = "serde_spanned"
-version = "1.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"
-dependencies = [
- "serde_core",
-]
-
-[[package]]
-name = "serde_with"
-version = "3.21.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "76a5c54c7310e7b8b9577c286d7e399ddd876c3e12b3ed917a8aabc4b96e9e8c"
-dependencies = [
- "base64 0.22.1",
- "bs58",
- "chrono",
- "hex",
- "indexmap 1.9.3",
- "indexmap 2.14.0",
- "schemars 0.9.0",
- "schemars 1.2.1",
- "serde_core",
- "serde_json",
- "serde_with_macros",
- "time",
-]
-
-[[package]]
-name = "serde_with_macros"
-version = "3.21.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "84d57bc0c8b9a17920c178daa6bb924850d54a9c97ab45194bb8c17ad66bb660"
-dependencies = [
- "darling",
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "serialize-to-javascript"
-version = "0.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "04f3666a07a197cdb77cdf306c32be9b7f598d7060d50cfd4d5aa04bfd92f6c5"
-dependencies = [
- "serde",
- "serde_json",
- "serialize-to-javascript-impl",
-]
-
-[[package]]
-name = "serialize-to-javascript-impl"
-version = "0.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "servo_arc"
-version = "0.4.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930"
-dependencies = [
- "stable_deref_trait",
-]
-
-[[package]]
-name = "sha2"
-version = "0.10.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
-dependencies = [
- "cfg-if",
- "cpufeatures",
- "digest",
-]
-
-[[package]]
-name = "shlex"
-version = "2.0.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
-
-[[package]]
-name = "signal-hook-registry"
-version = "1.4.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
-dependencies = [
- "errno",
- "libc",
-]
-
-[[package]]
-name = "simd-adler32"
-version = "0.3.10"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
-
-[[package]]
-name = "siphasher"
-version = "1.0.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649"
-
-[[package]]
-name = "slab"
-version = "0.4.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
-
-[[package]]
-name = "smallvec"
-version = "1.15.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
-
-[[package]]
-name = "socket2"
-version = "0.6.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
-dependencies = [
- "libc",
- "windows-sys 0.60.2",
-]
-
-[[package]]
-name = "softbuffer"
-version = "0.4.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3"
-dependencies = [
- "bytemuck",
- "js-sys",
- "ndk",
- "objc2",
- "objc2-core-foundation",
- "objc2-core-graphics",
- "objc2-foundation",
- "objc2-quartz-core",
- "raw-window-handle",
- "redox_syscall",
- "tracing",
- "wasm-bindgen",
- "web-sys",
- "windows-sys 0.61.2",
-]
-
-[[package]]
-name = "soup3"
-version = "0.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f"
-dependencies = [
- "futures-channel",
- "gio",
- "glib",
- "libc",
- "soup3-sys",
-]
-
-[[package]]
-name = "soup3-sys"
-version = "0.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27"
-dependencies = [
- "gio-sys",
- "glib-sys",
- "gobject-sys",
- "libc",
- "system-deps",
-]
-
-[[package]]
-name = "stable_deref_trait"
-version = "1.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
-
-[[package]]
-name = "string_cache"
-version = "0.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"
-dependencies = [
- "new_debug_unreachable",
- "parking_lot",
- "phf_shared",
- "precomputed-hash",
-]
-
-[[package]]
-name = "string_cache_codegen"
-version = "0.6.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69"
-dependencies = [
- "phf_generator",
- "phf_shared",
- "proc-macro2",
- "quote",
-]
-
-[[package]]
-name = "strsim"
-version = "0.11.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
-
-[[package]]
-name = "subtle"
-version = "2.6.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
-
-[[package]]
-name = "swift-rs"
-version = "1.0.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4057c98e2e852d51fdcfca832aac7b571f6b351ad159f9eda5db1655f8d0c4d7"
-dependencies = [
- "base64 0.21.7",
- "serde",
- "serde_json",
-]
-
-[[package]]
-name = "syn"
-version = "1.0.109"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
-dependencies = [
- "proc-macro2",
- "unicode-ident",
-]
-
-[[package]]
-name = "syn"
-version = "2.0.119"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
-dependencies = [
- "proc-macro2",
- "quote",
- "unicode-ident",
-]
-
-[[package]]
-name = "syn"
-version = "3.0.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
-dependencies = [
- "proc-macro2",
- "quote",
- "unicode-ident",
-]
-
-[[package]]
-name = "sync_wrapper"
-version = "1.0.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
-dependencies = [
- "futures-core",
-]
-
-[[package]]
-name = "synstructure"
-version = "0.13.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "system-deps"
-version = "6.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349"
-dependencies = [
- "cfg-expr",
- "heck 0.5.0",
- "pkg-config",
- "toml 0.8.2",
- "version-compare",
-]
-
-[[package]]
-name = "tao"
-version = "0.35.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d1c93047acf68669466a34690ac58cca7010bd1b201e1ec86f1fd0a75d3dd4a9"
-dependencies = [
- "bitflags 2.13.1",
- "block2",
- "core-foundation",
- "core-graphics",
- "crossbeam-channel",
- "dbus",
- "dispatch2",
- "dlopen2",
- "dpi",
- "gdkwayland-sys",
- "gdkx11-sys",
- "gtk",
- "jni",
- "libc",
- "log",
- "ndk",
- "ndk-sys",
- "objc2",
- "objc2-app-kit",
- "objc2-foundation",
- "objc2-ui-kit",
- "once_cell",
- "parking_lot",
- "percent-encoding",
- "raw-window-handle",
- "tao-macros",
- "unicode-segmentation",
- "url",
- "windows",
- "windows-core 0.61.2",
- "windows-version",
- "x11-dl",
-]
-
-[[package]]
-name = "tao-macros"
-version = "0.1.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f4e16beb8b2ac17db28eab8bca40e62dbfbb34c0fcdc6d9826b11b7b5d047dfd"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "target-lexicon"
-version = "0.12.16"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
-
-[[package]]
-name = "tauri"
-version = "2.11.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "667b20e2726d572dea2de7370da16e188eb06008faf9a92fab7cdc46791190b5"
-dependencies = [
- "anyhow",
- "bytes",
- "cookie",
- "dirs",
- "dunce",
- "embed_plist",
- "getrandom 0.3.4",
- "glob",
- "gtk",
- "heck 0.5.0",
- "http",
- "jni",
- "libc",
- "log",
- "mime",
- "muda",
- "objc2",
- "objc2-app-kit",
- "objc2-foundation",
- "objc2-ui-kit",
- "objc2-web-kit",
- "percent-encoding",
- "plist",
- "raw-window-handle",
- "reqwest",
- "serde",
- "serde_json",
- "serde_repr",
- "serialize-to-javascript",
- "swift-rs",
- "tauri-build",
- "tauri-macros",
- "tauri-runtime",
- "tauri-runtime-wry",
- "tauri-utils",
- "thiserror 2.0.19",
- "tokio",
- "tray-icon",
- "url",
- "webkit2gtk",
- "webview2-com",
- "window-vibrancy",
- "windows",
-]
-
-[[package]]
-name = "tauri-build"
-version = "2.6.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bc9ce40b16101cb6ea63d3e221567affd1c3a9205f95d7bc574941a10636b632"
-dependencies = [
- "anyhow",
- "cargo_toml",
- "dirs",
- "glob",
- "heck 0.5.0",
- "json-patch",
- "schemars 0.8.22",
- "semver",
- "serde",
- "serde_json",
- "tauri-utils",
- "tauri-winres",
- "walkdir",
-]
-
-[[package]]
-name = "tauri-codegen"
-version = "2.6.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "08279169ff42f8fc45a1dbc9dcae888893ba95288142e5880c59b93a26d2cfc5"
-dependencies = [
- "base64 0.22.1",
- "brotli",
- "ico",
- "json-patch",
- "plist",
- "png 0.17.16",
- "proc-macro2",
- "quote",
- "semver",
- "serde",
- "serde_json",
- "sha2",
- "syn 2.0.119",
- "tauri-utils",
- "thiserror 2.0.19",
- "time",
- "url",
- "uuid",
- "walkdir",
-]
-
-[[package]]
-name = "tauri-macros"
-version = "2.6.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e8b394794f399a421811d06966343e7933fcae92d59f5180b9388d1174497a45"
-dependencies = [
- "heck 0.5.0",
- "proc-macro2",
- "quote",
- "syn 2.0.119",
- "tauri-codegen",
- "tauri-utils",
-]
-
-[[package]]
-name = "tauri-plugin"
-version = "2.6.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "74be5dd4bed9afbd145e5716b5fa2ec28cbc29c34ffa61c258c9273d896c8020"
-dependencies = [
- "anyhow",
- "glob",
- "plist",
- "schemars 0.8.22",
- "serde",
- "serde_json",
- "tauri-utils",
- "walkdir",
-]
-
-[[package]]
-name = "tauri-plugin-dialog"
-version = "2.7.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b2d3c1dbe38037e7f590cdf2492594d5ceebe031e7bc7e827509b22a999d2940"
-dependencies = [
- "log",
- "raw-window-handle",
- "rfd",
- "serde",
- "serde_json",
- "tauri",
- "tauri-plugin",
- "tauri-plugin-fs",
- "thiserror 2.0.19",
- "url",
-]
-
-[[package]]
-name = "tauri-plugin-fs"
-version = "2.5.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b7ecc274121aca0c036a2b42d1cbe83d368d348f54e0bb8a735c2b1548e8f371"
-dependencies = [
- "anyhow",
- "dunce",
- "glob",
- "log",
- "objc2-foundation",
- "percent-encoding",
- "schemars 0.8.22",
- "serde",
- "serde_json",
- "serde_repr",
- "tauri",
- "tauri-plugin",
- "tauri-utils",
- "thiserror 2.0.19",
- "toml 1.1.3+spec-1.1.0",
- "url",
-]
-
-[[package]]
-name = "tauri-plugin-opener"
-version = "2.5.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "17e1bea14edce6b793a04e2417e3fd924b9bc4faae83cdee7d714156cceeed29"
-dependencies = [
- "dunce",
- "glob",
- "objc2-app-kit",
- "objc2-foundation",
- "open",
- "schemars 0.8.22",
- "serde",
- "serde_json",
- "tauri",
- "tauri-plugin",
- "thiserror 2.0.19",
- "url",
- "windows",
- "zbus",
-]
-
-[[package]]
-name = "tauri-runtime"
-version = "2.11.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b0b4bc95aed361b0019067d189a1174a603d460d0f6c72606512d59fc9c12ec8"
-dependencies = [
- "cookie",
- "dpi",
- "gtk",
- "http",
- "jni",
- "objc2",
- "objc2-ui-kit",
- "objc2-web-kit",
- "raw-window-handle",
- "serde",
- "serde_json",
- "tauri-utils",
- "thiserror 2.0.19",
- "url",
- "webkit2gtk",
- "webview2-com",
- "windows",
-]
-
-[[package]]
-name = "tauri-runtime-wry"
-version = "2.11.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4e6fac707727b7a2f48e4ded90976324267371073edbb415ffb73bb0458d203f"
-dependencies = [
- "gtk",
- "http",
- "jni",
- "log",
- "objc2",
- "objc2-app-kit",
- "once_cell",
- "percent-encoding",
- "raw-window-handle",
- "softbuffer",
- "tao",
- "tauri-runtime",
- "tauri-utils",
- "url",
- "webkit2gtk",
- "webview2-com",
- "windows",
- "wry",
-]
-
-[[package]]
-name = "tauri-utils"
-version = "2.9.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3e176a18e67764923c4f1ce66f25ae4abe5f688384d5eb1a0fa6c77f3d90f887"
-dependencies = [
- "anyhow",
- "brotli",
- "cargo_metadata",
- "ctor",
- "dom_query",
- "dunce",
- "glob",
- "http",
- "infer",
- "json-patch",
- "log",
- "memchr",
- "phf",
- "plist",
- "proc-macro2",
- "quote",
- "regex",
- "schemars 0.8.22",
- "semver",
- "serde",
- "serde-untagged",
- "serde_json",
- "serde_with",
- "swift-rs",
- "thiserror 2.0.19",
- "toml 1.1.3+spec-1.1.0",
- "url",
- "urlpattern",
- "uuid",
- "walkdir",
-]
-
-[[package]]
-name = "tauri-winres"
-version = "0.3.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cc65d45c68858bfe420dd29e834b5d15dbecf8a07a8a16cf4d532c7b1f69d4b6"
-dependencies = [
- "dunce",
- "embed-resource",
- "toml 1.1.3+spec-1.1.0",
-]
-
-[[package]]
-name = "tempfile"
-version = "3.27.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
-dependencies = [
- "fastrand",
- "getrandom 0.4.3",
- "once_cell",
- "rustix",
- "windows-sys 0.52.0",
-]
-
-[[package]]
-name = "tendril"
-version = "0.5.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08"
-dependencies = [
- "new_debug_unreachable",
-]
-
-[[package]]
-name = "thiserror"
-version = "1.0.69"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
-dependencies = [
- "thiserror-impl 1.0.69",
-]
-
-[[package]]
-name = "thiserror"
-version = "2.0.19"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9"
-dependencies = [
- "thiserror-impl 2.0.19",
-]
-
-[[package]]
-name = "thiserror-impl"
-version = "1.0.69"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "thiserror-impl"
-version = "2.0.19"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "43cbfe0cf76104d42a574802844187e84a305e531ed54455f11fbde0f10541cd"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 3.0.3",
-]
-
-[[package]]
-name = "time"
-version = "0.3.54"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3e1d5e639ff6bab73cb6885cc7e7b1de96c3f32c68ec55f3952614bec1092244"
-dependencies = [
- "deranged",
- "num-conv",
- "powerfmt",
- "serde_core",
- "time-core",
- "time-macros",
-]
-
-[[package]]
-name = "time-core"
-version = "0.1.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
-
-[[package]]
-name = "time-macros"
-version = "0.2.32"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
-dependencies = [
- "num-conv",
- "time-core",
-]
-
-[[package]]
-name = "tinystr"
-version = "0.8.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d"
-dependencies = [
- "displaydoc",
- "zerovec",
-]
-
-[[package]]
-name = "tinyvec"
-version = "1.12.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f"
-dependencies = [
- "tinyvec_macros",
-]
-
-[[package]]
-name = "tinyvec_macros"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
-
-[[package]]
-name = "tokio"
-version = "1.53.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e"
-dependencies = [
- "bytes",
- "libc",
- "mio",
- "pin-project-lite",
- "socket2",
- "tokio-macros",
- "windows-sys 0.61.2",
-]
-
-[[package]]
-name = "tokio-macros"
-version = "2.7.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6328af13490e73a9b4694030fafd93f8c8c6a9dede33e821c3fc63eddf8042ba"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "tokio-util"
-version = "0.7.19"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"
-dependencies = [
- "bytes",
- "futures-core",
- "futures-sink",
- "pin-project-lite",
- "tokio",
-]
-
-[[package]]
-name = "toml"
-version = "0.8.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d"
-dependencies = [
- "serde",
- "serde_spanned 0.6.9",
- "toml_datetime 0.6.3",
- "toml_edit 0.20.2",
-]
-
-[[package]]
-name = "toml"
-version = "0.9.12+spec-1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"
-dependencies = [
- "indexmap 2.14.0",
- "serde_core",
- "serde_spanned 1.1.1",
- "toml_datetime 0.7.5+spec-1.1.0",
- "toml_parser",
- "toml_writer",
- "winnow 0.7.15",
-]
-
-[[package]]
-name = "toml"
-version = "1.1.3+spec-1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "53c96ecdfa941c8fc4fcaed14f99ada8ebed502eef533015095a07e3301d4c3c"
-dependencies = [
- "indexmap 2.14.0",
- "serde_core",
- "serde_spanned 1.1.1",
- "toml_datetime 1.1.1+spec-1.1.0",
- "toml_parser",
- "toml_writer",
- "winnow 1.0.4",
-]
-
-[[package]]
-name = "toml_datetime"
-version = "0.6.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b"
-dependencies = [
- "serde",
-]
-
-[[package]]
-name = "toml_datetime"
-version = "0.7.5+spec-1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
-dependencies = [
- "serde_core",
-]
-
-[[package]]
-name = "toml_datetime"
-version = "1.1.1+spec-1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
-dependencies = [
- "serde_core",
-]
-
-[[package]]
-name = "toml_edit"
-version = "0.19.15"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421"
-dependencies = [
- "indexmap 2.14.0",
- "toml_datetime 0.6.3",
- "winnow 0.5.40",
-]
-
-[[package]]
-name = "toml_edit"
-version = "0.20.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338"
-dependencies = [
- "indexmap 2.14.0",
- "serde",
- "serde_spanned 0.6.9",
- "toml_datetime 0.6.3",
- "winnow 0.5.40",
-]
-
-[[package]]
-name = "toml_edit"
-version = "0.25.13+spec-1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b"
-dependencies = [
- "indexmap 2.14.0",
- "toml_datetime 1.1.1+spec-1.1.0",
- "toml_parser",
- "winnow 1.0.4",
-]
-
-[[package]]
-name = "toml_parser"
-version = "1.1.2+spec-1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526"
-dependencies = [
- "winnow 1.0.4",
-]
-
-[[package]]
-name = "toml_writer"
-version = "1.1.2+spec-1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
-
-[[package]]
-name = "tower"
-version = "0.5.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
-dependencies = [
- "futures-core",
- "futures-util",
- "pin-project-lite",
- "sync_wrapper",
- "tokio",
- "tower-layer",
- "tower-service",
-]
-
-[[package]]
-name = "tower-http"
-version = "0.6.11"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
-dependencies = [
- "bitflags 2.13.1",
- "bytes",
- "futures-util",
- "http",
- "http-body",
- "pin-project-lite",
- "tower",
- "tower-layer",
- "tower-service",
- "url",
-]
-
-[[package]]
-name = "tower-layer"
-version = "0.3.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
-
-[[package]]
-name = "tower-service"
-version = "0.3.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
-
-[[package]]
-name = "tracing"
-version = "0.1.44"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
-dependencies = [
- "pin-project-lite",
- "tracing-attributes",
- "tracing-core",
-]
-
-[[package]]
-name = "tracing-attributes"
-version = "0.1.31"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "tracing-core"
-version = "0.1.36"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
-dependencies = [
- "once_cell",
-]
-
-[[package]]
-name = "tray-icon"
-version = "0.24.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "65ba1e5f6b9ef9fd87e21b9c6f351554dbd717960089168fcfdef854686961dc"
-dependencies = [
- "crossbeam-channel",
- "dirs",
- "libappindicator",
- "muda",
- "objc2",
- "objc2-app-kit",
- "objc2-core-foundation",
- "objc2-core-graphics",
- "objc2-foundation",
- "once_cell",
- "png 0.18.1",
- "serde",
- "thiserror 2.0.19",
- "windows-sys 0.60.2",
-]
-
-[[package]]
-name = "try-lock"
-version = "0.2.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
-
-[[package]]
-name = "typeid"
-version = "1.0.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"
-
-[[package]]
-name = "typenum"
-version = "1.20.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
-
-[[package]]
-name = "uds_windows"
-version = "1.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
-dependencies = [
- "memoffset",
- "tempfile",
- "windows-sys 0.60.2",
-]
-
-[[package]]
-name = "unic-char-property"
-version = "0.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221"
-dependencies = [
- "unic-char-range",
-]
-
-[[package]]
-name = "unic-char-range"
-version = "0.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc"
-
-[[package]]
-name = "unic-common"
-version = "0.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc"
-
-[[package]]
-name = "unic-ucd-ident"
-version = "0.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e230a37c0381caa9219d67cf063aa3a375ffed5bf541a452db16e744bdab6987"
-dependencies = [
- "unic-char-property",
- "unic-char-range",
- "unic-ucd-version",
-]
-
-[[package]]
-name = "unic-ucd-version"
-version = "0.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4"
-dependencies = [
- "unic-common",
-]
-
-[[package]]
-name = "unicode-ident"
-version = "1.0.24"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
-
-[[package]]
-name = "unicode-segmentation"
-version = "1.13.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
-
-[[package]]
-name = "untrusted"
-version = "0.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
-
-[[package]]
-name = "ureq"
-version = "3.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dea7109cdcd5864d4eeb1b58a1648dc9bf520360d7af16ec26d0a9354bafcfc0"
-dependencies = [
- "base64 0.22.1",
- "flate2",
- "log",
- "percent-encoding",
- "rustls",
- "rustls-pki-types",
- "ureq-proto",
- "utf8-zero",
- "webpki-roots",
-]
-
-[[package]]
-name = "ureq-proto"
-version = "0.6.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e994ba84b0bd1b1b0cf92878b7ef898a5c1760108fe7b6010327e274917a808c"
-dependencies = [
- "base64 0.22.1",
- "http",
- "httparse",
- "log",
-]
-
-[[package]]
-name = "url"
-version = "2.5.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
-dependencies = [
- "form_urlencoded",
- "idna",
- "percent-encoding",
- "serde",
- "serde_derive",
-]
-
-[[package]]
-name = "urlpattern"
-version = "0.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "70acd30e3aa1450bc2eece896ce2ad0d178e9c079493819301573dae3c37ba6d"
-dependencies = [
- "regex",
- "serde",
- "unic-ucd-ident",
- "url",
-]
-
-[[package]]
-name = "utf8-zero"
-version = "0.8.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
-
-[[package]]
-name = "utf8_iter"
-version = "1.0.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
-
-[[package]]
-name = "uuid"
-version = "1.24.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bf3923a6f5c4c6382e0b653c4117f48d631ea17f38ed86e2a828e6f7412f5239"
-dependencies = [
- "getrandom 0.4.3",
- "js-sys",
- "serde_core",
- "wasm-bindgen",
-]
-
-[[package]]
-name = "version-compare"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e"
-
-[[package]]
-name = "version_check"
-version = "0.9.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
-
-[[package]]
-name = "vswhom"
-version = "0.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b"
-dependencies = [
- "libc",
- "vswhom-sys",
-]
-
-[[package]]
-name = "vswhom-sys"
-version = "0.1.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150"
-dependencies = [
- "cc",
- "libc",
-]
-
-[[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 = "want"
-version = "0.3.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
-dependencies = [
- "try-lock",
-]
-
-[[package]]
-name = "wasi"
-version = "0.11.1+wasi-snapshot-preview1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
-
-[[package]]
-name = "wasip2"
-version = "1.0.4+wasi-0.2.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
-dependencies = [
- "wit-bindgen",
-]
-
-[[package]]
-name = "wasm-bindgen"
-version = "0.2.126"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4"
-dependencies = [
- "cfg-if",
- "once_cell",
- "rustversion",
- "wasm-bindgen-macro",
- "wasm-bindgen-shared",
-]
-
-[[package]]
-name = "wasm-bindgen-futures"
-version = "0.4.76"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d"
-dependencies = [
- "js-sys",
- "wasm-bindgen",
-]
-
-[[package]]
-name = "wasm-bindgen-macro"
-version = "0.2.126"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1"
-dependencies = [
- "quote",
- "wasm-bindgen-macro-support",
-]
-
-[[package]]
-name = "wasm-bindgen-macro-support"
-version = "0.2.126"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e"
-dependencies = [
- "bumpalo",
- "proc-macro2",
- "quote",
- "syn 2.0.119",
- "wasm-bindgen-shared",
-]
-
-[[package]]
-name = "wasm-bindgen-shared"
-version = "0.2.126"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24"
-dependencies = [
- "unicode-ident",
-]
-
-[[package]]
-name = "wasm-streams"
-version = "0.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb"
-dependencies = [
- "futures-util",
- "js-sys",
- "wasm-bindgen",
- "wasm-bindgen-futures",
- "web-sys",
-]
-
-[[package]]
-name = "web-sys"
-version = "0.3.103"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141"
-dependencies = [
- "js-sys",
- "wasm-bindgen",
-]
-
-[[package]]
-name = "web_atoms"
-version = "0.2.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "075474b12bcb3d2e3d4546580e9de478eeeead668a1761e2a8860c836b7ef297"
-dependencies = [
- "phf",
- "phf_codegen",
- "string_cache",
- "string_cache_codegen",
-]
-
-[[package]]
-name = "webkit2gtk"
-version = "2.0.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793"
-dependencies = [
- "bitflags 1.3.2",
- "cairo-rs",
- "gdk",
- "gdk-sys",
- "gio",
- "gio-sys",
- "glib",
- "glib-sys",
- "gobject-sys",
- "gtk",
- "gtk-sys",
- "javascriptcore-rs",
- "libc",
- "once_cell",
- "soup3",
- "webkit2gtk-sys",
-]
-
-[[package]]
-name = "webkit2gtk-sys"
-version = "2.0.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5"
-dependencies = [
- "bitflags 1.3.2",
- "cairo-sys-rs",
- "gdk-sys",
- "gio-sys",
- "glib-sys",
- "gobject-sys",
- "gtk-sys",
- "javascriptcore-rs-sys",
- "libc",
- "pkg-config",
- "soup3-sys",
- "system-deps",
-]
-
-[[package]]
-name = "webpki-roots"
-version = "1.0.10"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9"
-dependencies = [
- "rustls-pki-types",
-]
-
-[[package]]
-name = "webview2-com"
-version = "0.38.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a"
-dependencies = [
- "webview2-com-macros",
- "webview2-com-sys",
- "windows",
- "windows-core 0.61.2",
- "windows-implement",
- "windows-interface",
-]
-
-[[package]]
-name = "webview2-com-macros"
-version = "0.8.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "webview2-com-sys"
-version = "0.38.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c"
-dependencies = [
- "thiserror 2.0.19",
- "windows",
- "windows-core 0.61.2",
-]
-
-[[package]]
-name = "winapi"
-version = "0.3.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
-dependencies = [
- "winapi-i686-pc-windows-gnu",
- "winapi-x86_64-pc-windows-gnu",
-]
-
-[[package]]
-name = "winapi-i686-pc-windows-gnu"
-version = "0.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
-
-[[package]]
-name = "winapi-util"
-version = "0.1.11"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
-dependencies = [
- "windows-sys 0.52.0",
-]
-
-[[package]]
-name = "winapi-x86_64-pc-windows-gnu"
-version = "0.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
-
-[[package]]
-name = "window-vibrancy"
-version = "0.6.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d9bec5a31f3f9362f2258fd0e9c9dd61a9ca432e7306cc78c444258f0dce9a9c"
-dependencies = [
- "objc2",
- "objc2-app-kit",
- "objc2-core-foundation",
- "objc2-foundation",
- "raw-window-handle",
- "windows-sys 0.59.0",
- "windows-version",
-]
-
-[[package]]
-name = "windows"
-version = "0.61.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"
-dependencies = [
- "windows-collections",
- "windows-core 0.61.2",
- "windows-future",
- "windows-link 0.1.3",
- "windows-numerics",
-]
-
-[[package]]
-name = "windows-collections"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8"
-dependencies = [
- "windows-core 0.61.2",
-]
-
-[[package]]
-name = "windows-core"
-version = "0.61.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
-dependencies = [
- "windows-implement",
- "windows-interface",
- "windows-link 0.1.3",
- "windows-result 0.3.4",
- "windows-strings 0.4.2",
-]
-
-[[package]]
-name = "windows-core"
-version = "0.62.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
-dependencies = [
- "windows-implement",
- "windows-interface",
- "windows-link 0.2.1",
- "windows-result 0.4.1",
- "windows-strings 0.5.1",
-]
-
-[[package]]
-name = "windows-future"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"
-dependencies = [
- "windows-core 0.61.2",
- "windows-link 0.1.3",
- "windows-threading",
-]
-
-[[package]]
-name = "windows-implement"
-version = "0.60.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "windows-interface"
-version = "0.59.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "windows-link"
-version = "0.1.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"
-
-[[package]]
-name = "windows-link"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
-
-[[package]]
-name = "windows-numerics"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1"
-dependencies = [
- "windows-core 0.61.2",
- "windows-link 0.1.3",
-]
-
-[[package]]
-name = "windows-result"
-version = "0.3.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6"
-dependencies = [
- "windows-link 0.1.3",
-]
-
-[[package]]
-name = "windows-result"
-version = "0.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
-dependencies = [
- "windows-link 0.2.1",
-]
-
-[[package]]
-name = "windows-strings"
-version = "0.4.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57"
-dependencies = [
- "windows-link 0.1.3",
-]
-
-[[package]]
-name = "windows-strings"
-version = "0.5.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
-dependencies = [
- "windows-link 0.2.1",
-]
-
-[[package]]
-name = "windows-sys"
-version = "0.45.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"
-dependencies = [
- "windows-targets 0.42.2",
-]
-
-[[package]]
-name = "windows-sys"
-version = "0.52.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
-dependencies = [
- "windows-targets 0.52.6",
-]
-
-[[package]]
-name = "windows-sys"
-version = "0.59.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
-dependencies = [
- "windows-targets 0.52.6",
-]
-
-[[package]]
-name = "windows-sys"
-version = "0.60.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
-dependencies = [
- "windows-targets 0.53.5",
-]
-
-[[package]]
-name = "windows-sys"
-version = "0.61.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
-dependencies = [
- "windows-link 0.2.1",
-]
-
-[[package]]
-name = "windows-targets"
-version = "0.42.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"
-dependencies = [
- "windows_aarch64_gnullvm 0.42.2",
- "windows_aarch64_msvc 0.42.2",
- "windows_i686_gnu 0.42.2",
- "windows_i686_msvc 0.42.2",
- "windows_x86_64_gnu 0.42.2",
- "windows_x86_64_gnullvm 0.42.2",
- "windows_x86_64_msvc 0.42.2",
-]
-
-[[package]]
-name = "windows-targets"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
-dependencies = [
- "windows_aarch64_gnullvm 0.52.6",
- "windows_aarch64_msvc 0.52.6",
- "windows_i686_gnu 0.52.6",
- "windows_i686_gnullvm 0.52.6",
- "windows_i686_msvc 0.52.6",
- "windows_x86_64_gnu 0.52.6",
- "windows_x86_64_gnullvm 0.52.6",
- "windows_x86_64_msvc 0.52.6",
-]
-
-[[package]]
-name = "windows-targets"
-version = "0.53.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
-dependencies = [
- "windows-link 0.2.1",
- "windows_aarch64_gnullvm 0.53.1",
- "windows_aarch64_msvc 0.53.1",
- "windows_i686_gnu 0.53.1",
- "windows_i686_gnullvm 0.53.1",
- "windows_i686_msvc 0.53.1",
- "windows_x86_64_gnu 0.53.1",
- "windows_x86_64_gnullvm 0.53.1",
- "windows_x86_64_msvc 0.53.1",
-]
-
-[[package]]
-name = "windows-threading"
-version = "0.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6"
-dependencies = [
- "windows-link 0.1.3",
-]
-
-[[package]]
-name = "windows-version"
-version = "0.1.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631"
-dependencies = [
- "windows-link 0.2.1",
-]
-
-[[package]]
-name = "windows_aarch64_gnullvm"
-version = "0.42.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
-
-[[package]]
-name = "windows_aarch64_gnullvm"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
-
-[[package]]
-name = "windows_aarch64_gnullvm"
-version = "0.53.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
-
-[[package]]
-name = "windows_aarch64_msvc"
-version = "0.42.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
-
-[[package]]
-name = "windows_aarch64_msvc"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
-
-[[package]]
-name = "windows_aarch64_msvc"
-version = "0.53.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
-
-[[package]]
-name = "windows_i686_gnu"
-version = "0.42.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
-
-[[package]]
-name = "windows_i686_gnu"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
-
-[[package]]
-name = "windows_i686_gnu"
-version = "0.53.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
-
-[[package]]
-name = "windows_i686_gnullvm"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
-
-[[package]]
-name = "windows_i686_gnullvm"
-version = "0.53.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
-
-[[package]]
-name = "windows_i686_msvc"
-version = "0.42.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
-
-[[package]]
-name = "windows_i686_msvc"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
-
-[[package]]
-name = "windows_i686_msvc"
-version = "0.53.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
-
-[[package]]
-name = "windows_x86_64_gnu"
-version = "0.42.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
-
-[[package]]
-name = "windows_x86_64_gnu"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
-
-[[package]]
-name = "windows_x86_64_gnu"
-version = "0.53.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
-
-[[package]]
-name = "windows_x86_64_gnullvm"
-version = "0.42.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
-
-[[package]]
-name = "windows_x86_64_gnullvm"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
-
-[[package]]
-name = "windows_x86_64_gnullvm"
-version = "0.53.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
-
-[[package]]
-name = "windows_x86_64_msvc"
-version = "0.42.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
-
-[[package]]
-name = "windows_x86_64_msvc"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
-
-[[package]]
-name = "windows_x86_64_msvc"
-version = "0.53.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
-
-[[package]]
-name = "winnow"
-version = "0.5.40"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876"
-dependencies = [
- "memchr",
-]
-
-[[package]]
-name = "winnow"
-version = "0.7.15"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
-
-[[package]]
-name = "winnow"
-version = "1.0.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
-dependencies = [
- "memchr",
-]
-
-[[package]]
-name = "winreg"
-version = "0.55.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97"
-dependencies = [
- "cfg-if",
- "windows-sys 0.59.0",
-]
-
-[[package]]
-name = "wit-bindgen"
-version = "0.57.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
-
-[[package]]
-name = "writeable"
-version = "0.6.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"
-
-[[package]]
-name = "wry"
-version = "0.55.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "186f9871daa55fd9c016578b810d149de58367113db7fb72b462d2323ce19514"
-dependencies = [
- "base64 0.22.1",
- "block2",
- "cookie",
- "crossbeam-channel",
- "dirs",
- "dom_query",
- "dpi",
- "dunce",
- "gdkx11",
- "gtk",
- "http",
- "javascriptcore-rs",
- "jni",
- "libc",
- "ndk",
- "objc2",
- "objc2-app-kit",
- "objc2-core-foundation",
- "objc2-foundation",
- "objc2-ui-kit",
- "objc2-web-kit",
- "once_cell",
- "percent-encoding",
- "raw-window-handle",
- "sha2",
- "soup3",
- "tao-macros",
- "thiserror 2.0.19",
- "url",
- "webkit2gtk",
- "webkit2gtk-sys",
- "webview2-com",
- "windows",
- "windows-core 0.61.2",
- "windows-version",
- "x11-dl",
-]
-
-[[package]]
-name = "x11"
-version = "2.21.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e"
-dependencies = [
- "libc",
- "pkg-config",
-]
-
-[[package]]
-name = "x11-dl"
-version = "2.21.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f"
-dependencies = [
- "libc",
- "once_cell",
- "pkg-config",
-]
-
-[[package]]
-name = "yoke"
-version = "0.8.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
-dependencies = [
- "stable_deref_trait",
- "yoke-derive",
- "zerofrom",
-]
-
-[[package]]
-name = "yoke-derive"
-version = "0.8.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
- "synstructure",
-]
-
-[[package]]
-name = "zbus"
-version = "5.18.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fe18fb60dc696039e738717b76eaea21e7a4489bbb1885020b43c94236d7e98a"
-dependencies = [
- "async-broadcast",
- "async-executor",
- "async-io",
- "async-lock",
- "async-process",
- "async-recursion",
- "async-task",
- "async-trait",
- "blocking",
- "enumflags2",
- "event-listener",
- "futures-core",
- "futures-lite",
- "hex",
- "libc",
- "ordered-stream",
- "rustix",
- "serde",
- "serde_repr",
- "tracing",
- "uds_windows",
- "uuid",
- "windows-sys 0.61.2",
- "winnow 1.0.4",
- "zbus_macros",
- "zbus_names",
- "zvariant",
-]
-
-[[package]]
-name = "zbus_macros"
-version = "5.18.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fe96480bed92df2b442a1a30df364e12d08eed03aeb061f2b8dc6afb2be91119"
-dependencies = [
- "proc-macro-crate 3.5.0",
- "proc-macro2",
- "quote",
- "syn 2.0.119",
- "zbus_names",
- "zvariant",
- "zvariant_utils",
-]
-
-[[package]]
-name = "zbus_names"
-version = "4.3.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e"
-dependencies = [
- "serde",
- "winnow 1.0.4",
- "zvariant",
-]
-
-[[package]]
-name = "zerofrom"
-version = "0.1.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
-dependencies = [
- "zerofrom-derive",
-]
-
-[[package]]
-name = "zerofrom-derive"
-version = "0.1.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
- "synstructure",
-]
-
-[[package]]
-name = "zeroize"
-version = "1.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
-
-[[package]]
-name = "zerotrie"
-version = "0.2.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"
-dependencies = [
- "displaydoc",
- "yoke",
- "zerofrom",
-]
-
-[[package]]
-name = "zerovec"
-version = "0.11.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"
-dependencies = [
- "yoke",
- "zerofrom",
- "zerovec-derive",
-]
-
-[[package]]
-name = "zerovec-derive"
-version = "0.11.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.119",
-]
-
-[[package]]
-name = "zmij"
-version = "1.0.23"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
-
-[[package]]
-name = "zvariant"
-version = "5.13.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bee2a0bcd2a907786a456fff45aaaaf54c9ba5f50b71ae9ec1a4edd200c94911"
-dependencies = [
- "endi",
- "enumflags2",
- "serde",
- "winnow 1.0.4",
- "zvariant_derive",
- "zvariant_utils",
-]
-
-[[package]]
-name = "zvariant_derive"
-version = "5.13.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "38a708216a18780796770bfe3f4739c7c83a3e8f789b755534bbbc06e4e23e12"
-dependencies = [
- "proc-macro-crate 3.5.0",
- "proc-macro2",
- "quote",
- "syn 2.0.119",
- "zvariant_utils",
-]
-
-[[package]]
-name = "zvariant_utils"
-version = "3.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "90cb9383f9b45290407a1258b202d3f8f01db719eb60b4e4055c6375af4fc7c7"
-dependencies = [
- "proc-macro2",
- "quote",
- "serde",
- "syn 2.0.119",
- "winnow 1.0.4",
-]
diff --git a/builder/desktop/Cargo.toml b/builder/desktop/Cargo.toml
deleted file mode 100644
index 9b9140dfa0..0000000000
--- a/builder/desktop/Cargo.toml
+++ /dev/null
@@ -1,75 +0,0 @@
-[package]
-name = "obc-desktop"
-version = "0.1.0"
-edition = "2021"
-publish = false # internal app crate — not published to crates.io
-description = "OpenBikeComputer desktop app: the published-cell builder in a Tauri shell"
-
-# A standalone cargo root, like obc-fw-nrf54l and obc-boot — deliberately NOT a
-# member of the root Cargo.toml. Tauri drags in wry and a platform webview
-# (WebKitGTK on Linux, WebView2 on Windows), so joining the workspace would put a
-# GUI toolkit and its system headers in the way of `cargo test` for the renderer.
-# The cost is the usual one for an excluded crate: its own Cargo.lock, its own
-# fmt/clippy/test invocations, and its own CI job — see the repo AGENTS.md and
-# .github/workflows/ci.yml's `desktop` job.
-[workspace]
-
-[features]
-# Plain `cargo build` produces a shippable app rather than a dev-server shell.
-default = ["custom-protocol"]
-
-# `tauri/custom-protocol` is what decides whether the app *is* an app: with it,
-# `tauri::generate_context!` embeds the built frontend and the webview loads it
-# over the `tauri://` protocol; without it, Tauri is in "dev" mode and points the
-# window at `build.devUrl`. The Tauri templates leave it off and have their CLI
-# add it for `tauri build` — which silently produces a blank window for anyone
-# running plain `cargo run`, which is how this repo builds everything.
-#
-# So it is ON by default here, and the live-reload loop is the explicit opt-out:
-#
-# npm --prefix ../web run dev -- --mode desktop
-# cargo run --no-default-features # follows Vite
-custom-protocol = ["tauri/custom-protocol"]
-
-[build-dependencies]
-# Generates the Tauri context (config + the embedded frontend bundle).
-tauri-build = { version = "2", features = [] }
-
-[dependencies]
-obc-usb = { path = "../usb" }
-tauri = { version = "2", features = [] }
-# Native USB (#909). Pure Rust: there is no C library to vendor, no CMake leg,
-# and nothing for a user to install. It talks to each platform's own USB
-# stack directly — usbfs on Linux, IOKit on macOS, WinUSB on Windows.
-#
-# `features = ["tokio"]` is load-bearing, not tuning. nusb wraps every blocking
-# syscall in a `MaybeFuture`, and without a runtime feature the `.await` arm of
-# that type is a `panic!` — it compiles on all three platforms and dies the first
-# time anything is actually awaited. Tauri's runtime is tokio, so this is the
-# arm to enable. See `usb::runtime_guard` for what stops it happening again.
-nusb = { version = "0.2", features = ["tokio"] }
-# `HotplugWatch` is a `futures_core::Stream`; this is the trait, and nothing else
-# (futures-core has no dependencies of its own).
-futures-core = "0.3"
-# Tauri's async runtime is tokio, and these are the pieces the USB plane needs:
-# `sync` for the per-endpoint mutexes and the cancel epochs, `macros` for the
-# select! that makes a parked transfer cancellable, `fs` to read a map off the
-# disk without blocking a runtime worker.
-tokio = { version = "1", features = ["sync", "macros", "fs", "io-util"] }
-# Used from Rust only (no JS permission needed): "show the file I just built" in
-# the platform's own file manager.
-tauri-plugin-opener = "2"
-# The one place the *user* names a directory: relocating the ride library (E2
-# #912). Called from Rust, like the opener above, so `capabilities/default.json`
-# stays at `core:default` and no JS gets a file-picker. That is also the crate's
-# standing rule about paths, met rather than bent — the frontend still never
-# names a place; here the OS's own chooser does, with the person driving it.
-tauri-plugin-dialog = "2"
-serde = { version = "1", features = ["derive"] }
-serde_json = "1"
-# Blocking HTTP for the small map catalog document. The caller runs on a worker
-# thread, and rustls-by-default avoids an OpenSSL system dependency.
-ureq = "3"
-# Parses catalog/object URLs so the native fetch command can enforce same-origin
-# access instead of handing the webview a general HTTP proxy.
-url = "2"
diff --git a/builder/desktop/README.md b/builder/desktop/README.md
deleted file mode 100644
index 3e75854ea8..0000000000
--- a/builder/desktop/README.md
+++ /dev/null
@@ -1,150 +0,0 @@
-# obc-desktop
-
-The website's cell-catalog map builder in a Tauri v2 window. The Svelte coverage UI, digest
-verification, corridor selection and wasm assembly engine are the same in both products. Rust
-supplies native HTTPS, durable map-set output, USB and the ride library; it does not link
-`obc-pack` and it does not process `.osm.pbf` files.
-
-## Setup
-
-| | |
-|---|---|
-| Rust | stable, via `rustup` |
-| Node | 22+, for the embedded frontend |
-| Linux only | WebKitGTK for `wry`: `libwebkit2gtk-4.1-dev libsoup-3.0-dev libjavascriptcoregtk-4.1-dev libgtk-3-dev librsvg2-dev` |
-
-No GEOS, CMake, libusb or Python dependency. `nusb` talks to each platform's native USB stack.
-
-USB on macOS and Windows needs no extra setup. On Linux:
-
-```sh
-sudo cp linux/99-openbikecomputer.rules /etc/udev/rules.d/
-sudo udevadm control --reload-rules
-sudo udevadm trigger
-# unplug and reconnect the device
-```
-
-## Build and run
-
-Build the two wasm bridges and the desktop frontend first, then run the standalone Rust crate:
-
-```sh
-cd builder/web
-npm ci
-npm run build:wasm
-npm run build:desktop
-
-cd ../desktop
-cargo run --release
-```
-
-`custom-protocol` is a default feature, so plain `cargo run` embeds `builder/web/dist/desktop`.
-For the Vite live-reload loop:
-
-```sh
-# terminal 1, from builder/desktop
-npm --prefix ../web run dev -- --mode desktop
-
-# terminal 2
-cargo run --no-default-features
-```
-
-Packaged builds compile their catalog root from `OBC_CATALOG_URL`, which defaults to
-`https://maps.openbikecomputer.com/cell-catalog/catalog.json`. A runtime variable of the same name
-overrides it to test an unpublished catalog:
-
-```sh
-OBC_CATALOG_URL=https://maps.example.test/catalog.json cargo run --release
-```
-
-Rust fetches the catalog root, every satellite and every cell. Object URLs must use the configured
-root's HTTPS origin; loopback HTTP is allowed for local testing. The webview never gets a general
-network proxy.
-
-## Basemap
-
-The region picker, ride library and route previews draw the same basemap from
-`tiles.openbikecomputer.com`. Each map reads the active release from
-`https://maps.openbikecomputer.com/planner/catalog.json` when it opens. The basemap needs WebGL2
-and shows detail only within the published tile coverage. If it cannot load, the map shows a
-notice and keeps the selection or route overlays. It sends no tile requests to a third-party map
-server.
-
-The webview loads tiles, fonts and symbols itself. The Content Security Policy in
-`tauri.conf.json` names the two hosts. The asset host must list the app origin in its CORS rules:
-`tauri://localhost` on macOS and Linux, `http://tauri.localhost` on Windows.
-
-## Test
-
-This is a standalone cargo root, like `obc-fw-nrf54l` and `obc-boot`, so it needs its own checks:
-
-```sh
-cargo fmt -- --check
-cargo check --release --locked
-cargo clippy --release --locked --all-targets -- -D warnings
-cargo test --release --locked -- --nocapture
-```
-
-The shared Svelte checks run from `builder/web`: `npm run check`, `npm test`, `npm run build:all`.
-
-### Linux release-launch test
-
-The manual suite `manual.desktop-linux-launch` opens the real window under Xvfb, checks its
-`tauri://localhost` origin, searches for Switzerland and adds it to the map, against a loopback
-catalog. CI does not run it. On a Linux host with no OBC device attached, build the release app
-first, then from the repository root:
-
-```sh
-sudo apt-get install webkit2gtk-driver xvfb imagemagick dbus-daemon
-cargo install tauri-driver --version 2.0.6 --locked
-xvfb-run -a dbus-run-session -- uv run --locked --group desktop-e2e python builder/desktop/e2e/launch.py
-```
-
-**Use a WebKit driver with the same version as the installed WebKitGTK runtime.**
-`dbus-run-session` gives the app and the desktop portal services a private session bus with the
-Xvfb display.
-
-`OBC_DESKTOP_BINARY` names an existing release executable. Evidence goes to
-`target/desktop-launch`, or `OBC_DESKTOP_EVIDENCE`: `result.json`, native catalog request logs,
-application and driver logs, rendered HTML and a screenshot, plus `failure.png` when a webview
-session is available.
-
-The suite covers Linux software launch and catalog integration only: no USB permission, no
-enumeration with a physical device and no route upload. Windows launch is not automated, and
-Tauri's native WebDriver route does not support macOS.
-
-## Reference
-
-| | |
-|---|---|
-| Assembled maps | `~/Documents/OpenBikeComputer//` |
-| Pulled rides (GPX) | `~/Documents/OpenBikeComputer/rides/` — relocatable |
-| Ride archive | `/ride-archive/` — internal, not relocatable |
-
-Each completed assembly is a uniquely named folder. Files are written to `.part`, flushed and
-atomically renamed before the assembly is reported complete. The website gets the same
-worker-produced bytes through browser downloads. The visible ride folder holds GPX files only;
-device ride objects and the index live in the internal archive, and `src/rides.rs` documents the
-durable import and relocation rules. Catalog cells are held only for the assembly run: there is no
-`.pbf`, land-polygon, Geofabrik-index or persistent cell cache.
-
-| | |
-|---|---|
-| `src/main.rs` | Tauri commands and the deliberately small webview capability surface |
-| `src/catalog.rs`, `src/http.rs` | Configured catalog root and same-origin native object reads |
-| `src/map_output.rs` | Opaque output sessions and atomic map-set writes |
-| `src/storage.rs`, `src/paths.rs` | Visible app-owned locations |
-| `src/rides.rs` | Managed GPX library plus the durable ride archive |
-| `src/usb/` | Native USB discovery and byte pipes beneath the shared TypeScript protocol |
-
-The window has `core:default` and no filesystem, shell or HTTP plugin; Rust commands hold those
-policies. `dragDropEnabled: false` in `tauri.conf.json` turns off Tauri's OS-level interception so
-the shared HTML5 GPX drop targets get files.
-
-The device protocol is the shared TypeScript implementation in `builder/web/src/lib/usb/`; Rust
-supplies the native pipes only. Large app-owned files stream from the maps folder without entering
-the webview. A newly assembled volume set streams to the device with the manifest last. The device
-page also accepts a standalone `.obcm` from elsewhere.
-
-There are no installers, signing or auto-update. There is no native arbitrary-file picker; files
-selected in the webview use the ordinary chunked transfer path.
diff --git a/builder/desktop/build.rs b/builder/desktop/build.rs
deleted file mode 100644
index 261851f6b6..0000000000
--- a/builder/desktop/build.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-fn main() {
- tauri_build::build();
-}
diff --git a/builder/desktop/capabilities/default.json b/builder/desktop/capabilities/default.json
deleted file mode 100644
index 61c5f8d64b..0000000000
--- a/builder/desktop/capabilities/default.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "$schema": "../gen/schemas/desktop-schema.json",
- "identifier": "default",
- "description": "The app's own commands need no permission; this grants the core set the webview itself uses (window, event, IPC channels). Nothing here opens a filesystem, shell or HTTP capability to JavaScript — every one of those is a Rust command with the policy written in Rust, which is the reason the backend exists.",
- "windows": ["main"],
- "permissions": ["core:default"]
-}
diff --git a/builder/desktop/e2e/launch.py b/builder/desktop/e2e/launch.py
deleted file mode 100644
index 81190fe337..0000000000
--- a/builder/desktop/e2e/launch.py
+++ /dev/null
@@ -1,138 +0,0 @@
-#!/usr/bin/env python3
-"""Launch the embedded Linux frontend and select a local catalog region."""
-
-from contextlib import suppress
-import json
-import os
-from pathlib import Path
-import shlex
-import signal
-import socket
-import subprocess
-import sys
-from tempfile import TemporaryDirectory
-import traceback
-from urllib.parse import urlsplit
-
-from selenium import webdriver
-from selenium.webdriver.common.by import By
-from selenium.webdriver.remote.client_config import ClientConfig
-from selenium.webdriver.support import expected_conditions as EC
-from selenium.webdriver.support.ui import WebDriverWait
-from selenium.webdriver.webkitgtk.options import Options
-
-ROOT = Path(__file__).resolve().parents[3]
-sys.path.insert(0, str(ROOT / "tools"))
-
-from fixture_catalog import CatalogServer, schema_examples # noqa: E402 — needs ROOT on the path
-
-
-def main():
- if sys.platform != "linux":
- raise SystemExit("The release-launch suite requires Linux and Xvfb.")
- binary = Path(os.environ.get("OBC_DESKTOP_BINARY", ROOT / "builder/desktop/target/release/obc-desktop")).resolve()
- evidence = Path(os.environ.get("OBC_DESKTOP_EVIDENCE", ROOT / "target/desktop-launch")).resolve()
- evidence.mkdir(parents=True, exist_ok=True)
- for name in ("result.json", "failure.png", "ready.png", "page.html", "driver.log", "application.log", "catalog.jsonl", "processes.txt"):
- (evidence / name).unlink(missing_ok=True)
- result = {"passed": False, "binary": str(binary)}
- browser = process = server = None
- objects = schema_examples()
-
- with TemporaryDirectory(prefix="obc-desktop-launch-") as scratch, (evidence / "driver.log").open("w") as driver_log:
- try:
- if not binary.is_file() or not os.access(binary, os.X_OK):
- raise RuntimeError(f"Missing executable release app: {binary}")
- server = CatalogServer(objects, log=evidence / "catalog.jsonl").start()
- catalog_url = f"{server.origin}/catalog.json"
- # WebKit launches this wrapper once. exec preserves its PID and captures Rust output.
- wrapper = Path(scratch) / "application.sh"
- pidfile = Path(scratch) / "application.pid"
- wrapper.write_text("#!/bin/sh\n" + f"echo $$ > {shlex.quote(str(pidfile))}\n" +
- f"exec > {shlex.quote(str(evidence / 'application.log'))} 2>&1\n" +
- 'printf "automation=%s inspector=%s display=%s\\n" "$TAURI_WEBVIEW_AUTOMATION" "$WEBKIT_INSPECTOR_SERVER" "$DISPLAY"\n' +
- f'exec {shlex.quote(str(binary))} "$@"\n')
- wrapper.chmod(0o755)
- environment = {**os.environ, "OBC_CATALOG_URL": catalog_url, "RUST_BACKTRACE": "1",
- "XDG_DATA_HOME": scratch, "XDG_CONFIG_HOME": scratch, "XDG_CACHE_HOME": scratch}
- process = subprocess.Popen(["tauri-driver"], env=environment, stdout=driver_log,
- stderr=subprocess.STDOUT, start_new_session=True)
-
- def listening(_):
- if process.poll() is not None:
- raise RuntimeError("tauri-driver exited before readiness")
- try:
- with socket.create_connection(("127.0.0.1", 4444), timeout=1):
- return True
- except OSError:
- return False
-
- WebDriverWait(None, 15).until(listening, "tauri-driver did not listen")
- options = Options()
- options.set_capability("browserName", "wry")
- options.set_capability("tauri:options", {"application": str(wrapper)})
- browser = webdriver.Remote(command_executor="http://127.0.0.1:4444", options=options,
- client_config=ClientConfig(remote_server_addr="http://127.0.0.1:4444", timeout=30))
- wait = WebDriverWait(browser, 30)
- search = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '[aria-label="Search regions"]')))
- result["url"] = browser.current_url
- origin = urlsplit(result["url"])
- if (origin.scheme, origin.netloc) != ("tauri", "localhost"):
- raise AssertionError(f"Expected embedded custom-protocol frontend, got {result['url']}")
- search.send_keys("Switzerland")
- wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[aria-label="Add Switzerland (1.0 KB)"]'))).click()
- wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '[aria-label="Switzerland is already in the map"]')))
- wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, '.ledger .total'), "1.0 KB"))
- if browser.find_elements(By.CSS_SELECTOR, '.catalog-error, .ledger .error, .parts .retry'):
- raise AssertionError("Catalog or region resolution failed")
- missing = set(objects) - set(server.requests)
- if missing:
- raise AssertionError(f"Native catalog requests missing: {sorted(missing)}")
- result["region"] = "Switzerland"
- result["price"] = browser.find_element(By.CSS_SELECTOR, '.ledger .total').text
- result["capabilities"] = browser.capabilities
- browser.save_screenshot(str(evidence / "ready.png"))
- (evidence / "page.html").write_text(browser.page_source)
- browser.quit()
- browser = None
- pid = int(pidfile.read_text())
- WebDriverWait(None, 10).until(lambda _: not Path(f"/proc/{pid}").exists(), "Application did not exit after session quit")
- result["application_exited"] = True
- if "panicked at" in (evidence / "application.log").read_text():
- raise AssertionError("The release app panicked")
- result["passed"] = True
- except Exception:
- result["error"] = traceback.format_exc()
- with suppress(Exception):
- # A session can fail before WebDriver can capture the still-open app window.
- subprocess.run(["import", "-window", "root", str(evidence / "failure.png")],
- check=True, timeout=5)
- (evidence / "processes.txt").write_text(subprocess.check_output(
- ["ps", "-eo", "pid,ppid,stat,comm"], text=True, timeout=5))
- if browser:
- with suppress(Exception):
- browser.save_screenshot(str(evidence / "failure.png"))
- (evidence / "page.html").write_text(browser.page_source)
- raise
- finally:
- if browser:
- with suppress(Exception):
- browser.quit()
- if process:
- with suppress(ProcessLookupError):
- os.killpg(process.pid, signal.SIGTERM)
- try:
- process.wait(timeout=5)
- except subprocess.TimeoutExpired:
- os.killpg(process.pid, signal.SIGKILL)
- process.wait()
- if server:
- server.shutdown()
- server.server_close()
- result["requests"] = server.requests if server else []
- (evidence / "result.json").write_text(json.dumps(result, indent=2) + "\n")
- print(json.dumps(result, indent=2))
-
-
-if __name__ == "__main__":
- main()
diff --git a/builder/desktop/icons/128x128.png b/builder/desktop/icons/128x128.png
deleted file mode 100644
index 8152165d92..0000000000
Binary files a/builder/desktop/icons/128x128.png and /dev/null differ
diff --git a/builder/desktop/icons/128x128@2x.png b/builder/desktop/icons/128x128@2x.png
deleted file mode 100644
index 2b13445fbe..0000000000
Binary files a/builder/desktop/icons/128x128@2x.png and /dev/null differ
diff --git a/builder/desktop/icons/32x32.png b/builder/desktop/icons/32x32.png
deleted file mode 100644
index 2f1c11b745..0000000000
Binary files a/builder/desktop/icons/32x32.png and /dev/null differ
diff --git a/builder/desktop/icons/icon.icns b/builder/desktop/icons/icon.icns
deleted file mode 100644
index 9537f6d4b7..0000000000
Binary files a/builder/desktop/icons/icon.icns and /dev/null differ
diff --git a/builder/desktop/icons/icon.ico b/builder/desktop/icons/icon.ico
deleted file mode 100644
index c2dbaabbc2..0000000000
Binary files a/builder/desktop/icons/icon.ico and /dev/null differ
diff --git a/builder/desktop/icons/icon.png b/builder/desktop/icons/icon.png
deleted file mode 100644
index f3bd39b9dc..0000000000
Binary files a/builder/desktop/icons/icon.png and /dev/null differ
diff --git a/builder/desktop/src/catalog.rs b/builder/desktop/src/catalog.rs
deleted file mode 100644
index 1f79d9daa9..0000000000
--- a/builder/desktop/src/catalog.rs
+++ /dev/null
@@ -1,56 +0,0 @@
-//! The published map catalog, fetched for the desktop app. The desktop and hosted builders consume
-//! the same document over HTTP and hand it to the same frontend catalog client.
-//!
-//! Two things a `fetch()` in the webview would not do: the window has no network capability at all,
-//! so every request the app makes is Rust code in [`crate::http`], and the catalog admits nothing
-//! partial, so the body is read whole and handed over as one string with the URL it came from.
-//!
-//! `OBC_CATALOG_URL` overrides the compiled default at run time, which is how a maintainer tests a
-//! bake tree before publishing.
-
-use serde::Serialize;
-
-const DEFAULT_CATALOG_URL: &str = "https://maps.openbikecomputer.com/cell-catalog/catalog.json";
-const COMPILED_CATALOG_URL: Option<&str> = option_env!("OBC_CATALOG_URL");
-
-/// The manifest body plus the URL it was read from. Relative references resolve against the
-/// manifest's own location, and only this side knows it.
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct FetchedCatalog {
- pub url: String,
- pub body: String,
-}
-
-pub fn url() -> String {
- selected_url(std::env::var("OBC_CATALOG_URL").ok())
-}
-
-fn selected_url(runtime: Option) -> String {
- runtime
- .filter(|value| !value.trim().is_empty())
- .or_else(|| COMPILED_CATALOG_URL.filter(|value| !value.trim().is_empty()).map(str::to_owned))
- .unwrap_or_else(|| DEFAULT_CATALOG_URL.to_owned())
-}
-
-pub fn fetch() -> Result {
- let url = url();
- let body = crate::http::get_text(&url).map_err(|e| format!("map catalog: {e}"))?;
- Ok(FetchedCatalog { url, body })
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn the_catalog_url_is_absolute_and_overridable() {
- // It must be absolute: the frontend resolves catalog references against it.
- assert_eq!(selected_url(None), "https://maps.openbikecomputer.com/cell-catalog/catalog.json");
- assert_eq!(
- selected_url(Some("https://example.invalid/catalog.json".into())),
- "https://example.invalid/catalog.json"
- );
- assert_ne!(selected_url(Some(String::new())), "", "an empty override must fall back");
- }
-}
diff --git a/builder/desktop/src/http.rs b/builder/desktop/src/http.rs
deleted file mode 100644
index 37f6b33e1a..0000000000
--- a/builder/desktop/src/http.rs
+++ /dev/null
@@ -1,74 +0,0 @@
-//! The desktop app's small native network surface. Map selection, verification and assembly are
-//! shared with the web builder; Rust moves the catalog bytes, because the Tauri webview has no
-//! blanket network permission.
-
-use std::io::Read;
-use std::sync::OnceLock;
-use std::time::Duration;
-
-/// A cell is megabytes and a connection to a CDN edge can wedge half-open, and without a deadline
-/// that read never returns. Sized for the largest object over a poor link: the point is to fail a
-/// long stall, not to police a slow connection.
-///
-/// Retrying is not done here. Every catalog object is digest-pinned, and the frontend's
-/// `fetchVerified` owns that policy for both this host and the website.
-const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
-const RESPONSE_TIMEOUT: Duration = Duration::from_secs(30);
-const BODY_TIMEOUT: Duration = Duration::from_secs(300);
-
-fn agent() -> &'static ureq::Agent {
- static AGENT: OnceLock = OnceLock::new();
- AGENT.get_or_init(|| {
- ureq::Agent::config_builder()
- .timeout_connect(Some(CONNECT_TIMEOUT))
- .timeout_recv_response(Some(RESPONSE_TIMEOUT))
- .timeout_recv_body(Some(BODY_TIMEOUT))
- .build()
- .into()
- })
-}
-
-/// Read a small text document whole.
-pub fn get_text(url: &str) -> Result {
- let mut response = agent().get(url).call().map_err(|e| format!("GET {url}: {e}"))?;
- response.body_mut().read_to_string().map_err(|e| format!("read {url}: {e}"))
-}
-
-/// Read one digest-pinned catalog object. It is not a general HTTP proxy: every URL must share the
-/// configured catalog root's origin.
-pub fn get_catalog_object(url: &str) -> Result, String> {
- same_catalog_origin(url, &crate::catalog::url())?;
- let mut response = agent().get(url).call().map_err(|e| format!("GET {url}: {e}"))?;
- let mut bytes = Vec::new();
- response.body_mut().as_reader().read_to_end(&mut bytes).map_err(|e| format!("read {url}: {e}"))?;
- Ok(bytes)
-}
-
-fn same_catalog_origin(requested: &str, catalog: &str) -> Result<(), String> {
- let requested = url::Url::parse(requested).map_err(|e| format!("catalog object URL: {e}"))?;
- let catalog = url::Url::parse(catalog).map_err(|e| format!("configured catalog URL: {e}"))?;
- let local_http =
- requested.scheme() == "http" && matches!(requested.host_str(), Some("localhost" | "127.0.0.1" | "::1"));
- if requested.scheme() != "https" && !local_http {
- return Err("catalog objects must use https (or loopback http for local testing)".into());
- }
- if requested.origin() != catalog.origin() {
- return Err(format!("catalog objects must stay on {}", catalog.origin().ascii_serialization()));
- }
- Ok(())
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn catalog_reads_are_https_and_same_origin() {
- let root = "https://maps.example.test/prefix/catalog.json";
- assert!(same_catalog_origin("https://maps.example.test/prefix/cells/fine/index.json", root).is_ok());
- assert!(same_catalog_origin("https://other.example.test/cell.obcm", root).is_err());
- assert!(same_catalog_origin("http://maps.example.test/cell.obcm", root).is_err());
- assert!(same_catalog_origin("file:///tmp/cell.obcm", root).is_err());
- assert!(same_catalog_origin("http://127.0.0.1:8123/cell.obcm", "http://127.0.0.1:8123/catalog.json").is_ok());
- }
-}
diff --git a/builder/desktop/src/main.rs b/builder/desktop/src/main.rs
deleted file mode 100644
index 06842624b3..0000000000
--- a/builder/desktop/src/main.rs
+++ /dev/null
@@ -1,224 +0,0 @@
-//! The OpenBikeComputer desktop app: the same published-cell map builder as the website, in a
-//! Tauri shell with native storage and device access.
-//!
-//! It adds three things the webview cannot do itself: [`catalog`] fetches the published map
-//! catalog, [`usb`] drives the device because the webview has no WebUSB, and [`rides`] keeps a
-//! durable copy of a ride.
-//!
-//! The window is granted `core:default` and nothing else: no filesystem, no shell, no HTTP. Every
-//! one of those policies is written in Rust, where it can be read, and catalog object reads are
-//! restricted to the configured catalog origin.
-
-mod catalog;
-mod http;
-mod map_output;
-mod paths;
-mod rides;
-mod usb;
-
-use std::sync::Arc;
-
-use tauri::Manager;
-
-/// The published cell catalog, body and base URL.
-#[tauri::command]
-async fn catalog() -> Result {
- tauri::async_runtime::spawn_blocking(catalog::fetch).await.map_err(|e| e.to_string())?
-}
-
-/// One catalog satellite or cell, restricted to the catalog root's origin.
-#[tauri::command]
-async fn catalog_get(url: String) -> Result {
- let bytes = tauri::async_runtime::spawn_blocking(move || http::get_catalog_object(&url))
- .await
- .map_err(|e| e.to_string())??;
- Ok(tauri::ipc::Response::new(bytes))
-}
-
-#[tauri::command]
-fn map_output_begin(
- app: tauri::AppHandle,
- outputs: tauri::State<'_, Arc>,
- name: String,
-) -> Result {
- outputs.begin(&maps_dir(&app), &name)
-}
-
-#[tauri::command]
-async fn map_output_write(
- outputs: tauri::State<'_, Arc>,
- request: tauri::ipc::Request<'_>,
-) -> Result {
- let header = |name: &str| {
- request
- .headers()
- .get(name)
- .and_then(|value| value.to_str().ok())
- .ok_or_else(|| format!("a map output write is missing its `{name}` header"))
- };
- let id: u64 = header("output-id")?.parse().map_err(|_| "a map output write has an invalid id".to_string())?;
- let name = header("filename")?.to_owned();
- let tauri::ipc::InvokeBody::Raw(bytes) = request.body() else {
- return Err("a map output write must carry raw bytes".into());
- };
- let bytes = bytes.clone();
- let outputs = outputs.inner().clone();
- tauri::async_runtime::spawn_blocking(move || outputs.write(id, &name, &bytes)).await.map_err(|e| e.to_string())?
-}
-
-#[tauri::command]
-async fn map_output_finish(outputs: tauri::State<'_, Arc>, id: u64) -> Result<(), String> {
- let outputs = outputs.inner().clone();
- tauri::async_runtime::spawn_blocking(move || outputs.finish(id)).await.map_err(|e| e.to_string())?
-}
-
-#[tauri::command]
-async fn map_output_discard(outputs: tauri::State<'_, Arc>, id: u64) -> Result<(), String> {
- let outputs = outputs.inner().clone();
- tauri::async_runtime::spawn_blocking(move || outputs.discard(id)).await.map_err(|e| e.to_string())?
-}
-
-/// Where built maps go. Shown in the UI, so the user can act on it.
-fn maps_dir(app: &tauri::AppHandle) -> std::path::PathBuf {
- paths::maps_dir(app.path().document_dir().ok())
-}
-
-/// Show a produced file in the platform's file manager.
-///
-/// Scoped to the folders this app owns: a webview can call this command, and revealing any path is
-/// a wider door than the features need. The ride library is listed separately from the maps folder,
-/// because a relocated library is not inside it.
-#[tauri::command]
-fn reveal_file(app: tauri::AppHandle, path: String) -> Result<(), String> {
- let path = std::path::PathBuf::from(path);
- let roots = [maps_dir(&app), ride_library(&app).0.root().to_path_buf()];
- if !roots.iter().any(|root| path.starts_with(root)) {
- let names: Vec = roots.iter().map(|r| r.display().to_string()).collect();
- return Err(format!("only files under {} can be revealed", names.join(" or ")));
- }
- tauri_plugin_opener::reveal_item_in_dir(&path).map_err(|e| format!("reveal {}: {e}", path.display()))
-}
-
-/// The library, and whether its visible GPX folder is the default one.
-///
-/// Resolved per call rather than held in state: the folder can move while the app is running, and a
-/// cached root would then be wrong exactly when a rider is looking at it. The archive lives in app
-/// data and never moves.
-fn ride_library(app: &tauri::AppHandle) -> (rides::Library, bool) {
- let default = paths::rides_dir(app.path().document_dir().ok());
- let archive = paths::ride_archive_dir(app.path().app_data_dir().ok());
- let (root, is_default) = match app.path().app_config_dir().ok().and_then(|dir| rides::configured(&dir)) {
- Some(chosen) if chosen != default => (chosen, false),
- _ => (default, true),
- };
- (rides::Library::new(root, archive), is_default)
-}
-
-/// The library folder and everything in it.
-#[tauri::command]
-fn rides_index(app: tauri::AppHandle) -> rides::IndexView {
- let (library, is_default) = ride_library(&app);
- library.view(is_default)
-}
-
-/// Land one pulled ride durably, and only then resolve.
-///
-/// It lands the bytes with `fsync` before it resolves, so a ride the frontend believes it has is a
-/// ride on this disk. A ride whose write failed rejects here and is absent from the durable index,
-/// so a power cut costs at worst a re-download.
-///
-/// It runs on the blocking pool, because `fsync` blocks.
-#[tauri::command]
-async fn rides_import(app: tauri::AppHandle, request: rides::ImportRequest) -> Result {
- let (library, _) = ride_library(&app);
- tauri::async_runtime::spawn_blocking(move || library.import(&request)).await.map_err(|e| e.to_string())?
-}
-
-/// The stored ride object of one key, which a GPX re-export decodes.
-#[tauri::command]
-async fn rides_read(app: tauri::AppHandle, key: String) -> Result {
- let (library, _) = ride_library(&app);
- let bytes =
- tauri::async_runtime::spawn_blocking(move || library.read_object(&key)).await.map_err(|e| e.to_string())??;
- // The raw path, like `usb_read`: a ride object is hundreds of kilobytes and a JSON number
- // array would be four times that in text.
- Ok(tauri::ipc::Response::new(bytes))
-}
-
-/// Write one ride's GPX into the visible folder: the repair for a GPX somebody deleted, and the
-/// fallback when the file to show is not there yet.
-#[tauri::command]
-async fn rides_write_gpx(app: tauri::AppHandle, key: String, gpx: String) -> Result {
- let (library, _) = ride_library(&app);
- tauri::async_runtime::spawn_blocking(move || library.write_gpx(&key, &gpx)).await.map_err(|e| e.to_string())?
-}
-
-/// Let the rider pick a new home for the library, and move it there.
-///
-/// The native chooser is opened from Rust, because the frontend names a file and never a place, and
-/// the OS's own directory picker is the one way a person can name a place without the webview being
-/// handed a filesystem. It answers `None` when the chooser was dismissed, which is an ordinary
-/// outcome.
-#[tauri::command]
-async fn rides_choose_folder(app: tauri::AppHandle) -> Result, String> {
- use tauri_plugin_dialog::DialogExt;
-
- let (library, _) = ride_library(&app);
- let from = library.root().to_path_buf();
- let (tx, rx) = std::sync::mpsc::channel();
- app.dialog().file().set_title("Where should pulled rides be kept?").pick_folder(move |picked| {
- let _ = tx.send(picked);
- });
- // The chooser answers on the UI thread, so parking a blocking-pool thread on the reply keeps
- // the event loop free to run it.
- let picked =
- tauri::async_runtime::spawn_blocking(move || rx.recv().ok().flatten()).await.map_err(|e| e.to_string())?;
- let Some(picked) = picked else { return Ok(None) };
- let to = picked.into_path().map_err(|e| format!("that folder could not be used: {e}"))?;
-
- let config = app.path().app_config_dir().map_err(|e| format!("no config directory: {e}"))?;
- let moved = to.clone();
- tauri::async_runtime::spawn_blocking(move || {
- rides::relocate(&from, &moved)?;
- rides::remember(&config, &moved)
- })
- .await
- .map_err(|e| e.to_string())??;
- Ok(Some(to.display().to_string()))
-}
-
-fn main() {
- tauri::Builder::default()
- .plugin(tauri_plugin_opener::init())
- // Registered for its Rust API only, which `rides_choose_folder` calls. No JS permission is
- // granted, so the webview cannot open a picker of its own.
- .plugin(tauri_plugin_dialog::init())
- .manage(Arc::new(usb::UsbState::default()))
- .manage(Arc::new(map_output::Outputs::default()))
- .invoke_handler(tauri::generate_handler![
- catalog,
- catalog_get,
- map_output_begin,
- map_output_write,
- map_output_finish,
- map_output_discard,
- reveal_file,
- // The library is a folder plus an index, and the ack follows `rides_import`.
- rides_index,
- rides_import,
- rides_read,
- rides_write_gpx,
- rides_choose_folder,
- // Bytes only: the protocol lives once, in TypeScript, over these.
- usb::usb_watch,
- usb::usb_list,
- usb::usb_open,
- usb::usb_close,
- usb::usb_read,
- usb::usb_write,
- usb::usb_cancel,
- usb::usb_reset,
- ])
- .run(tauri::generate_context!())
- .expect("run the OpenBikeComputer app");
-}
diff --git a/builder/desktop/src/map_output.rs b/builder/desktop/src/map_output.rs
deleted file mode 100644
index 7b9600042f..0000000000
--- a/builder/desktop/src/map_output.rs
+++ /dev/null
@@ -1,144 +0,0 @@
-//! Native landing place for verified assemblies.
-//!
-//! The wasm worker produces the same bytes in every host. The website hands each file to the
-//! browser downloader; the desktop writes the files into one newly created folder under the maps
-//! directory. An opaque id keeps the webview from turning this into a write-anywhere command.
-
-use std::collections::HashMap;
-use std::io::Write;
-use std::path::{Path, PathBuf};
-use std::sync::atomic::{AtomicU64, Ordering};
-use std::sync::Mutex;
-
-use serde::Serialize;
-
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct Opened {
- pub id: u64,
- pub path: String,
-}
-
-#[derive(Default)]
-pub struct Outputs {
- next: AtomicU64,
- open: Mutex>,
-}
-
-impl Outputs {
- pub fn begin(&self, maps: &Path, name: &str) -> Result {
- std::fs::create_dir_all(maps).map_err(|e| format!("{}: {e}", maps.display()))?;
- let base = folder_name(name);
- let path = (1..10_000)
- .find_map(|n| {
- let candidate = maps.join(if n == 1 { base.clone() } else { format!("{base}-{n}") });
- match std::fs::create_dir(&candidate) {
- Ok(()) => Some(Ok(candidate)),
- Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => None,
- Err(e) => Some(Err(format!("{}: {e}", candidate.display()))),
- }
- })
- .ok_or_else(|| format!("{}: could not allocate an output folder", maps.display()))??;
- let id = self.next.fetch_add(1, Ordering::Relaxed).wrapping_add(1);
- self.open.lock().map_err(|_| "map output registry is poisoned".to_string())?.insert(id, path.clone());
- Ok(Opened { id, path: path.display().to_string() })
- }
-
- pub fn write(&self, id: u64, name: &str, bytes: &[u8]) -> Result {
- let open = self.open.lock().map_err(|_| "map output registry is poisoned".to_string())?;
- let root = open.get(&id).ok_or_else(|| "that map output session is not open".to_string())?;
- write_file(root, name, bytes)
- }
-
- pub fn finish(&self, id: u64) -> Result<(), String> {
- self.take(id)?;
- Ok(())
- }
-
- pub fn discard(&self, id: u64) -> Result<(), String> {
- let mut open = self.open.lock().map_err(|_| "map output registry is poisoned".to_string())?;
- let path = open.get(&id).ok_or_else(|| "that map output session is not open".to_string())?;
- match std::fs::remove_dir_all(path) {
- Ok(()) => {}
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
- Err(e) => return Err(format!("discard {}: {e}", path.display())),
- }
- open.remove(&id);
- Ok(())
- }
-
- fn take(&self, id: u64) -> Result {
- self.open
- .lock()
- .map_err(|_| "map output registry is poisoned".to_string())?
- .remove(&id)
- .ok_or_else(|| "that map output session is not open".into())
- }
-}
-
-fn write_file(root: &Path, name: &str, bytes: &[u8]) -> Result {
- validate_filename(name)?;
- let final_path = root.join(name);
- let part_path = root.join(format!(".{name}.part"));
- let result = (|| {
- let mut file = std::fs::OpenOptions::new()
- .write(true)
- .create_new(true)
- .open(&part_path)
- .map_err(|e| format!("{}: {e}", part_path.display()))?;
- file.write_all(bytes).map_err(|e| format!("{}: {e}", part_path.display()))?;
- file.sync_all().map_err(|e| format!("{}: {e}", part_path.display()))?;
- std::fs::rename(&part_path, &final_path).map_err(|e| format!("{}: {e}", final_path.display()))
- })();
- if result.is_err() {
- let _ = std::fs::remove_file(&part_path);
- }
- result?;
- Ok(final_path.display().to_string())
-}
-
-fn folder_name(name: &str) -> String {
- let cleaned: String =
- name.trim().chars().filter(|c| c.is_alphanumeric() || matches!(c, ' ' | '_' | '-')).take(80).collect();
- if cleaned.is_empty() {
- "Map".into()
- } else {
- cleaned
- }
-}
-
-fn validate_filename(name: &str) -> Result<(), String> {
- let safe = !name.is_empty()
- && name != "."
- && name != ".."
- && name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
- if safe {
- Ok(())
- } else {
- Err(format!("unsafe map output filename `{name}`"))
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn an_output_is_grouped_and_cannot_escape() {
- let maps = std::env::temp_dir().join(format!("obc-map-output-{}", std::process::id()));
- let _ = std::fs::remove_dir_all(&maps);
- let outputs = Outputs::default();
- let opened = outputs.begin(&maps, "Baden-Württemberg / tour").unwrap();
- let path = outputs.write(opened.id, "MS1.OBS", b"set").unwrap();
- assert!(Path::new(&path).starts_with(&maps));
- assert_eq!(std::fs::read(path).unwrap(), b"set");
- assert!(outputs.write(opened.id, "../escape", b"no").is_err());
- outputs.finish(opened.id).unwrap();
- assert!(outputs.write(opened.id, "MS1.OBS", b"late").is_err());
- let discarded = outputs.begin(&maps, "Discarded").unwrap();
- outputs.write(discarded.id, "MS1.OBS", b"partial").unwrap();
- outputs.discard(discarded.id).unwrap();
- assert!(!Path::new(&discarded.path).exists());
- let _ = std::fs::remove_dir_all(&maps);
- }
-}
diff --git a/builder/desktop/src/paths.rs b/builder/desktop/src/paths.rs
deleted file mode 100644
index c3ada6052e..0000000000
--- a/builder/desktop/src/paths.rs
+++ /dev/null
@@ -1,72 +0,0 @@
-//! Where the app keeps things.
-//!
-//! Two locations are visible to the user. Assembled maps go somewhere the user can find them: the
-//! desktop tier exists because it has a real filesystem, and a build that landed in an opaque
-//! app-support directory would be a download manager with extra steps. Pulled rides live beside
-//! them in a relocatable GPX folder, with their durable archive in app data.
-
-use std::path::PathBuf;
-
-/// The visible output folder for built maps.
-pub fn maps_dir(documents: Option) -> PathBuf {
- documents.unwrap_or_else(home).join("OpenBikeComputer")
-}
-
-/// The default home of the managed ride library, beside the maps, so one folder answers where this
-/// app puts things and `reveal_file`'s rule covers it without widening.
-///
-/// It is only the default. A rider whose rides belong on an external drive relocates it, and the
-/// choice is remembered in the app's config directory: a folder that named itself could not be
-/// found once it moved.
-pub fn rides_dir(documents: Option) -> PathBuf {
- maps_dir(documents).join("rides")
-}
-
-/// The internal ride archive: the index plus the ride objects the library keeps behind the visible
-/// GPX folder. It is app data and not user files, and it does not follow the GPX folder when the
-/// rider moves it, because a store that follows another folder around is two ways to lose it.
-///
-/// `app_data` is Tauri's per-app data directory. The fallback exists so a platform that cannot name
-/// one still gets a deterministic, private location rather than a panic.
-pub fn ride_archive_dir(app_data: Option) -> PathBuf {
- app_data.unwrap_or_else(|| home().join(".openbikecomputer")).join("ride-archive")
-}
-
-fn home() -> PathBuf {
- #[cfg(windows)]
- let var = "USERPROFILE";
- #[cfg(not(windows))]
- let var = "HOME";
- std::env::var_os(var).map(PathBuf::from).unwrap_or_else(std::env::temp_dir)
-}
-
-/// The same rule for any suffix: strip every path separator, keep only characters that mean nothing
-/// to a shell or a filesystem, and force the extension. It is the reason a name typed into the
-/// window cannot name a place. `fallback` is the stem used when nothing survives the filter.
-pub fn sanitize_basename(name: &str, ext: &str, fallback: &str) -> String {
- let base = name.trim().rsplit(['/', '\\']).next().unwrap_or("");
- let mut cleaned: String =
- base.chars().filter(|c| c.is_alphanumeric() || matches!(c, '.' | '_' | '-' | ' ')).collect();
- cleaned = cleaned.trim().to_string();
- if cleaned.is_empty() || cleaned == ext {
- cleaned = fallback.to_string();
- }
- if !cleaned.ends_with(ext) {
- cleaned.push_str(ext);
- }
- cleaned
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn the_same_rule_forces_any_other_suffix() {
- assert_eq!(sanitize_basename("bikepacking", ".json", "style"), "bikepacking.json");
- assert_eq!(sanitize_basename("../../.ssh/config", ".json", "style"), "config.json");
- assert_eq!(sanitize_basename("", ".json", "style"), "style.json");
- assert_eq!(sanitize_basename(".json", ".json", "style"), "style.json");
- assert_eq!(sanitize_basename("obcm-style-default.json", ".json", "style"), "obcm-style-default.json");
- }
-}
diff --git a/builder/desktop/src/rides.rs b/builder/desktop/src/rides.rs
deleted file mode 100644
index a80656e5c6..0000000000
--- a/builder/desktop/src/rides.rs
+++ /dev/null
@@ -1,1144 +0,0 @@
-//! Durable desktop ride library. [`Library::import`] returns only after it has flushed
-//! the ride object, GPX, and index in that order.
-//!
-//! ```text
-//! / rider-owned, relocatable GPX files
-//! 2026-07-20-schauinsland.gpx
-//!
-//! /ride-archive/ internal, fixed-location archive
-//! index.json
-//! 2026-07-20-schauinsland.obcride
-//! ```
-//!
-//! The lossless `.obcride` copy makes GPX re-export possible. Identity is
-//! `(serial, store_id, id)` because object ids can be reused after a card change.
-
-use std::fs::File;
-use std::io::{self, Write};
-use std::path::{Path, PathBuf};
-use std::sync::{Mutex, MutexGuard};
-use std::time::{SystemTime, UNIX_EPOCH};
-
-use serde::{Deserialize, Serialize};
-
-/// Serializes imports and relocation so temp names and index updates cannot interleave.
-static LIBRARY_LOCK: Mutex<()> = Mutex::new(());
-
-fn lock() -> MutexGuard<'static, ()> {
- // A panic while holding the lock poisons it; the disk state is still governed by the
- // rename-last discipline, so the next operation may simply proceed.
- LIBRARY_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
-}
-
-/// The index's filename. It is readable JSON on purpose: it is the record a person can open and
-/// read.
-pub const INDEX_FILE: &str = "index.json";
-/// Bumped only when an older index can no longer be read. An unreadable index is not fatal: it
-/// re-imports and never deletes.
-const INDEX_VERSION: u32 = 2;
-/// The stored ride object's extension, chosen so it cannot be mistaken for a GPX.
-const RIDE_EXT: &str = "obcride";
-const GPX_EXT: &str = "gpx";
-
-/// Largest ride object this command accepts. It is a ceiling and not an expectation: it is roughly
-/// ten days of continuous recording, and it exists because a Tauri command is a door.
-const MAX_RIDE_BYTES: usize = 16 * 1024 * 1024;
-/// The GPX is the same track as text, five to six times the object, so its ceiling keeps the same
-/// margin.
-const MAX_GPX_BYTES: usize = 128 * 1024 * 1024;
-/// Preview tracks are drawn a few hundred pixels wide, so more points than this would be index
-/// weight nobody can see. The frontend downsamples to it and this is the enforcement.
-const MAX_TRACK_POINTS: usize = 512;
-/// Longest filename stem the library will mint, before its extension.
-const MAX_STEM: usize = 64;
-
-/// The pointer file that remembers a relocated library. It lives in the app's config directory: a
-/// folder that named itself could not be found once it moved.
-const LOCATION_FILE: &str = "ride-library.json";
-
-/// One ride in the library, as `index.json` stores it.
-///
-/// It holds only facts that stay true: no absolute paths, because the GPX folder can move, and no
-/// existence, because a person can delete a GPX in the file manager. Those are [`RideEntry`]'s,
-/// recomputed on every read.
-#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
-#[serde(rename_all = "camelCase")]
-pub struct LibraryRide {
- /// `serial:storeId:objectId`, minted here and never taken from the caller.
- pub key: String,
- pub serial: String,
- #[serde(deserialize_with = "deserialize_store_id")]
- pub store_id: String,
- #[serde(serialize_with = "serialize_object_id", deserialize_with = "deserialize_object_id")]
- pub object_id: u64,
- pub name: String,
- /// Ride start, unix seconds UTC. `0` on a device that never had a trusted clock.
- pub start_time: u32,
- pub distance_m: u32,
- pub moving_time_s: u32,
- pub climb_m: u32,
- pub points: u32,
- /// Length of the stored ride object, bytes.
- pub bytes: u64,
- /// The device's whole-object CRC-32, kept so the stored copy can be re-checked without the
- /// device.
- pub crc32: u32,
- /// When this app first landed the ride, unix seconds. Never re-stamped, so a second pull is a
- /// no-op, which matches the first-ack-wins rule on the device.
- pub imported_at: u64,
- /// Basename of the archived ride object, in the archive directory.
- pub ride_file: String,
- /// Basename of the GPX, in the visible folder.
- pub gpx_file: String,
- /// A downsampled `[lat, lon]` track for the list's preview, in degrees, drawn from the ride's
- /// own points.
- pub track: Vec<[f64; 2]>,
-}
-
-/// One ride as the UI reads it: the stored record plus what only the filesystem can say.
-///
-/// The two extra pairs are recomputed on every read and never written down. `present` means the
-/// archive file exists: a ride whose object is gone is not a durable copy, so it is not acked and
-/// it is pulled again. A missing GPX is only a re-export away, because the archive is its source.
-#[derive(Serialize, Clone, Debug)]
-#[serde(rename_all = "camelCase")]
-pub struct RideEntry {
- #[serde(flatten)]
- pub ride: LibraryRide,
- pub ride_path: String,
- pub gpx_path: String,
- pub present: bool,
- pub gpx_present: bool,
-}
-
-/// So an entry reads as the ride it describes. The wrapper adds facts about the filesystem; it is
-/// not a different kind of thing.
-impl std::ops::Deref for RideEntry {
- type Target = LibraryRide;
-
- fn deref(&self) -> &LibraryRide {
- &self.ride
- }
-}
-
-/// The index file's whole body.
-#[derive(Serialize, Deserialize, Clone, Debug, Default)]
-struct Index {
- version: u32,
- rides: Vec,
-}
-
-/// What the UI is handed: where the visible folder is, and what is in the library.
-#[derive(Serialize, Clone, Debug)]
-#[serde(rename_all = "camelCase")]
-pub struct IndexView {
- pub folder: String,
- /// True when the folder is the app's default rather than one the user picked.
- pub is_default: bool,
- pub rides: Vec,
-}
-
-/// One ride, as the pull hands it over. The bytes and the GPX both cross the IPC boundary here.
-///
-/// A ride is orders of magnitude smaller than the maps and firmware images that need the raw-body
-/// path in [`crate::usb`], and the GPX beside it is text, so a structured command with a stated
-/// ceiling is the cheaper thing to review.
-#[derive(Deserialize, Clone, Debug)]
-#[serde(rename_all = "camelCase")]
-pub struct ImportRequest {
- pub serial: String,
- #[serde(deserialize_with = "deserialize_store_id")]
- pub store_id: String,
- #[serde(deserialize_with = "deserialize_object_id")]
- pub object_id: u64,
- pub name: String,
- pub start_time: u32,
- pub distance_m: u32,
- pub moving_time_s: u32,
- pub climb_m: u32,
- /// Points in the recorded track, from the caller's decode of the object. This crate has no
- /// ride-object decoder and must not grow one: the codecs live once, in `lib/usb/objects.ts`.
- pub points: u32,
- pub crc32: u32,
- pub track: Vec<[f64; 2]>,
- /// The ride object exactly as it came off the wire.
- pub object: Vec,
- /// The GPX 1.1 document, from the same `obc_route::track_to_gpx` the device runs. There is no
- /// GPX writer in this crate and there must never be one.
- pub gpx: String,
-}
-
-/// [`Library::import`]'s answer. `imported` is false when the ride was already in the library,
-/// which is the idempotent case and must not re-stamp anything.
-#[derive(Serialize, Clone, Debug)]
-#[serde(rename_all = "camelCase")]
-pub struct Imported {
- pub ride: RideEntry,
- pub imported: bool,
-}
-
-/// Where a durable write is interrupted.
-///
-/// Production constructs a [`Library`] with [`CrashPoint::None`], and nothing outside this module
-/// can ask for anything else. The other variants exist so the rule that the ack follows the fsync
-/// is checked by running the real code with the power cut at a chosen instant.
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
-pub enum CrashPoint {
- #[default]
- None,
- /// The bytes reached `write()` and the process died before `fsync`: the case that decides
- /// whether this feature can lose a ride.
- BeforeObjectFsync,
- /// The ride's two files are durable and the process died before the index committed.
- BeforeIndexCommit,
-}
-
-/// The message a simulated crash returns, so a test can tell it from a real IO error.
-const CRASH_MSG: &str = "simulated power loss";
-
-pub struct Library {
- /// The visible, relocatable GPX folder.
- root: PathBuf,
- /// The internal archive: `index.json` plus the ride objects. It is app data, so it does not
- /// move when the rider moves the GPX folder.
- archive: PathBuf,
- crash: CrashPoint,
-}
-
-impl Library {
- pub fn new(root: PathBuf, archive: PathBuf) -> Self {
- Library { root, archive, crash: CrashPoint::None }
- }
-
- /// A library that dies at `crash`. Test-only by construction, not by convention.
- #[cfg(test)]
- fn crashing_at(root: PathBuf, archive: PathBuf, crash: CrashPoint) -> Self {
- Library { root, archive, crash }
- }
-
- pub fn root(&self) -> &Path {
- &self.root
- }
-
- /// The index as it is on disk right now, with existence recomputed per ride.
- ///
- /// A missing index is an empty library, and so is a corrupt one. That is the safe direction:
- /// the worst it costs is re-downloading rides the device still holds, while salvaging a
- /// half-parsed index risks writing over the files it half-understood.
- fn load(&self) -> Index {
- read_index(&self.archive.join(INDEX_FILE))
- .unwrap_or_else(|| Index { version: INDEX_VERSION, rides: Vec::new() })
- }
-
- /// A stored record, joined to the filesystem as it is right now.
- fn entry(&self, ride: LibraryRide) -> RideEntry {
- let ride_path = self.archive.join(&ride.ride_file);
- let gpx_path = self.root.join(&ride.gpx_file);
- // Existence alone is not durability. `present` feeds the ack, so a truncated or swapped
- // archive file must read as absent: the ride is then pulled again, which costs a download
- // instead of a ride. The index's own `bytes` is the cheap whole-file check; hashing every
- // archive on every read would make listing a library cost its size.
- let present = std::fs::metadata(&ride_path).is_ok_and(|m| m.is_file() && m.len() == ride.bytes);
- RideEntry {
- present,
- gpx_present: gpx_path.is_file(),
- ride_path: ride_path.display().to_string(),
- gpx_path: gpx_path.display().to_string(),
- ride,
- }
- }
-
- fn entries(&self) -> Vec {
- self.load().rides.into_iter().map(|ride| self.entry(ride)).collect()
- }
-
- pub fn view(&self, is_default: bool) -> IndexView {
- let _guard = lock();
- IndexView { folder: self.root.display().to_string(), is_default, rides: self.entries() }
- }
-
- /// Land one pulled ride durably. Idempotent on its `(serial, store_id, id)` key.
- ///
- /// It returns only after the ride object, the GPX and the index have each been fsynced. The
- /// caller may ack after this resolves and at no earlier point.
- pub fn import(&self, req: &ImportRequest) -> Result {
- let _guard = lock();
- if req.serial.is_empty() {
- return Err("this device reports no serial number, so a ride from it cannot be keyed".into());
- }
- validate_store_id(&req.store_id)?;
- if req.object_id == 0 {
- return Err("objectId zero names no object".into());
- }
- if req.object.is_empty() {
- return Err("that ride object is empty".into());
- }
- if req.object.len() > MAX_RIDE_BYTES {
- return Err(format!("that ride object is {} bytes; the limit is {MAX_RIDE_BYTES}", req.object.len()));
- }
- if req.gpx.is_empty() {
- return Err("that ride converted to an empty GPX".into());
- }
- if req.gpx.len() > MAX_GPX_BYTES {
- return Err(format!("that GPX is {} bytes; the limit is {MAX_GPX_BYTES}", req.gpx.len()));
- }
- if req.track.len() > MAX_TRACK_POINTS {
- return Err(format!("a preview track carries at most {MAX_TRACK_POINTS} points"));
- }
-
- std::fs::create_dir_all(&self.root).map_err(|e| format!("create {}: {e}", self.root.display()))?;
- std::fs::create_dir_all(&self.archive).map_err(|e| format!("create {}: {e}", self.archive.display()))?;
- let mut index = self.load();
- let key = ride_key(&req.serial, &req.store_id, req.object_id);
-
- // The idempotent path: everything is already here, so nothing is written or re-stamped.
- if let Some(existing) = index.rides.iter().find(|r| r.key == key) {
- let entry = self.entry(existing.clone());
- if entry.present && entry.gpx_present {
- return Ok(Imported { ride: entry, imported: false });
- }
- }
-
- let existing = index.rides.iter().position(|r| r.key == key);
- let (ride_file, gpx_file, imported_at) = match existing {
- // A repair: the record survived and a file did not. Keep the names and the original
- // `imported_at`, because this is the same ride arriving again.
- Some(at) => {
- let r = &index.rides[at];
- (r.ride_file.clone(), r.gpx_file.clone(), r.imported_at)
- }
- None => {
- let stem = unique_stem(&index, &self.root, &self.archive, &key, &stem_for(req))?;
- (format!("{stem}.{RIDE_EXT}"), format!("{stem}.{GPX_EXT}"), now_secs())
- }
- };
-
- // Order is the contract: the lossless object, then the portable GPX, then the index that
- // claims both. A crash at any point leaves an index that does not name this ride.
- durable_write(&self.archive, &ride_file, &req.object, self.crash_at(CrashPoint::BeforeObjectFsync))
- .map_err(|e| format!("write {}: {e}", self.archive.join(&ride_file).display()))?;
- durable_write(&self.root, &gpx_file, req.gpx.as_bytes(), CrashPoint::None)
- .map_err(|e| format!("write {}: {e}", self.root.join(&gpx_file).display()))?;
-
- let ride = LibraryRide {
- key: key.clone(),
- serial: req.serial.clone(),
- store_id: req.store_id.clone(),
- object_id: req.object_id,
- name: req.name.clone(),
- start_time: req.start_time,
- distance_m: req.distance_m,
- moving_time_s: req.moving_time_s,
- climb_m: req.climb_m,
- points: req.points,
- bytes: req.object.len() as u64,
- crc32: req.crc32,
- imported_at,
- ride_file,
- gpx_file,
- track: req.track.clone(),
- };
-
- match existing {
- Some(at) => index.rides[at] = ride.clone(),
- None => index.rides.push(ride.clone()),
- }
- if self.crash == CrashPoint::BeforeIndexCommit {
- return Err(format!("{CRASH_MSG} before the index committed"));
- }
- self.commit(&index)?;
- Ok(Imported { ride: self.entry(ride), imported: existing.is_none() })
- }
-
- /// The stored ride object of one key, which is what a re-export reads.
- pub fn read_object(&self, key: &str) -> Result, String> {
- let _guard = lock();
- let ride = self.find(key)?;
- std::fs::read(self.archive.join(&ride.ride_file))
- .map_err(|e| format!("read {}: {e}", self.archive.join(&ride.ride_file).display()))
- }
-
- /// Write one ride's GPX durably into the visible folder: the repair for a GPX somebody deleted
- /// or renamed. The archived object is the source, so it can always be run again.
- pub fn write_gpx(&self, key: &str, gpx: &str) -> Result {
- let _guard = lock();
- if gpx.is_empty() || gpx.len() > MAX_GPX_BYTES {
- return Err(format!("a GPX of {} bytes is outside 1..={MAX_GPX_BYTES}", gpx.len()));
- }
- let ride = self.find(key)?;
- std::fs::create_dir_all(&self.root).map_err(|e| format!("create {}: {e}", self.root.display()))?;
- durable_write(&self.root, &ride.gpx_file, gpx.as_bytes(), CrashPoint::None)
- .map_err(|e| format!("write {}: {e}", self.root.join(&ride.gpx_file).display()))?;
- Ok(self.root.join(&ride.gpx_file).display().to_string())
- }
-
- fn find(&self, key: &str) -> Result {
- self.load().rides.into_iter().find(|r| r.key == key).ok_or_else(|| format!("no ride {key} in this library"))
- }
-
- /// Rewrite the index durably, through its own temp and rename, so a crash mid-write leaves the
- /// previous index whole and loses only the last ride's record.
- fn commit(&self, index: &Index) -> Result<(), String> {
- let body = serde_json::to_vec_pretty(index).map_err(|e| format!("encode {INDEX_FILE}: {e}"))?;
- durable_write(&self.archive, INDEX_FILE, &body, CrashPoint::None)
- .map_err(|e| format!("write {}: {e}", self.archive.join(INDEX_FILE).display()))
- }
-
- fn crash_at(&self, point: CrashPoint) -> CrashPoint {
- if self.crash == point {
- point
- } else {
- CrashPoint::None
- }
- }
-}
-
-/// Read and parse an index file. `None` means missing or unreadable, and the caller decides what
-/// that means.
-fn read_index(path: &Path) -> Option {
- let bytes = std::fs::read(path).ok()?;
- match serde_json::from_slice::(&bytes) {
- Ok(index) if index.version == INDEX_VERSION => Some(index),
- Ok(_) => None,
- Err(e) => {
- eprintln!("ride library: {} is unreadable ({e}); treating it as empty", path.display());
- None
- }
- }
-}
-
-/// Move one file into `dir/name` so that no point of interruption loses it: `rename` on the same
-/// volume, otherwise copy, fsync, atomic rename into place, and only then unlink the source. The
-/// copy path makes a cross-filesystem move as safe as a same-volume one.
-fn move_file_durably(source: &Path, dir: &Path, name: &str) -> Result<(), String> {
- if std::fs::rename(source, dir.join(name)).is_ok() {
- return sync_dir(dir).map_err(|e| format!("sync {}: {e}", dir.display()));
- }
- let bytes = std::fs::read(source).map_err(|e| format!("read {}: {e}", source.display()))?;
- durable_write(dir, name, &bytes, CrashPoint::None)
- .map_err(|e| format!("write {}: {e}", dir.join(name).display()))?;
- std::fs::remove_file(source).map_err(|e| format!("remove {}: {e}", source.display()))
-}
-
-/// Shared with `lib/device/rides.ts`: full StoreId hex and decimal u64 ObjectId.
-pub fn ride_key(serial: &str, store_id: &str, object_id: u64) -> String {
- format!("{serial}:{store_id}:{object_id}")
-}
-
-fn validate_store_id(value: &str) -> Result<(), String> {
- if value.len() == 32 && value.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) {
- Ok(())
- } else {
- Err("storeId must contain exactly 32 lowercase hexadecimal digits".into())
- }
-}
-
-fn deserialize_store_id<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result {
- let value = String::deserialize(deserializer)?;
- validate_store_id(&value).map_err(serde::de::Error::custom)?;
- Ok(value)
-}
-
-fn serialize_object_id(value: &u64, serializer: S) -> Result {
- serializer.collect_str(value)
-}
-
-fn deserialize_object_id<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result {
- let text = String::deserialize(deserializer)?;
- let value = text.parse::().map_err(serde::de::Error::custom)?;
- if value == 0 || text != value.to_string() {
- return Err(serde::de::Error::custom("objectId must be a canonical nonzero decimal u64 string"));
- }
- Ok(value)
-}
-
-/// Write `bytes` to `dir/name` so that a power cut cannot leave a half-file behind.
-///
-/// Four steps, none of them optional. The write goes into a `.part` sibling, so the destination
-/// keeps its previous contents for the whole write. `sync_all` puts the bytes and the inode on the
-/// disk; on macOS Rust's std implements it as `F_FULLFSYNC`, which also flushes the drive's own
-/// write cache, where plain `fsync` does not. The `rename` is atomic on every filesystem this app
-/// runs on, so a reader sees the old file or the new one. The directory fsync makes that rename
-/// durable; skipping it is the classic failure where the data survives and the name does not.
-///
-/// A real IO failure cleans its `.part` up. A [`CrashPoint`] does not, because the point of
-/// simulating a power cut is to leave the mess a power cut leaves.
-fn durable_write(dir: &Path, name: &str, bytes: &[u8], crash: CrashPoint) -> io::Result<()> {
- let tmp = dir.join(format!(".{name}.part"));
- let result = write_and_sync(&tmp, bytes, crash);
- if result.is_err() {
- if crash == CrashPoint::None {
- let _ = std::fs::remove_file(&tmp);
- }
- return result;
- }
- std::fs::rename(&tmp, dir.join(name))?;
- sync_dir(dir)
-}
-
-fn write_and_sync(tmp: &Path, bytes: &[u8], crash: CrashPoint) -> io::Result<()> {
- let mut file = File::create(tmp)?;
- file.write_all(bytes)?;
- if crash != CrashPoint::None {
- // The process dies here. The bytes are in the page cache, the rename never happened, and
- // nothing above this line told anyone the ride was safe.
- return Err(io::Error::new(io::ErrorKind::Interrupted, format!("{CRASH_MSG} before fsync")));
- }
- file.sync_all()
-}
-
-/// fsync the directory entry, so the rename itself survives a power cut.
-///
-/// Unix opens the directory read-only and fsyncs the handle. Windows has no equivalent and does not
-/// need one: `File::open` on a directory fails without `FILE_FLAG_BACKUP_SEMANTICS`, and NTFS
-/// records a rename in its metadata log, which is committed before `MoveFileEx` returns, so the
-/// file's own flush is the whole requirement there.
-#[cfg(unix)]
-fn sync_dir(dir: &Path) -> io::Result<()> {
- File::open(dir)?.sync_all()
-}
-
-#[cfg(not(unix))]
-fn sync_dir(_dir: &Path) -> io::Result<()> {
- Ok(())
-}
-
-/// `YYYY-MM-DD-some-ride-name`, or just the name when the device had no clock.
-///
-/// The date leads because a folder sorts by name and rides are read in order. It is UTC, matching
-/// the ride object's `start_time`: rendering it locally would file a late-evening ride under the
-/// wrong day for anyone west of Greenwich.
-fn stem_for(req: &ImportRequest) -> String {
- let name = crate::paths::sanitize_basename(&req.name, "", "ride");
- let mut stem = match utc_date(req.start_time) {
- Some(date) => format!("{date}-{name}"),
- None => name,
- };
- if stem.len() > MAX_STEM {
- // On a char boundary: a stem is a filename, and half a UTF-8 sequence is not one.
- let cut = (0..=MAX_STEM).rev().find(|&n| stem.is_char_boundary(n)).unwrap_or(0);
- stem.truncate(cut);
- }
- stem.trim().trim_end_matches(['.', '-']).to_string()
-}
-
-/// A stem unclaimed by the index or either folder, including files from an unreadable index.
-fn unique_stem(index: &Index, root: &Path, archive: &Path, key: &str, base: &str) -> Result {
- let taken = |candidate: &str| {
- let ride_file = format!("{candidate}.{RIDE_EXT}");
- let gpx_file = format!("{candidate}.{GPX_EXT}");
- index.rides.iter().any(|r| r.ride_file == ride_file || r.gpx_file == gpx_file)
- || archive.join(ride_file).exists()
- || root.join(gpx_file).exists()
- };
- let base = if base.is_empty() { "ride" } else { base };
- if !taken(base) {
- return Ok(base.to_string());
- }
- let with_id = format!("{base}-{}", key.rsplit(':').next().unwrap_or("0"));
- if !taken(&with_id) {
- return Ok(with_id);
- }
- (2..10_000)
- .map(|n| format!("{with_id}-{n}"))
- .find(|candidate| !taken(candidate))
- .ok_or_else(|| "no unused ride filename is available".into())
-}
-
-/// `YYYY-MM-DD` in UTC, or `None` for a device whose clock was never set.
-///
-/// Civil-from-days arithmetic, because a date is fifteen lines and a date library is a dependency.
-/// Valid for every timestamp a `u32` can hold.
-fn utc_date(start_time: u32) -> Option {
- if start_time == 0 {
- return None;
- }
- let days = (start_time / 86_400) as i64;
- let z = days + 719_468;
- let era = z.div_euclid(146_097);
- let doe = z.rem_euclid(146_097);
- let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
- let y = yoe + era * 400;
- let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
- let mp = (5 * doy + 2) / 153;
- let d = doy - (153 * mp + 2) / 5 + 1;
- let m = if mp < 10 { mp + 3 } else { mp - 9 };
- let y = if m <= 2 { y + 1 } else { y };
- Some(format!("{y:04}-{m:02}-{d:02}"))
-}
-
-fn now_secs() -> u64 {
- SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
-}
-
-#[derive(Serialize, Deserialize)]
-struct Location {
- dir: String,
-}
-
-/// The folder the user relocated the library to, if they did.
-///
-/// A folder that no longer exists is not replaced by the default: the app would then start a second
-/// library on an unplugged external drive and report nothing missing. The caller surfaces it.
-pub fn configured(config_dir: &Path) -> Option {
- let bytes = std::fs::read(config_dir.join(LOCATION_FILE)).ok()?;
- let location: Location = serde_json::from_slice(&bytes).ok()?;
- let dir = PathBuf::from(location.dir);
- (!dir.as_os_str().is_empty()).then_some(dir)
-}
-
-/// Remember a relocated library. Durable, because forgetting where the rides went is its own kind
-/// of data loss.
-pub fn remember(config_dir: &Path, dir: &Path) -> Result<(), String> {
- std::fs::create_dir_all(config_dir).map_err(|e| format!("create {}: {e}", config_dir.display()))?;
- let body = serde_json::to_vec_pretty(&Location { dir: dir.display().to_string() })
- .map_err(|e| format!("encode {LOCATION_FILE}: {e}"))?;
- durable_write(config_dir, LOCATION_FILE, &body, CrashPoint::None)
- .map_err(|e| format!("write {}: {e}", config_dir.join(LOCATION_FILE).display()))
-}
-
-/// Move the visible library, the GPX files, to a new folder.
-///
-/// The internal archive stays in app data. Existing destination files are never replaced.
-/// Cross-filesystem moves copy and flush before unlinking the source, and the caller updates the
-/// configured location only after success.
-pub fn relocate(from: &Path, to: &Path) -> Result<(), String> {
- let _guard = lock();
- if from == to {
- return Ok(());
- }
- if to.starts_with(from) || from.starts_with(to) {
- return Err("pick a folder that is not inside the current one".into());
- }
- std::fs::create_dir_all(to).map_err(|e| format!("create {}: {e}", to.display()))?;
- if !from.exists() {
- return Ok(());
- }
-
- let entries = std::fs::read_dir(from).map_err(|e| format!("read {}: {e}", from.display()))?;
- let mut names: Vec = entries
- .flatten()
- .filter(|entry| entry.path().is_file())
- .filter_map(|entry| entry.file_name().to_str().map(str::to_owned))
- .filter(|name| !name.starts_with('.') && Path::new(name).extension().is_some_and(|e| e == GPX_EXT))
- .collect();
- names.sort();
-
- // Two passes: the first discovers a collision before anything has moved, and the second
- // re-checks per file, because `rename` clobbers and std has no portable no-clobber rename. The
- // re-check narrows the race to the one rename; a file another program drops into that window
- // can still be lost. The library lock rules out this process racing itself.
- for name in &names {
- if to.join(name).exists() {
- return Err(format!("{} already contains a file named {name} — pick another folder", to.display()));
- }
- }
- for name in &names {
- if to.join(name).exists() {
- return Err(format!("{} now contains a file named {name} — nothing further was moved", to.display()));
- }
- move_file_durably(&from.join(name), to, name)?;
- }
- sync_dir(to).map_err(|e| format!("sync {}: {e}", to.display()))?;
- let _ = sync_dir(from);
- // Best effort: an empty folder left behind is untidy and a failed move is not. A folder that
- // still holds the rider's other files stays.
- let _ = std::fs::remove_dir(from);
- Ok(())
-}
-
-#[cfg(test)]
-mod tests {
- /// The ack set, as a test helper: which rides are durably on this disk. It is a filter over
- /// `view()`'s entries, and the tests below are about that property.
- fn durable_ids(lib: &Library, serial: &str, store_id: u128) -> Vec {
- let mut ids: Vec = lib
- .view(false)
- .rides
- .into_iter()
- .filter(|e| e.present && e.ride.serial == serial && e.ride.store_id == format!("{store_id:032x}"))
- .map(|e| e.ride.object_id)
- .collect();
- ids.sort_unstable();
- ids.dedup();
- ids
- }
-
- use super::*;
-
- fn temp(tag: &str) -> PathBuf {
- let dir = std::env::temp_dir().join(format!(
- "obc-rides-{tag}-{}-{:?}",
- std::process::id(),
- std::time::SystemTime::now().duration_since(UNIX_EPOCH).unwrap().subsec_nanos()
- ));
- std::fs::create_dir_all(&dir).expect("temp dir");
- dir
- }
-
- /// A library over a visible folder and an internal archive: the production shape, in a
- /// sandbox.
- fn library(base: &Path) -> Library {
- Library::new(base.join("rides"), base.join("archive"))
- }
-
- fn request(serial: &str, store_id: u128, id: u64, name: &str) -> ImportRequest {
- ImportRequest {
- serial: serial.into(),
- store_id: format!("{store_id:032x}"),
- object_id: id,
- name: name.into(),
- start_time: 1_764_547_200, // 2025-12-01
- distance_m: 42_195,
- moving_time_s: 7_200,
- climb_m: 640,
- points: 4_211,
- crc32: 0xdead_beef,
- track: vec![[48.0, 7.85], [48.01, 7.86]],
- object: format!("ride-object-{name}-{id}").into_bytes(),
- gpx: format!("{name} "),
- }
- }
-
- fn file_names(dir: &Path) -> Vec {
- let mut names: Vec = std::fs::read_dir(dir)
- .map(|entries| entries.flatten().filter_map(|e| e.file_name().to_str().map(str::to_owned)).collect())
- .unwrap_or_default();
- names.sort();
- names
- }
-
- #[test]
- fn a_second_import_of_the_same_ride_writes_nothing_and_re_stamps_nothing() {
- let base = temp("idem");
- let lib = library(&base);
- let req = request("OBC-24-000317", 0xa1b2c3d4, 7, "Dawn Patrol");
-
- let first = lib.import(&req).expect("first import");
- assert!(first.imported, "the first pull lands the ride");
- let stamp = first.ride.imported_at;
- let archive = base.join("archive");
- let ride_mtime = std::fs::metadata(archive.join(&first.ride.ride_file)).unwrap().modified().unwrap();
-
- let second = lib.import(&req).expect("second import");
- assert!(!second.imported, "the second pull is a no-op, not a duplicate");
- assert_eq!(second.ride.imported_at, stamp, "imported_at is first-import-wins, like synced_at");
- assert_eq!(second.ride.key, first.ride.key);
- assert_eq!(
- std::fs::metadata(archive.join(&first.ride.ride_file)).unwrap().modified().unwrap(),
- ride_mtime,
- "the ride file was not rewritten"
- );
- assert_eq!(lib.load().rides.len(), 1, "one record, not two");
- assert_eq!(durable_ids(&lib, "OBC-24-000317", 0xa1b2c3d4), vec![7]);
-
- let _ = std::fs::remove_dir_all(&base);
- }
-
- /// The visible folder holds GPX and nothing else; the archive holds the object and the
- /// index.
- #[test]
- fn an_import_leaves_only_gpx_in_the_visible_folder() {
- let base = temp("split");
- let lib = library(&base);
- let landed = lib.import(&request("S", 1, 1, "Split")).expect("import");
-
- assert_eq!(file_names(&base.join("rides")), vec![landed.ride.gpx_file.clone()]);
- let mut archived = vec![INDEX_FILE.to_string(), landed.ride.ride_file.clone()];
- archived.sort();
- assert_eq!(file_names(&base.join("archive")), archived);
- assert!(landed.ride.ride_path.starts_with(base.join("archive").to_str().unwrap()));
- assert!(landed.ride.gpx_path.starts_with(base.join("rides").to_str().unwrap()));
-
- let _ = std::fs::remove_dir_all(&base);
- }
-
- /// The power goes out between `write()` and `fsync()`. The real `import` runs, and what is
- /// checked is what a restart then sees, because that is what the ack list is computed from. The
- /// ride must be absent from it, so the device is never told and the next pull fetches it
- /// again.
- #[test]
- fn a_crash_between_write_and_fsync_leaves_the_ride_unacked() {
- let base = temp("crash");
- let good = request("OBC-24-000317", 7, 1, "Landed");
- let lost = request("OBC-24-000317", 7, 2, "Interrupted");
-
- library(&base).import(&good).expect("the first ride lands");
-
- let err = Library::crashing_at(base.join("rides"), base.join("archive"), CrashPoint::BeforeObjectFsync)
- .import(&lost)
- .expect_err("a crash before fsync must not report success");
- assert!(err.contains(CRASH_MSG), "unexpected failure: {err}");
-
- // Restart: a new Library over the same folders, reading the index a relaunched app would
- // read.
- let restarted = library(&base);
- assert_eq!(
- durable_ids(&restarted, "OBC-24-000317", 7),
- vec![1],
- "only the fsynced ride is ackable; the interrupted one is not"
- );
- assert!(
- !base.join("archive").join(format!("2025-12-01-Interrupted.{RIDE_EXT}")).exists(),
- "nothing was committed under the destination name"
- );
- assert_eq!(restarted.load().rides.len(), 1, "the index never learned about the lost ride");
-
- // The next pull, with the power on, lands it and only then makes it ackable.
- library(&base).import(&lost).expect("the retry lands");
- assert_eq!(durable_ids(&library(&base), "OBC-24-000317", 7), vec![1, 2]);
-
- let _ = std::fs::remove_dir_all(&base);
- }
-
- /// The other half of the ordering: the files are durable and the index never committed. The
- /// ride is still not ackable, and the retry repairs the record without minting a second one.
- #[test]
- fn a_crash_before_the_index_commits_also_leaves_the_ride_unacked() {
- let base = temp("crash-index");
- let req = request("OBC-24-000317", 7, 3, "Half landed");
-
- Library::crashing_at(base.join("rides"), base.join("archive"), CrashPoint::BeforeIndexCommit)
- .import(&req)
- .expect_err("crash");
- let restarted = library(&base);
- assert!(durable_ids(&restarted, "OBC-24-000317", 7).is_empty(), "an uncommitted index acks nothing");
- assert!(base.join("archive").join(format!("2025-12-01-Half landed.{RIDE_EXT}")).exists(), "the bytes did land");
-
- let retry = restarted.import(&req).expect("the retry commits");
- assert!(retry.imported);
- assert_eq!(restarted.load().rides.len(), 1, "the retry did not mint a second record");
-
- let _ = std::fs::remove_dir_all(&base);
- }
-
- /// Card identities that share their first 32 bits must keep recycled object ids distinct.
- #[test]
- fn a_card_change_with_a_recycled_id_keeps_both_rides() {
- let base = temp("store_id");
- let lib = library(&base);
- let serial = "OBC-24-000317";
-
- let old =
- lib.import(&request(serial, 0xa1b2c3d4_00000000_00000000_00000000, 1, "Old era ride")).expect("old era");
- let new =
- lib.import(&request(serial, 0xa1b2c3d4_00000000_00000000_00000001, 1, "New era ride")).expect("new era");
-
- assert!(old.imported && new.imported, "the recycled id is a different ride, not a duplicate");
- assert_ne!(old.ride.key, new.ride.key);
- assert_ne!(old.ride.ride_file, new.ride.ride_file, "and it gets its own file");
- assert_eq!(lib.load().rides.len(), 2);
-
- // Each era acks only its own ids. The old era's record is archival: it names a ride the
- // device no longer has, and nothing in the new era may claim it.
- assert_eq!(durable_ids(&lib, serial, 0xa1b2c3d4_00000000_00000000_00000000), vec![1]);
- assert_eq!(durable_ids(&lib, serial, 0xa1b2c3d4_00000000_00000000_00000001), vec![1]);
- // A different device with the same id is a third ride again.
- assert!(durable_ids(&lib, "OBC-24-000999", 0xa1b2c3d4_00000000_00000000_00000001).is_empty());
-
- let _ = std::fs::remove_dir_all(&base);
- }
-
- /// What the device is told matches what is on the disk, including after something deletes an
- /// archive file, which `present` must notice.
- #[test]
- fn durable_ids_follow_the_filesystem_not_the_index() {
- let base = temp("present");
- let lib = library(&base);
- let serial = "OBC-24-000317";
- for id in [4u64, 5, 6] {
- lib.import(&request(serial, 9, id, &format!("Ride {id}"))).expect("import");
- }
- assert_eq!(durable_ids(&lib, serial, 9), vec![4, 5, 6]);
-
- let gone = lib.load().rides.iter().find(|r| r.object_id == 5).expect("ride 5").ride_file.clone();
- std::fs::remove_file(base.join("archive").join(&gone)).expect("delete the archive file");
-
- assert_eq!(durable_ids(&lib, serial, 9), vec![4, 6], "a deleted ride is not durable and is not acked");
- let listed = lib.entries();
- assert_eq!(listed.len(), 3, "the record survives so the UI can say the file is missing");
- assert!(!listed.iter().find(|r| r.object_id == 5).unwrap().present);
-
- let _ = std::fs::remove_dir_all(&base);
- }
-
- #[test]
- fn a_missing_gpx_is_repaired_without_re_downloading_the_ride() {
- let base = temp("regpx");
- let lib = library(&base);
- let landed = lib.import(&request("S", 1, 8, "Export me")).expect("import");
- std::fs::remove_file(base.join("rides").join(&landed.ride.gpx_file)).expect("delete the gpx");
- assert!(!lib.entries()[0].gpx_present);
-
- let object = lib.read_object(&landed.ride.key).expect("the archive is still there");
- assert_eq!(object, request("S", 1, 8, "Export me").object);
- lib.write_gpx(&landed.ride.key, "rebuilt ").expect("re-export");
- assert!(lib.entries()[0].gpx_present);
- assert_eq!(
- std::fs::read_to_string(base.join("rides").join(&landed.ride.gpx_file)).unwrap(),
- "rebuilt "
- );
-
- let _ = std::fs::remove_dir_all(&base);
- }
-
- #[test]
- fn a_corrupt_index_reads_as_empty_rather_than_as_nonsense() {
- let base = temp("corrupt");
- let lib = library(&base);
- lib.import(&request("S", 1, 1, "A ride")).expect("import");
- std::fs::write(base.join("archive").join(INDEX_FILE), b"{ this is not json").expect("corrupt it");
-
- assert!(lib.load().rides.is_empty(), "an unreadable index is an empty library");
- assert!(durable_ids(&lib, "S", 1).is_empty(), "and acks nothing — the safe direction");
- // The files are still there, so the next pull re-imports over them.
- assert!(lib.import(&request("S", 1, 1, "A ride")).expect("re-import").imported);
-
- let _ = std::fs::remove_dir_all(&base);
- }
-
- #[test]
- fn two_rides_that_want_the_same_filename_get_different_ones() {
- let base = temp("stems");
- let lib = library(&base);
- let a = lib.import(&request("S", 1, 11, "Commute")).expect("a");
- let b = lib.import(&request("S", 1, 12, "Commute")).expect("b");
- assert_ne!(a.ride.ride_file, b.ride.ride_file);
- assert_eq!(a.ride.ride_file, format!("2025-12-01-Commute.{RIDE_EXT}"));
- assert_eq!(b.ride.ride_file, format!("2025-12-01-Commute-12.{RIDE_EXT}"));
- let _ = std::fs::remove_dir_all(&base);
- }
-
- #[test]
- fn a_ride_name_can_never_name_a_place() {
- let req = request("S", 1, 1, "../../.ssh/authorized_keys");
- let stem = stem_for(&req);
- assert!(!stem.contains('/') && !stem.contains('\\') && !stem.contains(".."), "{stem}");
- assert_eq!(stem, "2025-12-01-authorized_keys");
- assert_eq!(stem_for(&request("S", 1, 1, "")), "2025-12-01-ride");
- }
-
- #[test]
- fn dates_are_utc_and_absent_when_the_device_had_no_clock() {
- assert_eq!(utc_date(0), None);
- assert_eq!(utc_date(1).as_deref(), Some("1970-01-01"));
- assert_eq!(utc_date(1_764_547_200).as_deref(), Some("2025-12-01"));
- assert_eq!(utc_date(1_767_225_599).as_deref(), Some("2025-12-31"));
- assert_eq!(utc_date(1_767_225_600).as_deref(), Some("2026-01-01"));
- // A leap day, and the last instant a u32 can hold.
- assert_eq!(utc_date(1_709_164_800).as_deref(), Some("2024-02-29"));
- assert_eq!(utc_date(u32::MAX).as_deref(), Some("2106-02-07"));
- }
-
- #[test]
- fn the_key_uses_full_store_hex_and_decimal_u64() {
- let store = "a1b2c3d4000000000000000000000000";
- for id in [65536, 9007199254740993, u64::MAX] {
- assert_eq!(ride_key("OBC-24-000317", store, id), format!("OBC-24-000317:{store}:{id}"));
- }
- assert_eq!(ride_key("a:b", store, 2), "a:b:a1b2c3d4000000000000000000000000:2");
- }
-
- fn json_request() -> serde_json::Value {
- serde_json::json!({
- "serial": "OBC-24-000317",
- "storeId": "a1b2c3d4000000000000000000000000",
- "objectId": "65536",
- "name": "Same name",
- "startTime": 1764547200_u32,
- "distanceM": 42195,
- "movingTimeS": 7200,
- "climbM": 640,
- "points": 1,
- "crc32": 0,
- "track": [],
- "object": [1, 2, 3],
- "gpx": " "
- })
- }
-
- #[test]
- fn json_identity_survives_import_reload_and_duplicate_detection() {
- let base = temp("full-identity");
- for store in ["a1b2c3d4000000000000000000000000", "a1b2c3d4000000000000000000000001"] {
- for id in ["65536", "9007199254740993", "18446744073709551615"] {
- let mut json = json_request();
- json["storeId"] = store.into();
- json["objectId"] = id.into();
- let req: ImportRequest = serde_json::from_value(json).expect("JSON request");
- let landed = library(&base).import(&req).expect("import");
- assert!(landed.imported);
- assert_eq!(landed.ride.key, format!("OBC-24-000317:{store}:{id}"));
- let reply = serde_json::to_value(&landed).expect("JSON response");
- assert_eq!(reply["ride"]["storeId"], store);
- assert_eq!(reply["ride"]["objectId"], id);
- assert!(!library(&base).import(&req).expect("reload and repeat").imported);
- }
- }
- let rides = library(&base).view(false).rides;
- assert_eq!(rides.len(), 6);
- assert!(rides.iter().all(|r| r.present && r.gpx_present));
- let _ = std::fs::remove_dir_all(base);
- }
-
- #[test]
- fn malformed_json_identity_is_refused_before_file_creation() {
- let base = temp("invalid-identity");
- for field in ["storeId", "objectId"] {
- let invalid = if field == "storeId" {
- vec![
- serde_json::json!(7),
- serde_json::json!(null),
- "".into(),
- "a1b2c3d4".into(),
- "A1B2C3D4000000000000000000000000".into(),
- "g1b2c3d4000000000000000000000000".into(),
- ]
- } else {
- vec![
- serde_json::json!(65536),
- serde_json::json!(null),
- "".into(),
- "0".into(),
- "-1".into(),
- "+1".into(),
- "01".into(),
- "1.0".into(),
- "1e3".into(),
- "18446744073709551616".into(),
- ]
- };
- for value in invalid {
- let mut json = json_request();
- json[field] = value;
- assert!(serde_json::from_value::(json).is_err(), "invalid {field}");
- }
- }
- let mut req = request("S", 1, 1, "Bad card");
- req.store_id = "invalid".into();
- assert!(library(&base).import(&req).is_err());
- assert!(file_names(&base).is_empty());
- let _ = std::fs::remove_dir_all(base);
- }
-
- #[test]
- fn an_old_index_never_overwrites_archived_objects_or_gpx() {
- let base = temp("old-index");
- let req = request("S", 1, 1, "Same name");
- let old = library(&base).import(&req).unwrap();
- let object_path = PathBuf::from(&old.ride.ride_path);
- let gpx_path = PathBuf::from(&old.ride.gpx_path);
- let mut index: serde_json::Value =
- serde_json::from_slice(&std::fs::read(base.join("archive").join(INDEX_FILE)).unwrap()).unwrap();
- index["version"] = 1.into();
- index["rides"][0].as_object_mut().unwrap().remove("storeId");
- index["rides"][0]["epoch"] = 1.into();
- index["rides"][0]["objectId"] = 1.into();
- std::fs::write(base.join("archive").join(INDEX_FILE), serde_json::to_vec(&index).unwrap()).unwrap();
- assert!(library(&base).view(false).rides.is_empty());
- let mut new_req = req.clone();
- new_req.object = b"different ride".to_vec();
- new_req.gpx = "different ride ".into();
- let new = library(&base).import(&new_req).unwrap();
- assert!(new.imported);
- assert_ne!(new.ride.ride_path, old.ride.ride_path);
- assert_ne!(new.ride.gpx_path, old.ride.gpx_path);
- assert_eq!(std::fs::read(object_path).unwrap(), req.object);
- assert_eq!(std::fs::read_to_string(gpx_path).unwrap(), req.gpx);
- let _ = std::fs::remove_dir_all(base);
- }
-
- #[test]
- fn oversized_and_empty_imports_are_refused_before_anything_is_written() {
- let base = temp("limits");
- let lib = library(&base);
- let mut req = request("S", 1, 1, "Huge");
- req.object = vec![0; MAX_RIDE_BYTES + 1];
- assert!(lib.import(&req).is_err());
- let mut req = request("S", 1, 1, "Empty");
- req.object.clear();
- assert!(lib.import(&req).is_err());
- let mut req = request("", 1, 1, "No serial");
- req.serial.clear();
- assert!(lib.import(&req).is_err(), "a device with no serial cannot key a ride");
- assert!(lib.load().rides.is_empty(), "nothing was written");
- let _ = std::fs::remove_dir_all(&base);
- }
-
- /// `present` is not bare existence: a truncated archive file must read as not durable, drop out
- /// of the ack list, and be repaired by the next pull.
- #[test]
- fn a_truncated_archive_is_not_durable_and_is_repaired() {
- let base = temp("truncated");
- let lib = library(&base);
- let landed = lib.import(&request("S", 1, 4, "Torn")).expect("import");
- assert_eq!(durable_ids(&lib, "S", 1), vec![4]);
-
- let path = base.join("archive").join(&landed.ride.ride_file);
- let whole = std::fs::read(&path).expect("read");
- std::fs::write(&path, &whole[..whole.len() / 2]).expect("truncate");
-
- assert!(durable_ids(&lib, "S", 1).is_empty(), "a torn file acks nothing");
- assert!(!lib.entries()[0].present, "…and the UI sees it as missing");
-
- let repaired = lib.import(&request("S", 1, 4, "Torn")).expect("the next pull repairs it");
- assert!(!repaired.imported, "the same ride arriving again, not a new one");
- assert_eq!(durable_ids(&lib, "S", 1), vec![4]);
- assert_eq!(std::fs::read(&path).expect("whole again"), whole);
-
- let _ = std::fs::remove_dir_all(&base);
- }
-
- // Relocation.
-
- #[test]
- fn relocating_moves_the_gpx_files_and_only_them() {
- let base = temp("move");
- let from = base.join("old");
- let to = base.join("new");
-
- let lib = Library::new(from.clone(), base.join("archive"));
- let landed = lib.import(&request("S", 1, 1, "Travelling")).expect("import");
-
- assert!(relocate(&from, &from.join("inside")).is_err(), "a move into itself is not a move");
-
- relocate(&from, &to).expect("relocate");
- let moved = Library::new(to.clone(), base.join("archive"));
- assert_eq!(durable_ids(&moved, "S", 1), vec![1], "the archive did not move, so nothing was lost");
- assert!(to.join(&landed.ride.gpx_file).is_file());
- assert!(moved.entries()[0].gpx_present);
- assert!(!from.exists(), "the old folder is gone once it is empty");
-
- // Moving into a folder the app has never used works, and a second relocate from an already
- // moved source is a no-op rather than an error.
- relocate(&from, &base.join("third")).expect("nothing to move");
-
- let _ = std::fs::remove_dir_all(&base);
- }
-
- #[test]
- fn relocating_refuses_to_overwrite_a_same_named_file() {
- let base = temp("move-collide");
- let from = base.join("old");
- let to = base.join("new");
- let lib = Library::new(from.clone(), base.join("archive"));
- let landed = lib.import(&request("S", 1, 1, "Collides")).expect("import");
- std::fs::create_dir_all(&to).expect("to");
- std::fs::write(to.join(&landed.ride.gpx_file), b"someone else's file").expect("occupy");
-
- assert!(relocate(&from, &to).is_err(), "an existing file is never overwritten");
- assert!(from.join(&landed.ride.gpx_file).is_file(), "and the source did not move");
-
- let _ = std::fs::remove_dir_all(&base);
- }
-
- #[test]
- fn the_configured_location_survives_a_restart() {
- let base = temp("location");
- let config = base.join("config");
- assert_eq!(configured(&config), None);
- remember(&config, &base.join("rides")).expect("remember");
- assert_eq!(configured(&config), Some(base.join("rides")));
- let _ = std::fs::remove_dir_all(&base);
- }
-}
diff --git a/builder/desktop/src/usb/mod.rs b/builder/desktop/src/usb/mod.rs
deleted file mode 100644
index b587f7a166..0000000000
--- a/builder/desktop/src/usb/mod.rs
+++ /dev/null
@@ -1,252 +0,0 @@
-//! Native USB: `nusb` under the shared byte-pipe seam.
-//!
-//! Tauri's webview has no WebUSB, so the desktop app drives USB itself. This is the only universal
-//! USB path, and it is what a Safari or Firefox user installs the app for.
-//!
-//! The protocol is not reimplemented here. The object model, the descriptor codecs, the
-//! whole-object CRC and the client live once, in TypeScript, over a pluggable `BytePipe`, so a
-//! second host drops a transport underneath them instead of growing a parallel implementation that
-//! drifts from a byte-exact wire contract. This module moves bytes and nothing else: every `0x` in
-//! the non-test code is USB's own vocabulary, a vendor id, a product id, an interface class or an
-//! endpoint-address direction bit.
-//!
-//! The control plane carries the protocol's control records and the stream plane carries its stream
-//! records, both over IPC.
-//!
-//! There is no path that streams a file straight from disk into the endpoint. A record stream is
-//! framed, and a raw byte streamer cannot produce one without a second implementation of the wire
-//! contract. If a measurement ever says the IPC boundary is the bottleneck, the honest shape is a
-//! Rust-side record sender that shares the codec.
-//!
-//! Both IPC directions carry raw binary and not JSON: a command result is [`tauri::ipc::Response`]
-//! and a write arrives as [`tauri::ipc::InvokeBody::Raw`] with its handle and plane in headers. A
-//! `Vec` argument would be serialised as a JSON array of numbers, about four bytes of text per
-//! byte of payload.
-//!
-//! The window has no filesystem capability. A file the rider picks arrives through the webview as a
-//! `File` with no path at all, exactly as it does on the web.
-
-pub mod runtime_guard;
-pub mod watch;
-
-use std::collections::HashMap;
-use std::sync::atomic::{AtomicU32, Ordering};
-use std::sync::{Arc, Mutex};
-
-use tauri::ipc::{Channel, InvokeBody, Request, Response};
-use tauri::State;
-
-use obc_usb::{Dir, OpenLink, OpenedLink, PipeFault, Plane};
-use watch::{DeviceSummary, UsbEvent};
-
-pub use obc_usb::{PRODUCT_ID, VENDOR_ID};
-
-/// Every device this app has open, plus the one hot-plug watch behind them.
-#[derive(Default)]
-pub struct UsbState {
- links: Mutex>>,
- next_handle: AtomicU32,
- /// Where the watch task sends events. Replaceable, so a window that reloaded re-points the
- /// existing watch at its new channel instead of starting a second one.
- sink: Mutex>>,
- watching: Mutex,
-}
-
-impl UsbState {
- fn link(&self, handle: u32) -> Result, PipeFault> {
- self.links
- .lock()
- .expect("usb links")
- .get(&handle)
- .cloned()
- .ok_or_else(|| PipeFault::closed("The device link is closed."))
- }
-
- /// Fail and forget every link on a device that has gone away.
- fn disconnected(&self, device_id: &str) {
- let mut links = self.links.lock().expect("usb links");
- links.retain(|_, link| {
- if link.device_id == device_id {
- link.cancel_all();
- false
- } else {
- true
- }
- });
- }
-
- fn drop_all(&self) {
- for (_, link) in self.links.lock().expect("usb links").drain() {
- link.cancel_all();
- }
- }
-}
-
-/// Start or re-point the hot-plug watch and report what is attached now.
-///
-/// It answers the matching devices after the watch is live, which is the order that cannot miss a
-/// device plugged in during the call.
-///
-/// Any link left over from a previous page load is dropped first. A reloaded window has no handles
-/// but the backend still holds the interface claim, and a stale claim is what makes the next
-/// `usb_open` fail as busy.
-#[tauri::command]
-pub async fn usb_watch(
- state: State<'_, Arc>,
- on_event: Channel,
-) -> Result, String> {
- let state = Arc::clone(&state);
- state.drop_all();
- *state.sink.lock().expect("usb sink") = Some(on_event);
-
- {
- let mut watching = state.watching.lock().expect("usb watching");
- if !*watching {
- *watching = true;
- let for_events = Arc::clone(&state);
- let for_disconnect = Arc::clone(&state);
- // One long-lived watch serves a window that reloads, because the task resolves the
- // sink per event rather than capturing the channel it was born with.
- watch::spawn(
- Arc::new(move |event: UsbEvent| {
- if let Some(channel) = for_events.sink.lock().expect("usb sink").as_ref() {
- let _ = channel.send(event);
- }
- }),
- Arc::new(move |device_id: &str| for_disconnect.disconnected(device_id)),
- );
- }
- }
-
- watch::list().await
-}
-
-/// The matching devices attached right now, without touching the watch. A native host has no
-/// chooser, so asking for a device is looking again.
-#[tauri::command]
-pub async fn usb_list() -> Result, String> {
- watch::list().await
-}
-
-/// Open, configure and claim a device; hand back a handle and the two pipes' packet sizes.
-#[tauri::command]
-pub async fn usb_open(state: State<'_, Arc>, device_id: String) -> Result {
- let devices =
- nusb::list_devices().await.map_err(|e| PipeFault::device(format!("USB devices could not be listed: {e}")))?;
- let info = devices
- .filter(watch::matches)
- .find(|info| watch::device_key(info.id()) == device_id)
- .ok_or_else(|| PipeFault::closed("That device is no longer attached."))?;
-
- let (link, mut opened) = obc_usb::open(&info, device_id).await?;
- let handle = state.next_handle.fetch_add(1, Ordering::Relaxed) + 1;
- opened.handle = handle;
- state.links.lock().expect("usb links").insert(handle, link);
- Ok(opened)
-}
-
-/// Release a link. Idempotent; everything parked on it settles first.
-#[tauri::command]
-pub fn usb_close(state: State<'_, Arc>, handle: u32) {
- let link = state.links.lock().expect("usb links").remove(&handle);
- // The cancel lets a pending read return instead of holding the interface claim until the
- // device says something. The claim drops with the last `Arc`, which the cancelled transfers
- // hold.
- if let Some(link) = link {
- link.cancel_all();
- }
-}
-
-/// One transfer's worth of bytes off a plane's IN endpoint.
-///
-/// A read is not a message on the bulk plane: it hands back whatever the transport delivered, and
-/// the client accumulates to the length its descriptor announced.
-#[tauri::command]
-pub async fn usb_read(state: State<'_, Arc>, handle: u32, plane: Plane) -> Result {
- let link = state.link(handle)?;
- let bytes = link.plane(plane).read().await?;
- // `Response` is the raw path: the frontend gets an ArrayBuffer, not a JSON array of numbers.
- Ok(Response::new(bytes))
-}
-
-/// Write one transfer to a plane's OUT endpoint.
-///
-/// It takes the raw invoke body rather than a `Vec` argument. `handle` and `plane` ride in
-/// headers, because a raw body is the whole payload.
-#[tauri::command]
-pub async fn usb_write(state: State<'_, Arc>, request: Request<'_>) -> Result<(), PipeFault> {
- let header = |name: &str| {
- request
- .headers()
- .get(name)
- .and_then(|v| v.to_str().ok())
- .ok_or_else(|| PipeFault::device(format!("a usb_write is missing its `{name}` header.")))
- };
- let handle: u32 =
- header("handle")?.parse().map_err(|_| PipeFault::device("a usb_write carried an unreadable handle."))?;
- let plane = match header("plane")? {
- "control" => Plane::Control,
- "bulk" => Plane::Bulk,
- other => return Err(PipeFault::device(format!("a usb_write named an unknown plane `{other}`."))),
- };
- let InvokeBody::Raw(bytes) = request.body() else {
- return Err(PipeFault::device("a usb_write must carry its bytes as a raw body."));
- };
- let link = state.link(handle)?;
- link.plane(plane).write(bytes).await
-}
-
-/// Cancel whatever is parked on one direction of a plane, so the caller's `AbortSignal` reaches the
-/// transport rather than only releasing the JavaScript promise.
-#[tauri::command]
-pub fn usb_cancel(state: State<'_, Arc>, handle: u32, plane: Plane, dir: Option) {
- if let Ok(link) = state.link(handle) {
- link.plane(plane).cancel(dir);
- }
-}
-
-/// Return a plane to a known-empty state.
-#[tauri::command]
-pub async fn usb_reset(state: State<'_, Arc>, handle: u32, plane: Plane) -> Result<(), PipeFault> {
- state.link(handle)?.plane(plane).reset().await
-}
-
-#[cfg(test)]
-mod tests {
- /// The policy without a Tauri app handle: the same canonicalise-then-prefix rule, over a real
- /// temp tree so the symlink case is real.
- fn allowed(root: &std::path::Path, candidate: &std::path::Path) -> bool {
- let (Ok(root), Ok(candidate)) = (std::fs::canonicalize(root), std::fs::canonicalize(candidate)) else {
- return false;
- };
- candidate.is_file() && candidate.starts_with(&root)
- }
-
- #[test]
- fn only_files_inside_an_app_owned_root_are_sendable() {
- let base = std::env::temp_dir().join(format!("obc-usb-policy-{}", std::process::id()));
- let root = base.join("maps");
- let outside = base.join("elsewhere");
- std::fs::create_dir_all(&root).expect("root");
- std::fs::create_dir_all(&outside).expect("outside");
- std::fs::write(root.join("ok.obcm"), b"x").expect("write");
- std::fs::write(outside.join("secret"), b"x").expect("write");
-
- assert!(allowed(&root, &root.join("ok.obcm")));
- assert!(!allowed(&root, &outside.join("secret")));
- // The traversal a prefix check alone would admit, and canonicalising does not.
- assert!(!allowed(&root, &root.join("../elsewhere/secret")));
- // A directory is not a file.
- assert!(!allowed(&root, &root));
-
- #[cfg(unix)]
- {
- // Why both sides are canonicalised: a symlink inside the root that points out of it
- // resolves to its target, and the target fails the prefix check.
- let link = root.join("escape");
- std::os::unix::fs::symlink(outside.join("secret"), &link).expect("symlink");
- assert!(!allowed(&root, &link));
- }
- let _ = std::fs::remove_dir_all(&base);
- }
-}
diff --git a/builder/desktop/src/usb/runtime_guard.rs b/builder/desktop/src/usb/runtime_guard.rs
deleted file mode 100644
index 5b86155c3a..0000000000
--- a/builder/desktop/src/usb/runtime_guard.rs
+++ /dev/null
@@ -1,51 +0,0 @@
-//! A test that the cargo feature which makes `nusb` usable from an async context is still on.
-//!
-//! `nusb` returns [`MaybeFuture`](nusb::MaybeFuture) rather than a plain future, so the same call
-//! serves a blocking caller and an async one. The async arm needs somewhere to put the blocking
-//! syscall, and which executor that is comes from the `smol` or `tokio` cargo feature. With neither
-//! enabled, `BlockingTask::spawn` panics. That is not a compile error: the crate builds, clippy is
-//! happy, and every `.await` on a `nusb` future panics the first time a real device is touched.
-//!
-//! What enforces it: Windows builds `list_devices()` from a blocking arm, so awaiting it reaches
-//! the panic with no device attached, and the Windows CI leg fails if the feature is dropped. Linux
-//! and macOS build the same call from a ready arm, so only the second half of this module covers
-//! them, and that half runs only where a device is plugged in.
-
-#[cfg(test)]
-mod tests {
- /// Await a `nusb` `MaybeFuture` and require it not to panic.
- ///
- /// `list_devices()` is the only entry point that needs no hardware, so it is the one a CI
- /// machine can run. The assertion is about reaching the result and not about its contents: a
- /// machine with no USB devices is a legitimate pass.
- #[tokio::test]
- async fn awaiting_nusb_does_not_panic() {
- let devices = nusb::list_devices().await.expect("the USB bus should be enumerable");
- // Draining it proves this is a real iterator and not an unpolled future.
- let count = devices.count();
- println!("nusb enumerated {count} device(s)");
- }
-
- /// The half that covers macOS and Linux, on any machine with the device plugged in.
- ///
- /// Opening is blocking on all three platforms, so this reaches the panicking arm everywhere. It
- /// skips loudly when the device is absent, because a silent skip would read as coverage that
- /// does not exist.
- #[tokio::test]
- async fn opening_the_device_does_not_panic() {
- let Some(info) = nusb::list_devices()
- .await
- .expect("the USB bus should be enumerable")
- .find(|d| d.vendor_id() == super::super::VENDOR_ID && d.product_id() == super::super::PRODUCT_ID)
- else {
- println!("no OpenBikeComputer attached — skipping (this half needs hardware)");
- return;
- };
- // The failure this guards is a panic, not an `Err`. A device held open by the app is an
- // ordinary `Err` and must not fail the test.
- match info.open().await {
- Ok(_) => println!("opened the device"),
- Err(e) => println!("device present but not openable ({e}) — the await itself is what mattered"),
- }
- }
-}
diff --git a/builder/desktop/src/usb/watch.rs b/builder/desktop/src/usb/watch.rs
deleted file mode 100644
index 902d4dcc7c..0000000000
--- a/builder/desktop/src/usb/watch.rs
+++ /dev/null
@@ -1,130 +0,0 @@
-//! Discovery and hot-plug: what makes plugging a cable in light the window up.
-//!
-//! Plugging in must light up the UI within about a second, and unplugging must not leave a stuck
-//! spinner. The browser gets that from `navigator.usb`'s events; here it comes from the OS
-//! notification streams nusb wraps, which are edge-driven rather than polled, so the latency budget
-//! is spent on the device side.
-//!
-//! A native host has no chooser and no permission prompt, so it sees the device the moment it
-//! appears. The session shape stays the same as the browser's anyway: `requestDevice()` here is
-//! looking again, so the same button keeps working and no UI branches on the transport.
-
-use std::sync::Arc;
-
-use futures_core::Stream;
-use nusb::hotplug::HotplugEvent;
-use nusb::DeviceInfo;
-use serde::Serialize;
-
-use super::{PRODUCT_ID, VENDOR_ID};
-
-/// A device the app is willing to talk to, as the frontend sees it.
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DeviceSummary {
- /// Opaque and stable for as long as the device stays plugged in: the key `usb_open` takes and
- /// the key a `disconnected` event carries. Never parsed by the frontend.
- pub id: String,
- pub vendor_id: u16,
- pub product_id: u16,
- pub product: Option,
- /// The nRF `FICR.DEVICEID`, which is what tells two boards apart.
- pub serial_number: Option,
-}
-
-/// What the watch task tells the frontend.
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase", tag = "type")]
-pub enum UsbEvent {
- Connected {
- device: DeviceSummary,
- },
- Disconnected {
- id: String,
- },
- /// The OS notification stream ended or could not be started. Reported rather than swallowed: a
- /// watch that died silently looks like nothing ever being plugged in.
- WatchFailed {
- message: String,
- },
-}
-
-/// The frontend's handle on a device, stable for the life of the connection.
-///
-/// `DeviceId` is opaque and platform-specific in shape, so it is stringified rather than
-/// interpreted. The only property anything depends on is that one physical connection produces the
-/// same string in a `connected` event, in `usb_list` and in the matching `disconnected`.
-pub fn device_key(id: nusb::DeviceId) -> String {
- format!("{id:?}")
-}
-
-/// Is this one of ours?
-///
-/// The pair is pid.codes' prototype and testing range, and the firmware declares the same one.
-/// Allocating a real product id moves this constant, the firmware's `PRODUCT_ID` and the web
-/// filters together.
-pub fn matches(info: &DeviceInfo) -> bool {
- info.vendor_id() == VENDOR_ID && info.product_id() == PRODUCT_ID
-}
-
-pub fn summarize(info: &DeviceInfo) -> DeviceSummary {
- DeviceSummary {
- id: device_key(info.id()),
- vendor_id: info.vendor_id(),
- product_id: info.product_id(),
- product: info.product_string().map(str::to_owned),
- serial_number: info.serial_number().map(str::to_owned),
- }
-}
-
-/// Every matching device attached right now.
-pub async fn list() -> Result, String> {
- let devices = nusb::list_devices().await.map_err(|e| format!("USB devices could not be listed: {e}"))?;
- Ok(devices.filter(matches).map(|info| summarize(&info)).collect())
-}
-
-/// What the watch task hands its events to.
-///
-/// A closure rather than a [`Channel`], because the channel is replaceable: a window that reloads
-/// opens a new one, and the watch outlives the page.
-pub type Emit = Arc;
-
-/// Follow hot-plug forever.
-///
-/// `on_disconnect` runs before the event reaches the frontend, and that ordering matters: it is
-/// where the pipes of a link on the vanished device are failed, so an in-flight transfer's UI says
-/// unplugged now instead of spinning until a timeout.
-pub fn spawn(emit: Emit, on_disconnect: Arc) {
- // Created before the caller lists devices: a device attached in the window between listing
- // and watching would otherwise be missed.
- let mut watch = match nusb::watch_devices() {
- Ok(watch) => watch,
- Err(e) => {
- emit(UsbEvent::WatchFailed { message: format!("USB hot-plug is unavailable: {e}") });
- return;
- }
- };
- tauri::async_runtime::spawn(async move {
- loop {
- let event = std::future::poll_fn(|cx| std::pin::Pin::new(&mut watch).poll_next(cx)).await;
- let Some(event) = event else {
- emit(UsbEvent::WatchFailed { message: "The system stopped reporting USB device changes.".into() });
- return;
- };
- match event {
- HotplugEvent::Connected(info) if matches(&info) => {
- emit(UsbEvent::Connected { device: summarize(&info) });
- }
- HotplugEvent::Connected(_) => {}
- HotplugEvent::Disconnected(id) => {
- // Not filtered by vendor and product id: a disconnect carries only an id, and
- // an id with no link is a no-op on both sides. Filtering here would mean
- // keeping a device table only to discard events that are already ignored.
- let key = device_key(id);
- on_disconnect(&key);
- emit(UsbEvent::Disconnected { id: key });
- }
- }
- }
- });
-}
diff --git a/builder/desktop/tauri.conf.json b/builder/desktop/tauri.conf.json
deleted file mode 100644
index be82ac6bc2..0000000000
--- a/builder/desktop/tauri.conf.json
+++ /dev/null
@@ -1,40 +0,0 @@
-{
- "$schema": "https://schema.tauri.app/config/2",
- "productName": "OpenBikeComputer",
- "version": "0.1.0",
- "identifier": "de.timohueser.openbikecomputer",
- "build": {
- "frontendDist": "../web/dist/desktop",
- "devUrl": "http://localhost:5173",
- "beforeDevCommand": "npm --prefix ../web run dev -- --mode desktop",
- "beforeBuildCommand": "npm --prefix ../web run build:desktop"
- },
- "app": {
- "windows": [
- {
- "label": "main",
- "title": "OpenBikeComputer",
- "width": 1360,
- "height": 900,
- "minWidth": 900,
- "minHeight": 620,
- "dragDropEnabled": false
- }
- ],
- "security": {
- "csp": "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'wasm-unsafe-eval'; connect-src 'self' ipc: http://ipc.localhost https://tiles.openbikecomputer.com https://maps.openbikecomputer.com"
- }
- },
- "bundle": {
- "active": true,
- "targets": "all",
- "icon": [
- "icons/32x32.png",
- "icons/128x128.png",
- "icons/128x128@2x.png",
- "icons/icon.ico",
- "icons/icon.icns",
- "icons/icon.png"
- ]
- }
-}
diff --git a/builder/server/schema_preview.py b/builder/server/schema_preview.py
index 825e3a2ccf..b33ffbcf76 100644
--- a/builder/server/schema_preview.py
+++ b/builder/server/schema_preview.py
@@ -1,6 +1,6 @@
"""Bounded native packing for the localhost maintainer schema lab.
-The product web and desktop hosts never import or expose this module. The
+The product web host never imports or exposes this module. The
FastAPI maintainer host accepts only a JSON config; the source, binary, crop,
command line, output path and resource bounds all remain server-owned.
"""
diff --git a/builder/usb/Cargo.toml b/builder/usb/Cargo.toml
index 4a7192d255..4e4c9528b5 100644
--- a/builder/usb/Cargo.toml
+++ b/builder/usb/Cargo.toml
@@ -3,13 +3,12 @@ name = "obc-usb"
version = "0.1.0"
edition = "2021"
publish = false
-description = "Shared native USB byte transport and maintenance CLI for OpenBikeComputer"
+description = "Native USB byte transport and card-format CLI for OpenBikeComputer"
[dependencies]
getrandom = { workspace = true }
nusb = { version = "=0.2.5", features = ["tokio"] }
obc-link = { workspace = true, features = ["client"] }
-serde = { workspace = true, features = ["derive"] }
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "sync", "time"] }
[dev-dependencies]
diff --git a/builder/usb/README.md b/builder/usb/README.md
new file mode 100644
index 0000000000..711818ec0e
--- /dev/null
+++ b/builder/usb/README.md
@@ -0,0 +1,24 @@
+# obc-usb
+
+The native USB byte transport and the flat-store client over it, for a computer that talks to the
+device over the cable. Its one program is `obc-format-card`, which `obc format-card` runs.
+
+## Linux USB permission
+
+macOS and Windows need no setup. On Linux, the USB device node belongs to root, so a program
+cannot open the device until a udev rule gives the person at the machine access. Chrome and Edge
+need the same rule for WebUSB.
+
+```sh
+sudo cp builder/usb/linux/99-openbikecomputer.rules /etc/udev/rules.d/
+sudo udevadm control --reload-rules
+sudo udevadm trigger
+# unplug and reconnect the device
+```
+
+## Test
+
+```sh
+obc test -p obc-usb
+obc exec cargo clippy -p obc-usb --all-targets -- -D warnings
+```
diff --git a/builder/desktop/linux/99-openbikecomputer.rules b/builder/usb/linux/99-openbikecomputer.rules
similarity index 79%
rename from builder/desktop/linux/99-openbikecomputer.rules
rename to builder/usb/linux/99-openbikecomputer.rules
index d46b583c73..e3142011cd 100644
--- a/builder/desktop/linux/99-openbikecomputer.rules
+++ b/builder/usb/linux/99-openbikecomputer.rules
@@ -1,16 +1,17 @@
-# OpenBikeComputer — let a logged-in desktop session open the device (#909).
+# OpenBikeComputer — let the person at the machine open the device over USB,
+# from Chrome or Edge (WebUSB) or from `obc format-card`.
#
# Linux is the only platform that needs anything. The device declares a
-# vendor-specific interface (class 0xFF, #889), and:
+# vendor-specific interface (class 0xFF), and:
#
# * macOS lets an application open one with no driver, no entitlement and no
# kext — IOKit hands it over as long as nothing else has claimed it.
# * Windows binds WinUSB automatically from the MS OS 2.0 BOS descriptors the
# firmware ships, so there is no .inf, no Zadig and no driver install.
# * Linux exposes it through usbfs at /dev/bus/usb/BBB/DDD, which is
-# root-owned by default. Without a rule the app can enumerate the device and
-# then fail to open it, which reads as "Permission denied" and looks like a
-# bug in the app.
+# root-owned by default. Without a rule a program can enumerate the device
+# and then fail to open it, which reads as "Permission denied" and looks like
+# a bug in the program.
#
# TAG+="uaccess" is the modern answer: systemd-logind grants the *currently
# active local session* an ACL on the node, so the person sitting at the machine
diff --git a/builder/usb/src/client/usb.rs b/builder/usb/src/client/usb.rs
index 5115d87d2b..5d1bdd9a5f 100644
--- a/builder/usb/src/client/usb.rs
+++ b/builder/usb/src/client/usb.rs
@@ -158,7 +158,7 @@ pub(super) struct UsbTransport {
impl UsbTransport {
pub(super) async fn open(info: &nusb::DeviceInfo) -> Result {
- let (link, _) = crate::open(info, format!("{:?}", info.id())).await?;
+ let link = crate::open(info).await?;
let readers = Readers::start(&link);
Ok(Self { link: Some(link), readers: Some(readers), serial: info.serial_number().map(str::to_owned) })
}
@@ -249,7 +249,7 @@ impl Transport for UsbTransport {
if devices.next().is_some() {
return Err(PipeFault::device("More than one device has the saved serial number."));
}
- if let Ok((link, _)) = crate::open(&info, format!("{:?}", info.id())).await {
+ if let Ok(link) = crate::open(&info).await {
self.readers = Some(Readers::start(&link));
self.link = Some(link);
return Ok(());
diff --git a/builder/usb/src/lib.rs b/builder/usb/src/lib.rs
index 5a2d0bd901..5622715748 100644
--- a/builder/usb/src/lib.rs
+++ b/builder/usb/src/lib.rs
@@ -1,8 +1,8 @@
//! One claimed device: endpoint discovery, and the two byte pipes over it.
//!
//! Everything here moves **bytes**. Nothing in this file knows what a transfer descriptor is, what
-//! a status envelope means, or which object an upload belongs to. The desktop app and maintenance
-//! CLI share this transport; their protocol clients sit above it.
+//! a status envelope means, or which object an upload belongs to. The protocol client in `client`
+//! sits above it.
pub mod client;
@@ -10,7 +10,6 @@ use std::sync::Arc;
use nusb::transfer::{Buffer, Bulk, Completion, In, Out, TransferError};
use nusb::{Device, DeviceInfo, Endpoint, Interface};
-use serde::{Deserialize, Serialize};
use tokio::sync::{watch, Mutex};
/// pid.codes' prototype/testing pair, shared with the board descriptors and WebUSB filter.
@@ -35,8 +34,7 @@ const USB_BINDING_MAJOR: u8 = 5;
const BULK_READ_TARGET: usize = 16 * 1024;
/// Which of the two planes a call means. The names match `lib/usb/pipe.ts`'s `DeviceLink`.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
-#[serde(rename_all = "lowercase")]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Plane {
Control,
Bulk,
@@ -44,8 +42,7 @@ pub enum Plane {
/// Which half of an endpoint pair. Cancellation is per-direction: an abort on a download must not
/// also tear down the write the caller is about to make.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
-#[serde(rename_all = "lowercase")]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Dir {
In,
Out,
@@ -53,11 +50,8 @@ pub enum Dir {
/// A transport failure, in the vocabulary `lib/usb/pipe.ts`'s `PipeError` already speaks.
///
-/// The `code` is the contract — the TS side switches on it — and the `message` is for a human.
-/// `unsupported` never appears here: it means "this browser has no WebUSB", which is exactly the
-/// condition the desktop app exists to not have.
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
+/// `unsupported` never appears here: it means "this browser has no WebUSB".
+#[derive(Debug, Clone)]
pub struct PipeFault {
/// `closed` | `aborted` | `device-error`.
pub code: &'static str,
@@ -170,10 +164,7 @@ fn check_binding_major(interface_protocol: u8, device_release: u16) -> Result<()
/// The mechanism is a `watch` channel rather than a `Notify` because the race matters: a cancel
/// that arrives between the caller deciding to abort and the read parking itself must not be lost.
/// A monotonic epoch the reader snapshots before it parks cannot miss one.
-/// that arrives between "the caller decided to abort" and "the read parked itself" must not be
-/// lost. A monotonic epoch the reader snapshots before it parks cannot miss one.
pub struct Pipe {
- pub max_packet: usize,
read_len: usize,
ep_in: Mutex>,
ep_out: Mutex>,
@@ -194,7 +185,6 @@ impl Pipe {
// OS would fail the URB anyway. Round down, floor at one packet.
let read_len = (target_read / max_packet).max(1) * max_packet;
Ok(Self {
- max_packet,
read_len,
ep_in: Mutex::new(ep_in),
ep_out: Mutex::new(ep_out),
@@ -329,10 +319,6 @@ async fn cancel_and_drain(ep: &mut Endpoin
/// The `Interface` is held for its whole life because dropping it releases the claim — nothing
/// reads it directly.
pub struct OpenLink {
- /// The stable key the frontend knows this device by; a hot-plug `Disconnected` carries the same
- /// one, which is how a pulled cable reaches the pipes without waiting for a transfer to time
- /// out.
- pub device_id: String,
pub control: Pipe,
pub bulk: Pipe,
_interface: Interface,
@@ -345,29 +331,10 @@ impl OpenLink {
Plane::Bulk => &self.bulk,
}
}
-
- /// Fail everything parked on both planes. Called on an unplug and on close.
- pub fn cancel_all(&self) {
- self.control.cancel(None);
- self.bulk.cancel(None);
- }
-}
-
-/// What `usb_open` tells the frontend about the link it just got.
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct OpenedLink {
- pub handle: u32,
- pub device_id: String,
- pub interface_number: u8,
- pub control_packet_size: usize,
- pub bulk_packet_size: usize,
- pub product: Option,
- pub serial_number: Option,
}
/// Open, configure and claim a device, returning its two pipes.
-pub async fn open(info: &DeviceInfo, device_id: String) -> Result<(Arc, OpenedLink), PipeFault> {
+pub async fn open(info: &DeviceInfo) -> Result, PipeFault> {
let device: Device = info
.open()
.await
@@ -414,23 +381,14 @@ pub async fn open(info: &DeviceInfo, device_id: String) -> Result<(Arc
let control = Pipe::new(&interface, layout.control.0, layout.control.1, layout.control.2)?;
let bulk = Pipe::new(&interface, layout.bulk.0, layout.bulk.1, BULK_READ_TARGET)?;
- let opened = OpenedLink {
- handle: 0, // filled in by the registry
- device_id: device_id.clone(),
- interface_number: layout.interface,
- control_packet_size: control.max_packet,
- bulk_packet_size: bulk.max_packet,
- product: info.product_string().map(str::to_owned),
- serial_number: info.serial_number().map(str::to_owned),
- };
- Ok((Arc::new(OpenLink { device_id, control, bulk, _interface: interface }), opened))
+ Ok(Arc::new(OpenLink { control, bulk, _interface: interface }))
}
/// The two failures whose remedy is not "try again", spelled out where they happen.
///
/// On Linux the usbfs node is root-owned unless a udev rule says otherwise, and the error the user
/// would otherwise read is a bare `Permission denied` with nothing to suggest that a one-line file
-/// fixes it (`builder/desktop/linux/`). macOS needs nothing for a vendor interface; Windows
+/// fixes it (`builder/usb/linux/`). macOS needs nothing for a vendor interface; Windows
/// binds WinUSB from the MS OS 2.0 descriptors the firmware already ships.
///
/// `Busy` is the other one, and it is not platform-specific: an interface may be claimed once, so a
@@ -439,7 +397,7 @@ pub async fn open(info: &DeviceInfo, device_id: String) -> Result<(Arc
fn permission_hint(error: &nusb::Error) -> &'static str {
match error.kind() {
nusb::ErrorKind::PermissionDenied if cfg!(target_os = "linux") => {
- " — install the udev rule from the app's `linux/` folder, then unplug and re-plug the device."
+ " — install the udev rule from `builder/usb/linux/`, then unplug and re-plug the device."
}
nusb::ErrorKind::PermissionDenied => " — this account is not allowed to open the device.",
nusb::ErrorKind::Busy => " — something else has it open. Close the other app or browser tab and try again.",
diff --git a/builder/wasm/Cargo.toml b/builder/wasm/Cargo.toml
index 03f8303bd9..5af5173397 100644
--- a/builder/wasm/Cargo.toml
+++ b/builder/wasm/Cargo.toml
@@ -12,7 +12,7 @@ crate-type = ["cdylib", "rlib"]
test-device = ["dep:obc-flat-device", "obc-link/std", "dep:obc-storage"]
[dependencies]
-obc-route = { workspace = true }
+obc-route = { workspace = true, features = ["alloc"] }
obc-formats = { workspace = true }
obcm-assemble = { workspace = true }
obc-map-scene = { workspace = true }
@@ -27,6 +27,7 @@ obc-link = { workspace = true, features = ["client"] }
obc-storage = { workspace = true, features = ["std"], optional = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
+obc-fit = { workspace = true }
wasm-bindgen = { workspace = true }
js-sys = { workspace = true }
console_error_panic_hook = { workspace = true }
diff --git a/builder/wasm/src/browser.rs b/builder/wasm/src/browser.rs
index d2c32ecdbb..76306cdeae 100644
--- a/builder/wasm/src/browser.rs
+++ b/builder/wasm/src/browser.rs
@@ -26,7 +26,6 @@ pub fn obc_builder_constants() -> Vec {
grid::MIN_CELL_LOG2 as f64,
grid::MAX_CELL_LOG2 as f64,
65_536.0,
- crate::gpx::MAX_ROUTE_POINTS as f64,
]
}
@@ -164,12 +163,6 @@ pub fn obc_gpx_read(text: &str, fallback: &str) -> Result {
serde_json::to_string(&imported).map_err(|e| error("GpxError", &e.to_string()))
}
-#[wasm_bindgen]
-pub fn obc_gpx_parse(text: &str, fallback: &str) -> Result {
- let route = crate::gpx::parse(text, fallback).map_err(|e| error("GpxError", &e))?;
- serde_json::to_string(&route).map_err(|e| error("GpxError", &e.to_string()))
-}
-
#[wasm_bindgen(js_name = IncrementalSha256)]
pub struct IncrementalSha256(Option);
diff --git a/builder/wasm/src/client_web.rs b/builder/wasm/src/client_web.rs
index b37501a4f8..6bcd13434f 100644
--- a/builder/wasm/src/client_web.rs
+++ b/builder/wasm/src/client_web.rs
@@ -3,7 +3,7 @@
use obc_link::flat::{
client::{Action, Client, Error, Event, Options, Outcome, QueryId, QueryOutcome},
wire::*,
- Ceilings, Channel, DisplayName, EntryMeta, ObjectId, ObjectKind, Revision, StoreId,
+ ArchiveSource, Ceilings, Channel, DisplayName, EntryMeta, ObjectId, ObjectKind, Revision, StoreId,
};
use serde::Deserialize;
use serde_json::{json, Value};
@@ -20,6 +20,7 @@ enum BrowserRequest {
Cancel { transfer: u32 },
Arm { id: String, revision: String },
Format { expected: String, replacement: String },
+ ArchiveRide { store: String, id: String, revision: String, length: String, crc: u32 },
}
#[derive(Deserialize)]
@@ -93,6 +94,13 @@ impl BrowserRequest {
Self::Format { expected, replacement } => {
Request::Format(FormatRequest { expected: store(&expected)?, replacement: store(&replacement)? })
}
+ Self::ArchiveRide { store: card, id, revision, length, crc } => Request::ArchiveRide(ArchiveSource {
+ store: store(&card)?,
+ id: ObjectId(number(&id)?),
+ revision: Revision(number(&revision)?),
+ payload_len: number(&length)?,
+ payload_crc: crc,
+ }),
})
}
}
@@ -158,7 +166,9 @@ fn outcome(outcome: Outcome) -> Value {
"kind": "arm", "rollbackObjectId": reserve.0.to_string(), "commitSequence": sequence.to_string(),
}),
Outcome::Format(store) => json!({"kind": "format", "storeId": store_text(store)}),
- Outcome::ArchiveRide(_) => unreachable!("The browser surface has no archive request."),
+ Outcome::ArchiveRide(result) => json!({
+ "kind": "archiveRide", "commitSequence": result.sequence.to_string(), "timestamp": result.timestamp,
+ }),
}
}
diff --git a/builder/wasm/src/convert.rs b/builder/wasm/src/convert.rs
index b207a1737b..c718cfd56d 100644
--- a/builder/wasm/src/convert.rs
+++ b/builder/wasm/src/convert.rs
@@ -3,8 +3,8 @@
//! and the two guards below are tested natively.
use obc_formats::io::{ByteSink, Error, SliceSource};
-use obc_formats::obcr::WAYPOINT_ELE_NONE;
-use obc_route::{for_each_waypoint, BikeType, RouteIndex, RouteReader, MAX_POINTS_PER_CHUNK, MAX_ROUTE_CHUNKS};
+use obc_formats::obcr::{ELEVATION_NONE, WAYPOINT_ELE_NONE, WAYPOINT_NAME_CAP};
+use obc_route::{BikeType, RoutePoint, Waypoint, MAX_POINTS_PER_CHUNK, MAX_ROUTE_CHUNKS};
/// Largest point count an `.obcr` can store, and so the ceiling [`gpx_to_obcr`] converts up to:
/// every chunk full, with consecutive chunks sharing their seam vertex.
@@ -57,8 +57,6 @@ pub enum ErrorCode {
RideNoPoints,
/// A read ran past the end of the input: the file is truncated or the upload was cut short.
InputTruncated,
- /// The bytes handed to [`obcr_to_track`] are not an OBCR route.
- NotRoute,
/// A defect in this bridge or in the shared converter.
Internal,
}
@@ -75,7 +73,6 @@ impl ErrorCode {
ErrorCode::NotRide => "not-ride",
ErrorCode::RideNoPoints => "ride-no-points",
ErrorCode::InputTruncated => "input-truncated",
- ErrorCode::NotRoute => "not-route",
ErrorCode::Internal => "internal",
}
}
@@ -114,6 +111,66 @@ pub fn gpx_to_obcr(gpx: &[u8], name: &str, bike: BikeType) -> Result, Co
Ok(sink.0)
}
+/// A waypoint of a calculated line. `distance_m` is along the line as the caller gave it, before
+/// decimation; the waypoint lies on the line.
+#[derive(Debug, Clone, PartialEq, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LineWaypoint {
+ pub lon: i32,
+ pub lat: i32,
+ pub distance_m: f64,
+ pub category: u8,
+ pub name: String,
+}
+
+/// Encode a calculated line into a `.obcr` route named `name` and typed `bike`, with the shared
+/// emitter that the phone uses. `points` are microdegrees with the height in metres;
+/// `surfaces[i]` is the surface class of the segment that ends at point `i`. A waypoint name is
+/// cut to the field on a char boundary.
+pub fn line_to_obcr(
+ points: &[(i32, i32, Option)],
+ surfaces: &[u8],
+ waypoints: &[LineWaypoint],
+ name: &str,
+ bike: BikeType,
+) -> Result, ConvertFailure> {
+ let points: Vec = points
+ .iter()
+ .enumerate()
+ .map(|(i, &(lon, lat, ele))| RoutePoint {
+ lon,
+ lat,
+ ele: ele.unwrap_or(ELEVATION_NONE),
+ surface: surfaces.get(i).copied().unwrap_or(0),
+ elevation_incomplete: ele.is_none(),
+ })
+ .collect();
+ let waypoints: Vec<(Waypoint, f64)> = waypoints
+ .iter()
+ .map(|w| {
+ let mut waypoint = Waypoint {
+ dist_along_m: 0,
+ lon: w.lon,
+ lat: w.lat,
+ ele: WAYPOINT_ELE_NONE,
+ category_id: w.category,
+ lateral_offset_m: 0,
+ name: Default::default(),
+ provenance: None,
+ };
+ for ch in w.name.chars() {
+ if waypoint.name.len() + ch.len_utf8() > WAYPOINT_NAME_CAP || waypoint.name.push(ch).is_err() {
+ break;
+ }
+ }
+ (waypoint, w.distance_m)
+ })
+ .collect();
+ let mut sink = VecSink(Vec::new());
+ obc_route::convert::points_to_obcr(&points, &waypoints, name, bike, &mut sink).map_err(describe_line_error)?;
+ Ok(sink.0)
+}
+
/// Convert a finished ride-v6 object's bytes into a GPX 1.1 document named `name`.
///
/// Byte-for-byte the same output as `obc_route::track_to_gpx`; only the buffer adapter is new.
@@ -148,111 +205,6 @@ pub fn track_to_gpx(ride: &[u8], name: &str) -> Result {
})
}
-/// Decode an `.obcr` route's polyline: flat `[lat, lon, ele]` triples in route order. A missing
-/// elevation is NaN, never a fabricated sea-level sample.
-///
-/// It reads back through the same [`RouteReader`] the firmware streams its map draw from, so what
-/// the preview traces is what the device traces. Flat `f64` triples because this crosses the wasm
-/// boundary as one `Float64Array`.
-///
-/// Chunks share their seam vertex, so every chunk after the first drops its first decoded point and
-/// the stored `point_count` is what comes back.
-pub fn obcr_to_track(obcr: &[u8]) -> Result, ConvertFailure> {
- let src = SliceSource(obcr);
- let idx = RouteIndex::read(&src).map_err(describe_route_read_error)?;
- let reader = RouteReader::new(&idx, &src);
-
- // Every chunk's bbox lies inside the route's own, so the route bbox visits them all.
- let mut chunks: Vec = Vec::new();
- idx.for_each_visible_chunk(&idx.bbox, |k, _| chunks.push(k));
- chunks.sort_unstable();
-
- let mut out: Vec = Vec::with_capacity(idx.point_count as usize * 3);
- for (i, k) in chunks.iter().enumerate() {
- let skip = usize::from(i > 0); // the shared seam vertex
- reader
- .with_chunk(*k, |points| {
- for p in points.skip(skip) {
- out.push(f64::from(p.lat) * 1e-6);
- out.push(f64::from(p.lon) * 1e-6);
- out.push(p.elevation().map_or(f64::NAN, f64::from));
- }
- })
- .map_err(|_| {
- ConvertFailure::new(
- ErrorCode::NotRoute,
- "A geometry chunk in this route failed to decode — the file is damaged.",
- )
- })?;
- }
- Ok(out)
-}
-
-/// One waypoint read back out of an `.obcr` route, with the wire encodings already unfolded:
-/// microdegrees to degrees, and the elevation sentinel to `None`.
-#[derive(Debug, Clone, PartialEq)]
-pub struct RouteWaypoint {
- /// The stored UTF-8 short name, at most 24 bytes, and possibly empty.
- pub name: String,
- /// The waypoint's own coordinate in degrees. It can sit off the polyline.
- pub lat: f64,
- pub lon: f64,
- /// Elevation in meters, or `None` where the source carried none.
- pub ele: Option,
- /// The stored category byte, raw: `0` is generic and `1..=6` are the POI category ids. A
- /// consumer renders any other value as generic.
- pub category: u8,
- /// Meters from the route start to the waypoint's position on the track: the stored field, not
- /// a recomputation.
- pub dist_along_m: u32,
-}
-
-/// Decode an `.obcr` route's waypoint table, in ascending distance order: name, position, raw
-/// category byte and along-track distance for each stored waypoint.
-///
-/// `dist_along_m` is returned as stored. The format fixes it at conversion time against the raw
-/// geometry the converter saw, which a reader of the decimated file could not reproduce.
-pub fn obcr_to_waypoints(obcr: &[u8]) -> Result, ConvertFailure> {
- let src = SliceSource(obcr);
- let mut out: Vec = Vec::new();
- for_each_waypoint(&src, |w| {
- out.push(RouteWaypoint {
- name: w.name.as_str().into(),
- lat: f64::from(w.lat) * 1e-6,
- lon: f64::from(w.lon) * 1e-6,
- ele: (w.ele != WAYPOINT_ELE_NONE).then(|| f64::from(w.ele)),
- category: w.category_id,
- dist_along_m: w.dist_along_m,
- });
- })
- .map_err(describe_route_read_error)?;
- Ok(out)
-}
-
-/// Map a failure to open or read an `.obcr` onto the browser vocabulary. Exhaustive like the other
-/// maps in this file: a new seam variant must break this build.
-fn describe_route_read_error(e: Error) -> ConvertFailure {
- match e {
- Error::BadMagic | Error::BadVersion => {
- ConvertFailure::new(ErrorCode::NotRoute, "These bytes are not an OBCR route this bridge can read.")
- }
- Error::BadOffset => ConvertFailure::new(
- ErrorCode::InputTruncated,
- "This route file ends mid-structure — the download or copy was cut short.",
- ),
- Error::TooLarge => ConvertFailure::new(
- ErrorCode::NotRoute,
- "This route's chunk index exceeds the reader's limits — it was not written by this \
- toolchain.",
- ),
- Error::Io | Error::Empty => ConvertFailure::new(
- ErrorCode::Internal,
- "Internal error: reading from an in-memory buffer failed. This is a bug in the \
- conversion bridge — please report it.",
- ),
- }
-}
-
/// The bytes after an optional UTF-8 BOM and any leading whitespace.
fn document_start(bytes: &[u8]) -> &[u8] {
let body = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);
@@ -311,6 +263,24 @@ fn describe_gpx_error(e: Error) -> ConvertFailure {
}
}
+/// Map a line-to-OBCR failure onto the browser vocabulary.
+fn describe_line_error(e: Error) -> ConvertFailure {
+ match e {
+ Error::Empty => ConvertFailure::new(ErrorCode::GpxNoTrackPoints, "This route has no line to send."),
+ Error::TooLarge => ConvertFailure::new(
+ ErrorCode::GpxTooManyPoints,
+ format!(
+ "This route is too long for the device: it needs more than {MAX_STORED_POINTS} stored \
+ points. Split it into shorter routes."
+ ),
+ ),
+ Error::BadOffset | Error::BadMagic | Error::BadVersion | Error::Io => ConvertFailure::new(
+ ErrorCode::Internal,
+ "Internal error: the route line could not be encoded. This is a bug — please report it.",
+ ),
+ }
+}
+
/// Map a track-to-GPX failure onto the browser vocabulary. Split from [`describe_gpx_error`]
/// because the same [`Error`] means a different thing in each direction: `Empty` is a GPX with no
/// track one way and an empty recording the other.
@@ -396,87 +366,6 @@ mod tests {
r.expect_err("expected a failure").code
}
- /// What `gpx_to_obcr` stored, `obcr_to_track` returns: point for point, in order, elevation
- /// included.
- #[test]
- fn obcr_round_trips_to_the_track_it_stored() {
- let obcr = gpx_to_obcr(TINY_GPX.as_bytes(), "Tiny", BikeType::Road).unwrap();
- let flat = obcr_to_track(&obcr).unwrap();
- assert_eq!(flat.len() % 3, 0);
- let points: Vec<[f64; 3]> = flat.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect();
- // The tiny track survives decimation whole: 3 in, 3 out.
- assert_eq!(points.len(), 3);
- let expect = [[48.0000, 7.8200, 236.0], [48.0005, 7.8230, 241.0], [48.0002, 7.8265, 249.5]];
- for (got, want) in points.iter().zip(expect) {
- assert!((got[0] - want[0]).abs() < 1e-5, "lat {got:?} vs {want:?}");
- assert!((got[1] - want[1]).abs() < 1e-5, "lon {got:?} vs {want:?}");
- assert!((got[2] - want[2]).abs() < 1.0, "ele {got:?} vs {want:?}");
- }
- }
-
- /// The tiny track with two waypoints ahead of it: one categorized with an elevation, one with
- /// an unmapped symbol and no elevation. They sit near different ends of the track, so the
- /// stored distances must differ.
- const WPT_GPX: &str = r#"
-
- Aussicht Viewpoint
- 238.0 Brunnen Drinking Water
- t
- 236.0
- 241.0
- 249.5
-
-
-"#;
-
- /// What the converter stored, `obcr_to_waypoints` returns, sorted by distance along.
- #[test]
- fn obcr_round_trips_the_waypoints_it_stored() {
- let obcr = gpx_to_obcr(WPT_GPX.as_bytes(), "Tiny", BikeType::Road).unwrap();
- let wps = obcr_to_waypoints(&obcr).unwrap();
- assert_eq!(wps.len(), 2);
-
- // Sorted ascending by distance along: Brunnen sits by the start, Aussicht by the end.
- let (near, far) = (&wps[0], &wps[1]);
- assert_eq!(near.name, "Brunnen");
- assert_eq!(near.category, 1, "Drinking Water maps to water (§4.1)");
- assert_eq!(near.ele, Some(238.0));
- assert!((near.lat - 48.0001).abs() < 1e-5);
- assert!((near.lon - 7.8201).abs() < 1e-5);
-
- assert_eq!(far.name, "Aussicht");
- assert_eq!(far.category, 0, "Viewpoint is deliberately unmapped — generic");
- assert_eq!(far.ele, None, "no comes back as None, not as the sentinel");
- assert!(near.dist_along_m < far.dist_along_m, "route order: {near:?} vs {far:?}");
- // The track is about 500 m long, and the far waypoint's anchor is near its end.
- assert!(far.dist_along_m > 300 && far.dist_along_m < 700, "{far:?}");
- }
-
- /// A route without waypoints is an empty list, which is the common case and not an error.
- #[test]
- fn a_waypoint_free_route_decodes_to_no_waypoints() {
- let obcr = gpx_to_obcr(TINY_GPX.as_bytes(), "Tiny", BikeType::Road).unwrap();
- assert_eq!(obcr_to_waypoints(&obcr).unwrap(), Vec::new());
- }
-
- /// The waypoint direction shares the track direction's error vocabulary.
- #[test]
- fn obcr_to_waypoints_refuses_what_is_not_a_route() {
- assert_eq!(code_of(obcr_to_waypoints(&[0u8; 200])), ErrorCode::NotRoute);
- assert_eq!(code_of(obcr_to_waypoints(b"short")), ErrorCode::InputTruncated);
- }
-
- #[test]
- fn obcr_to_track_refuses_what_is_not_a_route() {
- // Long enough to read a header out of, wrong magic: not a route.
- assert_eq!(code_of(obcr_to_track(&[0u8; 200])), ErrorCode::NotRoute);
- // Too short for even the header, which reads the same as a cut-off copy.
- assert_eq!(code_of(obcr_to_track(b"short")), ErrorCode::InputTruncated);
- // A valid header cut off mid-index reads as truncation too.
- let obcr = gpx_to_obcr(TINY_GPX.as_bytes(), "Tiny", BikeType::Road).unwrap();
- assert_eq!(code_of(obcr_to_track(&obcr[..116])), ErrorCode::InputTruncated);
- }
-
/// The bridge adds nothing to the bytes: its output equals the shared converter's, and the
/// picked bike type lands in the header.
#[test]
@@ -533,6 +422,48 @@ mod tests {
assert!(mine.contains("a < b "), "name escaping survives: {mine}");
}
+ /// The line encoder adds nothing to the shared emitter: the same points, surfaces and waypoints
+ /// give the same bytes, and a long waypoint name is cut on a char boundary.
+ #[test]
+ fn line_conversion_matches_the_shared_emitter() {
+ let line =
+ [(7_820_000, 48_000_000, Some(236)), (7_823_000, 48_000_500, None), (7_826_500, 48_000_200, Some(249))];
+ let long = "Brunnen am Marktplatz Süd";
+ let waypoint =
+ LineWaypoint { lon: 7_823_000, lat: 48_000_500, distance_m: 230.0, category: 1, name: long.into() };
+ let mine = line_to_obcr(&line, &[0, 1, 3], core::slice::from_ref(&waypoint), "Day", BikeType::Gravel).unwrap();
+
+ let points: Vec = line
+ .iter()
+ .zip([0, 1, 3])
+ .map(|(&(lon, lat, ele), surface)| RoutePoint {
+ lon,
+ lat,
+ ele: ele.unwrap_or(ELEVATION_NONE),
+ surface,
+ elevation_incomplete: ele.is_none(),
+ })
+ .collect();
+ let mut stored = Waypoint {
+ dist_along_m: 0,
+ lon: waypoint.lon,
+ lat: waypoint.lat,
+ ele: WAYPOINT_ELE_NONE,
+ category_id: 1,
+ lateral_offset_m: 0,
+ name: Default::default(),
+ provenance: None,
+ };
+ // "ü" would end at byte 25 of the 24-byte field.
+ stored.name.push_str("Brunnen am Marktplatz S").unwrap();
+ let mut reference = VecSink(Vec::new());
+ obc_route::convert::points_to_obcr(&points, &[(stored, 230.0)], "Day", BikeType::Gravel, &mut reference)
+ .unwrap();
+ assert_eq!(mine, reference.0);
+ assert_eq!(mine[obc_formats::obcr::BIKE_TYPE_OFF], BikeType::Gravel as u8);
+ assert_eq!(code_of(line_to_obcr(&[], &[], &[], "x", BikeType::Road)), ErrorCode::GpxNoTrackPoints);
+ }
+
/// An empty file, a non-GPX file and a GPX without a track are three different answers, not one
/// invalid-file message.
#[test]
diff --git a/builder/wasm/src/convert_web.rs b/builder/wasm/src/convert_web.rs
index 7c9f7723ea..e45e5e7084 100644
--- a/builder/wasm/src/convert_web.rs
+++ b/builder/wasm/src/convert_web.rs
@@ -12,64 +12,58 @@ mod web {
/// Throws an `Error` carrying `code` and `message` on failure; see [`crate::convert::ErrorCode`].
#[wasm_bindgen]
pub fn obc_convert_gpx_to_obcr(bytes: &[u8], name: &str, bike: f64) -> Result, JsValue> {
+ crate::convert::gpx_to_obcr(bytes, name, bike_type(bike)?).map_err(to_js)
+ }
+
+ fn bike_type(bike: f64) -> Result {
let whole = bike.fract() == 0.0 && (0.0..=3.0).contains(&bike);
- let bike = whole.then_some(bike as u8).and_then(obc_route::BikeType::from_u8).ok_or_else(|| {
+ whole.then_some(bike as u8).and_then(obc_route::BikeType::from_u8).ok_or_else(|| {
to_js(ConvertFailure {
code: crate::convert::ErrorCode::Internal,
// A static message: formatting the `f64` would link float printing into the module.
message: "Internal error: the bike type is not 0 to 3. This is a bug in the builder.".into(),
})
- })?;
- crate::convert::gpx_to_obcr(bytes, name, bike).map_err(to_js)
- }
-
- /// Convert a finished ride-v6 object into a GPX 1.1 document, naming the track `name`.
- ///
- /// Throws an `Error` carrying `code` and `message` on failure; see [`crate::convert::ErrorCode`].
- #[wasm_bindgen]
- pub fn obc_convert_track_to_gpx(bytes: &[u8], name: &str) -> Result {
- crate::convert::track_to_gpx(bytes, name).map_err(to_js)
+ })
}
- /// Decode a `.obcr` route's polyline for the device page's preview: flat `[lat, lon, ele]`
- /// triples in route order, crossing as one `Float64Array`.
- ///
- /// Throws an `Error` carrying `code` and `message` on failure; see [`crate::convert::ErrorCode`].
+ /// Encode a calculated line into `.obcr` bytes; see [`crate::convert::line_to_obcr`].
+ /// `coordinates` holds longitude and latitude in microdegrees for each point; `heights` holds
+ /// metres, `i16::MIN` where none is known; `waypoints` is a JSON array of
+ /// [`crate::convert::LineWaypoint`] with camelCase fields.
#[wasm_bindgen]
- pub fn obc_convert_obcr_to_track(bytes: &[u8]) -> Result, JsValue> {
- crate::convert::obcr_to_track(bytes).map_err(to_js)
+ pub fn obc_convert_line_to_obcr(
+ coordinates: &[i32],
+ heights: &[i16],
+ surfaces: &[u8],
+ waypoints: &str,
+ name: &str,
+ bike: f64,
+ ) -> Result, JsValue> {
+ let bike = bike_type(bike)?;
+ let internal = |message: &str| {
+ to_js(ConvertFailure { code: crate::convert::ErrorCode::Internal, message: message.into() })
+ };
+ if coordinates.len() != heights.len() * 2 {
+ return Err(internal("Internal error: each point needs one height. This is a bug in the planner."));
+ }
+ let waypoints: Vec = serde_json::from_str(waypoints)
+ .map_err(|_| internal("Internal error: the waypoints are not valid. This is a bug in the planner."))?;
+ let points: Vec<_> = coordinates
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .zip(heights)
+ .map(|(&[lon, lat], &height)| (lon, lat, (height != i16::MIN).then_some(height)))
+ .collect();
+ crate::convert::line_to_obcr(&points, surfaces, &waypoints, name, bike).map_err(to_js)
}
- /// Decode a `.obcr` route's waypoint table: an `Array` of plain
- /// `{name, lat, lon, ele, category, distAlongM}` objects in ascending `distAlongM` order.
- /// `ele` is `null` where the source carried none, `category` is the stored byte raw, and
- /// `distAlongM` is the stored placement-time distance and not a recomputation. A route without
- /// waypoints yields `[]`.
- ///
- /// Plain objects rather than a flat array because names are strings, and at most 32 waypoints
- /// cross per route.
+ /// Convert a finished ride-v6 object into a GPX 1.1 document, naming the track `name`.
///
/// Throws an `Error` carrying `code` and `message` on failure; see [`crate::convert::ErrorCode`].
#[wasm_bindgen]
- pub fn obc_convert_obcr_to_waypoints(bytes: &[u8]) -> Result {
- let wps = crate::convert::obcr_to_waypoints(bytes).map_err(to_js)?;
- let arr = js_sys::Array::new();
- for w in wps {
- let obj = js_sys::Object::new();
- set(&obj, "name", &JsValue::from_str(&w.name));
- set(&obj, "lat", &JsValue::from_f64(w.lat));
- set(&obj, "lon", &JsValue::from_f64(w.lon));
- set(&obj, "ele", &w.ele.map_or(JsValue::NULL, JsValue::from_f64));
- set(&obj, "category", &JsValue::from_f64(f64::from(w.category)));
- set(&obj, "distAlongM", &JsValue::from_f64(f64::from(w.dist_along_m)));
- arr.push(&obj.into());
- }
- Ok(arr)
- }
-
- /// `Reflect::set` on a fresh plain object, which cannot fail, so the result is ignored.
- fn set(obj: &js_sys::Object, key: &str, value: &JsValue) {
- let _ = js_sys::Reflect::set(obj, &JsValue::from_str(key), value);
+ pub fn obc_convert_track_to_gpx(bytes: &[u8], name: &str) -> Result {
+ crate::convert::track_to_gpx(bytes, name).map_err(to_js)
}
/// Build the JS exception as a real `Error` instance, so it carries a stack and survives
diff --git a/builder/wasm/src/fit.rs b/builder/wasm/src/fit.rs
new file mode 100644
index 0000000000..897f878dc2
--- /dev/null
+++ b/builder/wasm/src/fit.rs
@@ -0,0 +1,145 @@
+//! Browser FIT import and export: a ride or a course from FIT bytes, and FIT bytes from both.
+//!
+//! The numbers cross as `Float64Array`s, with NaN for an absent value. A course does not cross as
+//! JSON text, because that would link the JSON parser into the module.
+
+use obc_fit::{Course, File, Point, Ride, Sample, Sport, Waypoint};
+use wasm_bindgen::prelude::*;
+
+/// A sample crosses as 10 values: Unix time, latitude, longitude, segment start (1 or 0),
+/// elevation, speed, heart rate, cadence, power and temperature.
+const SAMPLE_VALUES: usize = 10;
+
+const SPORTS: [(Sport, &str); 7] = [
+ (Sport::Road, "road"),
+ (Sport::Gravel, "gravel"),
+ (Sport::Mtb, "mtb"),
+ (Sport::Bike, "bike"),
+ (Sport::Foot, "foot"),
+ (Sport::Other, "other"),
+ (Sport::Unknown, "unknown"),
+];
+
+fn error(name: &str, message: &str, code: Option<&str>) -> JsValue {
+ let error = js_sys::Error::new(message);
+ error.set_name(name);
+ if let Some(code) = code {
+ let _ = js_sys::Reflect::set(&error, &"code".into(), &code.into());
+ }
+ error.into()
+}
+
+fn present(value: f64) -> Option {
+ (!value.is_nan()).then_some(value)
+}
+
+fn whole>(value: f64) -> Option {
+ present(value).and_then(|v| T::try_from(v.round() as i64).ok())
+}
+
+fn nan(value: Option>) -> f64 {
+ value.map_or(f64::NAN, Into::into)
+}
+
+/// Gives `{ sport, samples }` for a ride, or `{ name, points, waypoints, names, elapsedS }` for a
+/// course: points as latitude, longitude and elevation, waypoints as latitude and longitude, and
+/// the waypoint names (`undefined` for none). Throws a `FitError` with a `code`.
+#[wasm_bindgen]
+pub fn obc_fit_read(bytes: &[u8], fallback: &str) -> Result {
+ let file = obc_fit::read(bytes).map_err(|e| error("FitError", e.message(), Some(e.code())))?;
+ let out = js_sys::Object::new();
+ let set = |key: &str, value: &JsValue| js_sys::Reflect::set(&out, &key.into(), value);
+ let array = |values: Vec| JsValue::from(js_sys::Float64Array::from(&values[..]));
+ match file {
+ File::Ride(ride) => {
+ let sport = SPORTS.iter().find(|(s, _)| *s == ride.sport).map_or("other", |(_, code)| code);
+ let samples = ride.samples.iter().flat_map(|s| {
+ [
+ s.time as f64,
+ s.lat.into(),
+ s.lon.into(),
+ f64::from(u8::from(s.segment_start)),
+ nan(s.elevation),
+ nan(s.speed),
+ nan(s.heart_rate),
+ nan(s.cadence),
+ nan(s.power),
+ nan(s.temperature),
+ ]
+ });
+ set("sport", &sport.into())?;
+ set("samples", &array(samples.collect()))?;
+ }
+ File::Course(course) => {
+ let name = if course.name.is_empty() { fallback } else { &course.name };
+ let points = course.points.iter().flat_map(|p| [p.lat.into(), p.lon.into(), nan(p.elevation)]);
+ let waypoints = course.waypoints.iter().flat_map(|w| [w.lat.into(), w.lon.into()]);
+ let names: js_sys::Array =
+ course.waypoints.iter().map(|w| w.name.as_deref().map_or(JsValue::UNDEFINED, JsValue::from)).collect();
+ set("name", &name.into())?;
+ set("points", &array(points.collect()))?;
+ set("waypoints", &array(waypoints.collect()))?;
+ set("names", &names)?;
+ set("elapsedS", &course.seconds.into())?;
+ }
+ }
+ Ok(out)
+}
+
+#[wasm_bindgen]
+pub fn obc_fit_write_ride(sport: &str, samples: &[f64]) -> Result, JsValue> {
+ let sport = SPORTS.iter().find(|(_, code)| *code == sport).ok_or_else(|| error("Error", "unknown sport", None))?.0;
+ let (samples, rest) = samples.as_chunks::();
+ if !rest.is_empty() {
+ return Err(error("Error", "a sample has 10 values", None));
+ }
+ let samples = samples
+ .iter()
+ .map(|v| Sample {
+ time: v[0] as i64,
+ lat: v[1].round() as i32,
+ lon: v[2].round() as i32,
+ segment_start: v[3] != 0.0,
+ elevation: present(v[4]),
+ speed: present(v[5]),
+ heart_rate: whole(v[6]),
+ cadence: whole(v[7]),
+ power: whole(v[8]),
+ temperature: whole(v[9]),
+ })
+ .collect();
+ Ok(obc_fit::write_ride(&Ride { sport, samples }))
+}
+
+/// Takes a course in the shape that `obc_fit_read` gives. An empty name is no name.
+#[wasm_bindgen]
+pub fn obc_fit_write_course(
+ name: String,
+ points: &[f64],
+ waypoints: &[f64],
+ names: Vec,
+ elapsed_s: f64,
+) -> Result, JsValue> {
+ let (points, rest) = points.as_chunks::<3>();
+ let (waypoints, odd) = waypoints.as_chunks::<2>();
+ if !rest.is_empty() || !odd.is_empty() || waypoints.len() != names.len() {
+ return Err(error("Error", "a point has 3 values, and a waypoint has 2 values and a name", None));
+ }
+ Ok(obc_fit::write_course(&Course {
+ name,
+ points: points
+ .iter()
+ .map(|p| Point { lat: p[0].round() as i32, lon: p[1].round() as i32, elevation: present(p[2]) })
+ .collect(),
+ waypoints: waypoints
+ .iter()
+ .zip(names)
+ .map(|(w, name)| Waypoint {
+ lat: w[0].round() as i32,
+ lon: w[1].round() as i32,
+ name: (!name.is_empty()).then_some(name),
+ })
+ .collect(),
+ seconds: elapsed_s.round().clamp(0.0, f64::from(u32::MAX)) as u32,
+ }))
+}
diff --git a/builder/wasm/src/gpx.rs b/builder/wasm/src/gpx.rs
index bfac45aae3..c3d0b72c4e 100644
--- a/builder/wasm/src/gpx.rs
+++ b/builder/wasm/src/gpx.rs
@@ -1,15 +1,28 @@
-//! Browser GPX import: full planner points and the bounded corridor preview.
+//! Browser GPX import: the points and waypoints of a GPX file.
use serde::Serialize;
-pub const MAX_ROUTE_POINTS: usize = 2048;
-
#[derive(Clone, Copy, Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
pub struct Point {
pub lat: f64,
pub lon: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub ele: Option,
+ /// Unix seconds, with the fraction of the file.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub time: Option,
+ /// The first point of the file, and of each `trk` and `trkseg`.
+ #[serde(skip_serializing_if = "std::ops::Not::not")]
+ pub segment_start: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub hr_bpm: Option,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cadence_rpm: Option,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub power_w: Option,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub temperature_c: Option,
}
#[derive(Debug, Serialize)]
@@ -26,14 +39,9 @@ pub struct Import {
pub name: String,
pub points: Vec,
pub waypoints: Vec,
-}
-
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct Route {
- pub name: String,
- pub points: Vec,
- pub distance_km: f64,
+ /// The `` of the first track, such as `cycling`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub kind: Option,
}
fn whitespace(c: char) -> bool {
@@ -135,6 +143,12 @@ fn point(attributes: &str) -> Option {
lat: round(lat * 1e6),
lon: round(lon * 1e6),
ele: None,
+ time: None,
+ segment_start: false,
+ hr_bpm: None,
+ cadence_rpm: None,
+ power_w: None,
+ temperature_c: None,
})
}
@@ -150,6 +164,55 @@ fn round(value: f64) -> f64 {
}
}
+/// `YYYY-MM-DDTHH:MM:SS`, an optional fraction, then `Z`, `±HH:MM` or no zone, which is UTC.
+fn time(text: &str) -> Option {
+ let b = text.as_bytes();
+ let digits = |at: usize, len: usize| -> Option {
+ let part = b.get(at..at + len)?;
+ part.iter().all(u8::is_ascii_digit).then(|| part.iter().fold(0, |n, c| n * 10 + i64::from(c - b'0')))
+ };
+ let [year, month, day, hour, minute, second] =
+ [(0, 4), (5, 2), (8, 2), (11, 2), (14, 2), (17, 2)].map(|(at, len)| digits(at, len));
+ let (year, month, day, hour, minute, second) = (year?, month?, day?, hour?, minute?, second?);
+ if b[4] != b'-' || b[7] != b'-' || !matches!(b[10], b'T' | b't' | b' ') || b[13] != b':' || b[16] != b':' {
+ return None;
+ }
+ if !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || minute > 59 || second > 60 {
+ return None;
+ }
+ let mut rest = &b[19..];
+ let mut fraction = 0.0;
+ if let Some(after) = rest.strip_prefix(b".") {
+ let end = after.iter().position(|c| !c.is_ascii_digit()).unwrap_or(after.len());
+ fraction = after[..end].iter().rev().fold(0.0, |f, c| (f + f64::from(c - b'0')) / 10.0);
+ rest = &after[end..];
+ }
+ let offset = match rest {
+ b"" | b"Z" | b"z" => 0,
+ [sign @ (b'+' | b'-'), h1, h2, b':', m1, m2] | [sign @ (b'+' | b'-'), h1, h2, m1, m2] => {
+ let zone = [h1, h2, m1, m2];
+ if !zone.iter().all(|c| c.is_ascii_digit()) {
+ return None;
+ }
+ let [h1, h2, m1, m2] = zone.map(|c| i64::from(c - b'0'));
+ let seconds = (h1 * 10 + h2) * 3600 + (m1 * 10 + m2) * 60;
+ if *sign == b'-' {
+ -seconds
+ } else {
+ seconds
+ }
+ }
+ _ => return None,
+ };
+ // Days since 1970-01-01 in the Gregorian calendar (`days_from_civil` of Howard Hinnant).
+ let y = if month <= 2 { year - 1 } else { year };
+ let era = y.div_euclid(400);
+ let yoe = y - era * 400;
+ let doy = (153 * ((month + 9) % 12) + 2) / 5 + day - 1;
+ let days = era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468;
+ Some((days * 86_400 + hour * 3600 + minute * 60 + second - offset) as f64 + fraction)
+}
+
fn first_text(text: &str, tag: &str) -> Option {
let begin = text.find(&format!("<{tag}>"))? + tag.len() + 2;
let end = text[begin..].find(&format!("{tag}>"))? + begin;
@@ -184,12 +247,38 @@ fn scoped_name(text: &str) -> Option {
None
}
+/// The first element in `extensions` whose local name, after any prefix, is `name`: its text as a finite
+/// decimal. This reads the Garmin `TrackPointExtension` v1 and v2 with any prefix, and a bare ``.
+fn sensor(extensions: &str, name: &str) -> Option {
+ let rest = extensions.match_indices('<').map(|(at, _)| &extensions[at + 1..]).find(|rest| {
+ let tag = &rest[..rest.find(|c| matches!(c, '/' | '>') || whitespace(c)).unwrap_or(rest.len())];
+ tag.rsplit(':').next() == Some(name)
+ })?;
+ let (head, text) = rest.split_once('>')?;
+ if head.ends_with('/') {
+ return None;
+ }
+ let value: f64 = text[..text.find('<').unwrap_or(text.len())].trim_matches(whitespace).parse().ok()?;
+ value.is_finite().then_some(value)
+}
+
pub fn read(text: &str, fallback: &str) -> Result {
let entries = elements(text, &["trkpt", "rtept"]);
- let mut tracks = Vec::new();
- let mut routes = Vec::new();
+ let trks = elements(text, &["trk"]);
+ // The openers of the tracks and their segments, in the order of the file.
+ let mut openers: Vec = trks.iter().chain(&elements(text, &["trkseg"])).map(|e| e.start).collect();
+ openers.sort_unstable();
+ let mut openers = openers.into_iter().peekable();
+ let mut tracks: Vec = Vec::new();
+ let mut routes: Vec = Vec::new();
let mut malformed = 0;
+ let mut segment_start = true;
for entry in &entries {
+ if entry.kind == "trkpt" {
+ while openers.next_if(|&at| at < entry.start).is_some() {
+ segment_start = true;
+ }
+ }
let Some(mut p) = point(entry.attributes) else {
malformed += 1;
continue;
@@ -205,9 +294,22 @@ pub fn read(text: &str, fallback: &str) -> Result {
break;
}
}
+ p.time = first_text(entry.body, "time").and_then(|t| time(&t));
+ if let Some(extensions) = elements(entry.body, &["extensions"]).first() {
+ // No sensor gives a heart rate of 0 or a negative cadence or power: some apps write 0 without strap contact.
+ let value = |name, min: f64| sensor(extensions.body, name).filter(|v| *v >= min);
+ (p.hr_bpm, p.cadence_rpm, p.power_w, p.temperature_c) = (
+ value("hr", f64::MIN_POSITIVE),
+ value("cad", 0.0),
+ value("power", 0.0),
+ sensor(extensions.body, "atemp"),
+ );
+ }
if entry.kind == "trkpt" {
+ p.segment_start = std::mem::take(&mut segment_start);
tracks.push(p);
} else {
+ p.segment_start = routes.is_empty();
routes.push(p);
}
}
@@ -242,25 +344,12 @@ pub fn read(text: &str, fallback: &str) -> Result {
}
file.push_str(&text[at..]);
let name = scoped.or_else(|| first_text(&file, "name")).unwrap_or_else(|| fallback.into());
- Ok(Import { name, points, waypoints })
-}
-
-pub fn parse(text: &str, fallback: &str) -> Result {
- let Import { name, points, .. } = read(text, fallback)?;
- let count = points.len().min(MAX_ROUTE_POINTS);
- let step = (points.len() - 1) as f64 / (count - 1) as f64;
- let points: Vec<_> = (0..count).map(|k| Point { ele: None, ..points[round(k as f64 * step) as usize] }).collect();
- let distance_km = points
- .windows(2)
- .map(|p| {
- let cos = (((p[0].lat + p[1].lat) / 2.0) * std::f64::consts::PI / 180e6).cos();
- let dlat = (p[1].lat - p[0].lat) * 111_320.0 / 1e6;
- let dlon = (p[1].lon - p[0].lon) * 111_320.0 * cos / 1e6;
- dlat.hypot(dlon)
- })
- .sum::()
- / 1000.0;
- Ok(Route { name, points, distance_km })
+ // Only the head of the track: a point can have a `` too.
+ let kind = trks.first().and_then(|trk| {
+ let head = [" ", 47.0 + i as f64 / 10_000.0)).collect();
- let full = read(&text, "fallback").unwrap();
- let route = parse(&text, "fallback").unwrap();
- assert_eq!(full.points.len(), 10_000);
- assert_eq!(route.points.len(), MAX_ROUTE_POINTS);
- let samples: Vec<_> =
- [0, 1, 2, 3, 512, 1023, 1024, 2046, 2047].into_iter().map(|i| route.points[i].lat).collect();
- assert_eq!(
- samples,
- [
- 47_000_000.0,
- 47_000_500.0,
- 47_001_000.0,
- 47_001_500.0,
- 47_250_100.0,
- 47_499_700.0,
- 47_500_200.0,
- 47_999_400.0,
- 47_999_900.0
- ]
- );
- assert!(route.points.iter().all(|point| point.ele.is_none()));
+ fn sensors_come_from_the_extensions_of_a_point_by_local_name() {
+ let sensors = |extensions: &str| {
+ let text = format!("{extensions} ");
+ let p = read(&text, "file").unwrap().points[0];
+ (p.hr_bpm, p.cadence_rpm, p.power_w, p.temperature_c)
+ };
+ let v1 = "21.5 141 88 250 ";
+ assert_eq!(sensors(v1), (Some(141.0), Some(88.0), Some(250.0), Some(21.5)));
+ let v2 = " 150 90 ";
+ assert_eq!(sensors(v2), (Some(150.0), Some(90.0), None, None));
+ assert_eq!(sensors("312 "), (None, None, Some(312.0), None));
+ let none = "Climb
140]]>0x8C inf ";
+ assert_eq!(sensors(none), (None, None, None, None));
+ let out_of_range = "0 -1 -5 ";
+ assert_eq!(sensors(out_of_range), (None, None, None, None));
+ let zero = "0 0 ";
+ assert_eq!(sensors(zero), (None, Some(0.0), Some(0.0), None));
+ assert_eq!(sensors(""), (None, None, None, None));
}
}
diff --git a/builder/wasm/src/lib.rs b/builder/wasm/src/lib.rs
index 37f53dc2e9..af13ffb8ae 100644
--- a/builder/wasm/src/lib.rs
+++ b/builder/wasm/src/lib.rs
@@ -12,6 +12,9 @@ mod browser;
#[cfg(target_arch = "wasm32")]
mod client_web;
+#[cfg(target_arch = "wasm32")]
+mod fit;
+
pub use driver::*;
pub use estimate::*;
pub use preview::*;
diff --git a/builder/web/package-lock.json b/builder/web/package-lock.json
index 568ae6854c..ab829fbd19 100644
--- a/builder/web/package-lock.json
+++ b/builder/web/package-lock.json
@@ -11,7 +11,6 @@
"@mapbox/vector-tile": "^3.0.0",
"@maplibre/maplibre-gl-leaflet": "^0.1.4",
"@protomaps/basemaps": "^5.7.2",
- "@tauri-apps/api": "^2.11.1",
"earcut": "^3.2.4",
"leaflet": "^1.9.4",
"maplibre-contour": "^0.1.1",
@@ -1042,16 +1041,6 @@
"vite": "^6.3.0 || ^7.0.0"
}
},
- "node_modules/@tauri-apps/api": {
- "version": "2.11.1",
- "resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.11.1.tgz",
- "integrity": "sha512-M2FPuYND2m+wh5hfW9ZpSdxMPdEJovPBWwoHJmwUpysTYNHaOkVFN419m/K0LIgjb/7KU2vBgsUepJWugQCvAA==",
- "license": "Apache-2.0 OR MIT",
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/tauri"
- }
- },
"node_modules/@tsconfig/svelte": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/@tsconfig/svelte/-/svelte-5.0.8.tgz",
diff --git a/builder/web/package.json b/builder/web/package.json
index d8673dd761..338d10b7ed 100644
--- a/builder/web/package.json
+++ b/builder/web/package.json
@@ -10,8 +10,7 @@
"build:data": "vite build --mode data",
"build:trailview": "vite build --mode trailview",
"build:web": "vite build --mode web",
- "build:desktop": "vite build --mode desktop",
- "build:all": "npm run build && npm run build:web && npm run build:desktop",
+ "build:all": "npm run build && npm run build:web",
"build:wasm": "bash ../build-wasm-bridges.sh",
"preview": "vite preview",
"check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings",
@@ -23,7 +22,6 @@
"@mapbox/vector-tile": "^3.0.0",
"@maplibre/maplibre-gl-leaflet": "^0.1.4",
"@protomaps/basemaps": "^5.7.2",
- "@tauri-apps/api": "^2.11.1",
"earcut": "^3.2.4",
"leaflet": "^1.9.4",
"maplibre-contour": "^0.1.1",
diff --git a/builder/web/src/App.svelte b/builder/web/src/App.svelte
index a18729aeee..253f9f5a22 100644
--- a/builder/web/src/App.svelte
+++ b/builder/web/src/App.svelte
@@ -2,13 +2,10 @@
import ConfirmDialog from "./components/ConfirmDialog.svelte";
import Header from "./components/Header.svelte";
import UpdatePrompt from "./components/UpdatePrompt.svelte";
- import Desktop from "./routes/Desktop.svelte";
import Home from "./routes/Home.svelte";
import { LINKS } from "./lib/constants";
import { platform, type StyleEditorModule } from "./lib/platform";
- import { DESKTOP_ADDS } from "./lib/platform/gating";
import { router } from "./lib/router.svelte";
- import { DESKTOP_ROUTE } from "./lib/routes";
// The advanced editor is maintainer tooling, reached through an `import()`
// only the dev host declares — product hosts have no reference to the route
@@ -20,28 +17,8 @@
let editor: Promise | undefined;
const openEditor = load ? () => (editor ??= load()) : null;
- // The device and rides pages reach the protocol codecs and the library —
- // exactly the modules the entry chunk must not contain (platform/bundle.test.ts)
- // — so both live behind memoized dynamic imports, the same shape the device
- // surfaces already use. Gated on caps, not on a host name: a tier without
- // the page treats its hash as home.
- let devicePage: Promise | undefined;
- const openDevice = platform.caps.deviceDashboard
- ? () => (devicePage ??= import("./routes/Device.svelte"))
- : null;
- let ridesPage: Promise | undefined;
- const openRides = platform.caps.rideLibrary
- ? () => (ridesPage ??= import("./routes/Rides.svelte"))
- : null;
-
const showEditor = $derived(router.route === "advanced" && openEditor !== null);
- // Same shape as the editor's gate: a host that is missing nothing has
- // nothing to read there, so #/desktop falls back to home rather than
- // rendering a page that pitches the app you are already running.
- const showDesktop = $derived(router.route === "desktop" && DESKTOP_ADDS.length > 0);
- const showDevice = $derived(router.route === "device" && openDevice !== null);
- const showRides = $derived(router.route === "rides" && openRides !== null);
- const showHome = $derived(!showEditor && !showDesktop && !showDevice && !showRides);
+ const showHome = $derived(!showEditor);
@@ -64,35 +41,18 @@
{/await}
{/if}
- {#if showDesktop}
-
- {/if}
- {#if showDevice && openDevice}
- {#await openDevice() then { default: Device }}
-
- {/await}
- {/if}
- {#if showRides && openRides}
- {#await openRides() then { default: Rides }}
-
- {/await}
- {/if}
-
+
+
+ {#if page.error}
+
{page.error}
+ {:else if page.component}
+
+ {/if}
+
+ {/if}
+ {/each}
+
+ {#if router.settings}
+ {#await import('./pages/Settings.svelte') then { default: Settings }}
+
+ {:catch error}
+ router.closeSettings()}>
+ {error instanceof Error ? error.message : String(error)}
+
+ {/await}
+ {/if}
+
+
+
+
diff --git a/builder/web/src/components/ConfirmDialog.svelte b/builder/web/src/components/ConfirmDialog.svelte
index e884d2579d..607f9df0a8 100644
--- a/builder/web/src/components/ConfirmDialog.svelte
+++ b/builder/web/src/components/ConfirmDialog.svelte
@@ -1,11 +1,9 @@
-
-
- {#if active}
-
- sending {active.label}{#if active.total > 0}
- · {active.pct}%{/if}
-
- {/if}
-
- {#if session?.status === "ready"}
-
-
-
- OBC
- {#if session.info}{session.info.hardwareRevision} {/if}
-
- session && void session.disconnect()}>
- Disconnect
-
-
- {:else if session?.status === "connecting"}
-
-
- Connecting…
-
- {:else if session?.status === "unsupported"}
-
-
- USB unavailable
-
- {:else}
-
-
- No device
-
- Connect
-
-
- {/if}
-
-
-
diff --git a/builder/web/src/components/Gated.svelte b/builder/web/src/components/Gated.svelte
deleted file mode 100644
index 6e90efc05c..0000000000
--- a/builder/web/src/components/Gated.svelte
+++ /dev/null
@@ -1,98 +0,0 @@
-
-
-
-{#if blocked}
- {#if unavailable}
- {@render unavailable(reasonId)}
- {/if}
-
-
- {GATES[blocked].reason}
- {DESKTOP_LINK.label}
-
-{:else if children}
- {@render children(value as T)}
-{/if}
-
-
diff --git a/builder/web/src/components/Header.svelte b/builder/web/src/components/Header.svelte
index 107eef600b..6646efca68 100644
--- a/builder/web/src/components/Header.svelte
+++ b/builder/web/src/components/Header.svelte
@@ -4,37 +4,25 @@
import { setupSiteNavigation } from "../../../../docs/assets/site-navigation.js";
import { appearance, startTheme, toggleTheme } from "../lib/theme.svelte";
- import DeviceChip from "./DeviceChip.svelte";
import { platform } from "../lib/platform";
- import { available } from "../lib/platform/gating";
import { router, type Route } from "../lib/router.svelte";
- import { ADVANCED_ROUTE, DEVICE_ROUTE, RIDES_ROUTE } from "../lib/routes";
+ import { ROUTES } from "../lib/routes";
let header: HTMLElement;
onMount(startTheme);
- onMount(() => siteNav ? setupSiteNavigation(header) : undefined);
+ onMount(() => setupSiteNavigation(header));
- // The header has two shapes, decided by capability rather than host name:
- // an app with more than one place to be gets tabs; a single-page site keeps
- // links. Each tab exists exactly where its route does (`App.svelte` gates
- // the same way), so a tab can never point at a page that falls back home.
+ // A host with more than one place to be gets tabs under the site links. Each
+ // tab exists exactly where its route does (`App.svelte` gates the same way),
+ // so a tab can never point at a page that falls back home.
const tabs: Array<{ route: Route; href: string; label: string }> = [
- { route: "home", href: "#/", label: "Maps" },
+ { route: "home", href: ROUTES.home, label: "Maps" },
...(platform.styleEditor
- ? [{ route: "advanced" as const, href: ADVANCED_ROUTE, label: "Style editor" }]
- : []),
- ...(available("deviceDashboard")
- ? [{ route: "device" as const, href: DEVICE_ROUTE, label: "Device" }]
- : []),
- ...(available("rideLibrary")
- ? [{ route: "rides" as const, href: RIDES_ROUTE, label: "Ride library" }]
+ ? [{ route: "advanced" as const, href: ROUTES.advanced, label: "Style editor" }]
: []),
];
const tabbed = tabs.length > 1;
- // Links out of the app, present only where there is a site around it (the
- // desktop app has none — `platform.siteNav` is absent there, and so are
- // these). Orthogonal to the tabs: the dev server shows both.
const siteNav = platform.siteNav;
@@ -57,20 +45,15 @@
- {#if siteNav && tabbed}
+ {#if tabbed}
{@render appTabs()}
@@ -103,7 +83,4 @@
.site-head:has(.tabs) :global(.name) { display: none; }
.site-head:has(.tabs) :global(.short-name) { display: inline; }
}
- @media (max-width: 760px) {
- .head-inner > .tabs { order: 3; width: 100%; }
- }
diff --git a/builder/web/src/components/TopBar.svelte b/builder/web/src/components/TopBar.svelte
new file mode 100644
index 0000000000..25d07be5ee
--- /dev/null
+++ b/builder/web/src/components/TopBar.svelte
@@ -0,0 +1,178 @@
+
+
+
+
+
diff --git a/builder/web/src/components/UpdatePrompt.svelte b/builder/web/src/components/UpdatePrompt.svelte
index d7299492c9..b783348da6 100644
--- a/builder/web/src/components/UpdatePrompt.svelte
+++ b/builder/web/src/components/UpdatePrompt.svelte
@@ -17,9 +17,7 @@
import { jobRegistry } from "../lib/device/job.svelte";
import { deviceHolder } from "../lib/device/session.svelte";
import { firmwareCheck } from "../lib/firmware/check.svelte";
- import { platform } from "../lib/platform";
- import { router } from "../lib/router.svelte";
- import { DEVICE_ROUTE, FIRMWARE_ANCHOR } from "../lib/routes";
+ import { FIRMWARE_ANCHOR } from "../lib/routes";
const session = $derived(deviceHolder.session);
/** Non-null exactly while a device is connected and has said what it is. */
@@ -42,15 +40,11 @@
}
/**
- * Take the rider to the card.
- *
- * On a tier with a Device page that is a navigation, and the page arrives through a dynamic
- * import — so the element does not exist yet at the moment of the click. Hence the short poll
- * rather than one `scrollIntoView` into nothing; it gives up quietly after a second.
+ * Take the rider to the card. The device surfaces arrive through a dynamic import, so the card
+ * can be missing at the moment of the click: a short poll, which gives up quietly after a second.
*/
function show(release: { version: string }) {
answer(release);
- if (platform.caps.deviceDashboard && router.route !== "device") router.go("device");
let tries = 0;
const settle = () => {
const card = document.getElementById(FIRMWARE_ANCHOR);
@@ -73,13 +67,7 @@
{/if}
answer(release)}>Dismiss
-
- {#if platform.caps.deviceDashboard}
-
show(release)}>View update
- {:else}
-
show(release)}>View update
- {/if}
+
show(release)}>View update
{/if}
@@ -115,11 +103,4 @@
gap: 8px;
margin-top: 6px;
}
-
- /* The link-shaped primary: `.btn` is written for buttons, so undo the anchor's own colour rule
- and keep the label from picking up an underline on hover. */
- a.btn.primary {
- color: var(--parchment);
- text-decoration: none;
- }
diff --git a/builder/web/src/components/coverage/CorridorPanel.svelte b/builder/web/src/components/coverage/CorridorPanel.svelte
deleted file mode 100644
index 7be7e55b58..0000000000
--- a/builder/web/src/components/coverage/CorridorPanel.svelte
+++ /dev/null
@@ -1,594 +0,0 @@
-
-
- {
- e.preventDefault();
- dragOver = true;
- }}
- ondragleave={() => (dragOver = false)}
- ondrop={onDrop}
->
-
-
Add corridor
-
-
- {deviceHolder.session?.status === "ready" ? "device connected" : "device optional"}
-
- ✕
-
-
-
- {
- source = "gpx";
- fileInput?.click();
- }}
- >
- ⤒ Upload GPX
-
- (source = "device")}>
- From device
-
-
-
-
- {#if source === "device"}
- {#if deviceHolder.session?.status === "ready" && deviceHolder.session.client}
- {#if deviceLoading}
-
Reading routes from the device…
- {:else if deviceEntries.length === 0 && !deviceError}
-
No routes are saved on this device.
- {:else}
-
- {/if}
- {:else if deviceHolder.error || deviceHolder.session?.status === "unsupported"}
-
- {deviceHolder.error ?? deviceHolder.session?.error ?? "This browser cannot connect to the device."}
-
- {:else}
-
-
Connect once to choose from the routes saved on your OBC.
-
- {prompting ? "Connecting…" : "Connect device"}
-
-
- {/if}
- {#if deviceError}
-
{deviceError}
- {/if}
- {/if}
-
- {#if uploadError}
-
{uploadError}
- {/if}
-
- {#if routes.length === 0 && source === "gpx"}
-
- Upload a route and the map around it — as wide as you choose, gaps and all — becomes part of
- this download. Or drop a .gpx file anywhere in this panel.
-
- {/if}
-
-
- {#if routes.some((route) => route.origin === source)}
- {#if source === "gpx"}
-
- {/if}
-
-
-
-
- Corridor width — all routes
- ± {radiusKm} km
-
-
-
-
- {#if previewError}
-
{previewError}
- {:else if adds && checkedCount}
-
- Adds {formatBytes(adds.addsBytes)} to the total{adds.patches > 1
- ? ` · ${adds.patches - 1} ${adds.patches === 2 ? "gap" : "gaps"} between routes`
- : ""}
-
- {:else if checkedCount}
-
Calculating…
- {/if}
-
-
-
- Add to map
-
- gaps are fine — holes stay visible
-
- {/if}
-
-
-
diff --git a/builder/web/src/components/coverage/CoverageHome.svelte b/builder/web/src/components/coverage/CoverageHome.svelte
index aa6e98dff3..e41f18ddae 100644
--- a/builder/web/src/components/coverage/CoverageHome.svelte
+++ b/builder/web/src/components/coverage/CoverageHome.svelte
@@ -2,9 +2,7 @@
import { tick } from "svelte";
import type { CatalogClient } from "../../lib/catalog/client";
import { CoverageStore } from "../../lib/coverage/store.svelte";
- import { available } from "../../lib/platform/gating";
import DeviceStep from "../device/DeviceStep.svelte";
- import MapSendStep from "../device/MapSendStep.svelte";
import CoverageMap from "./CoverageMap.svelte";
import DownloadStep from "./DownloadStep.svelte";
import MapSummary from "./MapSummary.svelte";
@@ -115,11 +113,7 @@
Or send directly to device
- {#if available("deviceDashboard")}
-
- {:else}
-
- {/if}
+
diff --git a/builder/web/src/components/coverage/CoverageHome.svelte.test.ts b/builder/web/src/components/coverage/CoverageHome.svelte.test.ts
index e122fa2a3f..6d74947135 100644
--- a/builder/web/src/components/coverage/CoverageHome.svelte.test.ts
+++ b/builder/web/src/components/coverage/CoverageHome.svelte.test.ts
@@ -14,8 +14,7 @@ vi.mock("./CoverageMap.svelte", async () => ({ default: (await import("../../../
vi.mock("./SkinStep.svelte", async () => ({ default: (await import("./ToolIcon.svelte")).default }));
vi.mock("../device/DeviceStep.svelte", async () => ({ default: (await import("./ToolIcon.svelte")).default }));
const host = vi.hoisted(() => ({ catalog: vi.fn(), catalogFetch: vi.fn(async () => new Response("gone", { status: 404 })) }));
-vi.mock("../../lib/platform", () => ({ platform: { ...host, name: "web", caps: { deviceDashboard: false }, openMapOutput: null } }));
-vi.mock("../../lib/platform/gating", () => ({ available: () => false }));
+vi.mock("../../lib/platform", () => ({ platform: { ...host, name: "web" } }));
const client = (body: string, url: string) => CatalogClient.fromBody(body, url, { fetchImpl: host.catalogFetch, attempts: 1 });
async function settle() { for (let n = 0; n < 20; n++) { await Promise.resolve(); await tick(); } }
diff --git a/builder/web/src/components/coverage/CoverageMap.svelte b/builder/web/src/components/coverage/CoverageMap.svelte
index f4215b6938..895d58b7ab 100644
--- a/builder/web/src/components/coverage/CoverageMap.svelte
+++ b/builder/web/src/components/coverage/CoverageMap.svelte
@@ -1,6 +1,6 @@
@@ -1264,35 +174,32 @@
stroke-width="1"
/>
{/each}
- {#each proof.routes as d, k (k)}
-
- {/each}
{proofCaption(proof)}
{/if}
- {#if refusal}
-
{refusal}
- {:else if estimateError}
+ {#if run.refusal}
+
{run.refusal}
+ {:else if run.estimateError}
- Could not check memory requirements: {estimateError}
- (estimateNonce += 1)}
+ Could not check memory requirements: {run.estimateError}
+ run.retryEstimate()}
>retry
- {:else if memoryCaution}
-
{memoryCaution}
+ {:else if run.memoryCaution}
+
{run.memoryCaution}
{/if}
void setKeepCells(event.currentTarget.checked)}
+ checked={run.keepCells}
+ disabled={run.running || run.clearingCells}
+ onchange={(event) => void run.setKeepCells(event.currentTarget.checked)}
/>
Keep map data for next time
@@ -1302,94 +209,87 @@
void clearStoredCells(true)}
+ disabled={run.running || run.clearingCells}
+ onclick={() => void run.clearStoredCells(true)}
>
- {clearingCells ? "Deleting…" : "Delete stored map data"}
+ {run.clearingCells ? "Deleting…" : "Delete stored map data"}
- {#if cellStorageNotice}{cellStorageNotice} {/if}
+ {#if run.cellStorageNotice}{run.cellStorageNotice} {/if}
- {#if phase === "idle" || phase === "cancelled" || phase === "error" || phase === "done"}
+ {#if run.phase === "idle" || run.phase === "cancelled" || run.phase === "error" || run.phase === "done"}
-
+ run.download()}>
Download map
{:else}
- {#if phase !== "finalizing"}
- Cancel
+ {#if run.phase !== "finalizing"}
+ run.cancel()}>Cancel
{/if}
- {#if phase === "downloading" && dlProgress}
+ {#if run.phase === "downloading" && run.dlProgress}
- downloading cells — {dlProgress.completedCells}/{dlProgress.totalCells} ·
- {formatBytes(dlProgress.receivedBytes)} of {formatBytes(dlProgress.totalBytes)}
- {#if cachedCells > 0}· {cachedCells} already on this computer ({formatBytes(
- cachedBytes,
+ downloading cells — {run.dlProgress.completedCells}/{run.dlProgress.totalCells} ·
+ {formatBytes(run.dlProgress.receivedBytes)} of {formatBytes(run.dlProgress.totalBytes)}
+ {#if run.cachedCells > 0}· {run.cachedCells} already on this computer ({formatBytes(
+ run.cachedBytes,
)}){/if}
- {:else if phase === "assembling"}
+ {:else if run.phase === "assembling"}
- assembling — {ASM_PHASE_LABEL[asmPhase]} · {Math.round(asmFraction * 100)}%{#if readMode}
- · cells {readMode}{/if}
+ assembling — {ASM_PHASE_LABEL[run.asmPhase]} · {Math.round(run.asmFraction * 100)}%{#if run.readMode}
+ · cells {run.readMode}{/if}
- {:else if phase === "saving"}
+ {:else if run.phase === "saving"}
- {output?.kind === "device" ? "sending the map" : "saving the map"}{#if runFileName}
- — {runFileName}{/if}
+ {run.sendingToDevice ? "sending the map" : "saving the map"}{#if run.runFileName}
+ — {run.runFileName}{/if}
- {:else if phase === "finalizing"}
+ {:else if run.phase === "finalizing"}
finishing up — removing temporary map data
{/if}
{/if}
- {#if phase === "done"}
+ {#if run.phase === "done"}
- {#if lastRunKind === "device"}
-
Assembled and sent {runFileName} .
+ {#if run.lastRunKind === "device"}
+
Assembled and sent {run.runFileName} .
{:else}
-
- {#if outputPath}
- Saved {savedFile?.name} in
- {outputPath} .
- {:else}
- Downloaded {savedFile?.name} .
- {/if}
-
+
Downloaded {run.savedFile?.name} .
{/if}
- {#if savedFile}
-
{formatBytes(savedFile.byteLength)}
+ {#if run.savedFile}
+
{formatBytes(run.savedFile.byteLength)}
{/if}
- {#if readMode}
+ {#if run.readMode}
- cells {readMode}{#if writeMode}
- · map {writeMode}{/if}{#if cachedCells > 0}
- · {cachedCells} reused from this computer ({formatBytes(cachedBytes)} not
+ cells {run.readMode}{#if run.writeMode}
+ · map {run.writeMode}{/if}{#if run.cachedCells > 0}
+ · {run.cachedCells} reused from this computer ({formatBytes(run.cachedBytes)} not
downloaded){/if}
{/if}
- {#each runWarnings as w, k (k)}
+ {#each run.runWarnings as w, k (k)}
{w}
{/each}
- {:else if phase === "error"}
+ {:else if run.phase === "error"}
- {#if incompleteFileRemains}
- The map was not completed. Discard the file it left behind: {errorMessage}
+ {#if run.persisted}
+ The map was not completed. Discard the file it left behind: {run.errorMessage}
{:else}
- Nothing was saved: {errorMessage}
+ Nothing was saved: {run.errorMessage}
{/if}
- {:else if phase === "cancelled"}
+ {:else if run.phase === "cancelled"}
- {#if incompleteFileRemains}
+ {#if run.persisted}
Cancelled — discard the incomplete file it left behind.
{:else}
Cancelled — nothing was saved.
diff --git a/builder/web/src/components/coverage/MapSummary.svelte.test.ts b/builder/web/src/components/coverage/MapSummary.svelte.test.ts
index 6f62fef30d..009fbcb328 100644
--- a/builder/web/src/components/coverage/MapSummary.svelte.test.ts
+++ b/builder/web/src/components/coverage/MapSummary.svelte.test.ts
@@ -62,10 +62,8 @@ describe("MapSummary", () => {
it.each([
{ label: "a region border", kind: "region", drawnCells: ["border"], warns: false },
- ...["box", "lasso", "corridor"].flatMap((kind) => [
- { label: `a region and a fully covered ${kind}`, kind, drawnCells: ["full"], warns: false },
- { label: `a region and a partly covered ${kind}`, kind, drawnCells: ["full", "border"], warns: true },
- ]),
+ { label: "a region and a fully covered box", kind: "box", drawnCells: ["full"], warns: false },
+ { label: "a region and a partly covered box", kind: "box", drawnCells: ["full", "border"], warns: true },
])("discloses only affected drawn coverage for $label", async ({ kind, drawnCells, warns }) => {
const region = { id: "region", kind: "region" };
const drawn = { id: "drawn", kind };
diff --git a/builder/web/src/components/coverage/PartsList.svelte b/builder/web/src/components/coverage/PartsList.svelte
index 41381ba0b5..e0507e97a8 100644
--- a/builder/web/src/components/coverage/PartsList.svelte
+++ b/builder/web/src/components/coverage/PartsList.svelte
@@ -1,16 +1,10 @@
{#if parts.length === 0}
@@ -28,7 +22,7 @@
}}
>
- {part.kind === "corridor" ? `Corridor — ${part.name}` : part.name}
+ {part.name}
{#if regionError}
{regionError}
{#if part.kind === "region" && store.region(part.regionId)}
@@ -47,27 +41,6 @@
{/each}
-
- {#if hasCorridor}
-
-
-
- Corridor width — all routes
-
- ± {radiusKm} km
-
-
- store.setCorridorRadius(Number((e.currentTarget as HTMLInputElement).value) * 1000)}
- />
-
- {/if}
{/if}
diff --git a/builder/web/src/components/coverage/SkinStep.svelte b/builder/web/src/components/coverage/SkinStep.svelte
index fb5cf9df72..cfa9f245af 100644
--- a/builder/web/src/components/coverage/SkinStep.svelte
+++ b/builder/web/src/components/coverage/SkinStep.svelte
@@ -9,7 +9,8 @@
import { renderSkinPreviewFrames, type SkinPreviewFrame } from "../../lib/skin/preview";
import { confirmAction } from "../../lib/ui/confirm.svelte";
- let { store }: { store: CoverageStore } = $props();
+ /** `plain`: only the choice, each skin with its name, with no note and no editor, for a window of the shell. */
+ let { store, plain = false }: { store: CoverageStore; plain?: boolean } = $props();
let previewUrls = $state>({});
let customPreviewFrames = $state>({});
let editing = $state(null);
@@ -44,7 +45,8 @@
});
$effect(() => {
- const custom = store.skins.filter((skin) => isCustomSkinId(skin.id));
+ // A catalog skin with no stored picture is drawn here, as a custom skin is.
+ const custom = store.skins.filter((skin) => isCustomSkinId(skin.id) || !skin.preview);
const controller = new AbortController();
let live = true;
if (custom.length === 0) {
@@ -80,11 +82,11 @@
- (mode = "light")}>Light
- (mode = "dark")}>Dark
+ (mode = "light")}>Day
+ (mode = "dark")}>Night
-Light and dark styles are included.
-
+{#if !plain}
Light and dark styles are included.
{/if}
+
{#each visibleSkins as skin (skin.id)}
mode === "light" ? (store.lightSkinId = skin.id) : (store.darkSkinId = skin.id)}
>
- {#if isCustomSkinId(skin.id)}
- {#if customPreviewFrames[skin.id]}
-
-
-
- {:else}
-
- {/if}
+ {#if customPreviewFrames[skin.id]}
+
+
+
{:else if previewUrls[skin.id]}
{/if}
- {#if isCustomSkinId(skin.id)}
+ {#if plain || isCustomSkinId(skin.id)}
{skin.name}
- custom
+ {#if isCustomSkinId(skin.id)}custom {/if}
{/if}
{/each}
+{#if !plain}
{#if isCustomSkinId(selected.id)}
Delete
@@ -134,6 +133,7 @@
{isCustomSkinId(selected.id) ? `Edit ${mode}` : `Customize ${mode}`}
+{/if}
{#if editing}
(editing = null)} />
@@ -146,6 +146,10 @@
gap: 10px;
}
+ .cards.plain {
+ margin-top: 12px;
+ }
+
.theme-tabs {
display: inline-flex;
padding: 3px;
diff --git a/builder/web/src/components/coverage/ToolIcon.svelte b/builder/web/src/components/coverage/ToolIcon.svelte
index e5467a1e0f..90963e7e3b 100644
--- a/builder/web/src/components/coverage/ToolIcon.svelte
+++ b/builder/web/src/components/coverage/ToolIcon.svelte
@@ -1,11 +1,11 @@
- {:else if kind === "box"}
+ {:else}
- {:else if kind === "corridor"}
-
-
-
-
- {:else}
-
-
-
-
{/if}
diff --git a/builder/web/src/components/device/CardFormat.svelte b/builder/web/src/components/device/CardFormat.svelte
index ead8f97fae..665000ba4c 100644
--- a/builder/web/src/components/device/CardFormat.svelte
+++ b/builder/web/src/components/device/CardFormat.svelte
@@ -1,6 +1,5 @@
-
- {#snippet children()}
- {#if deviceHolder.error}
- {deviceHolder.error}
- {:else if !session}
- Looking for a device…
- {:else if session.status === "unsupported"}
- {session.error}
- {:else if session.status === "ready" && session.client}
-
-
-
- Connected
- {#if session.info}{session.info.hardwareRevision} {/if}
-
-
void session.disconnect()}>
- Disconnect
-
-
-
- {#await loadSurfaces()}
- Loading…
- {:then { default: Surfaces }}
-
- {:catch}
-
- The device tools could not be loaded. Check your connection and reload the page.
-
- {/await}
- {:else if session.status === "connecting"}
- Connecting…
- {:else}
- {#if deviceHolder.interrupted}
- {deviceHolder.interrupted}
- {/if}
-
-
- Connect device
-
-
Connect by USB, then choose your device.
-
- {#if session.status === "error" && session.error}
- {session.error}
- {/if}
- {/if}
- {/snippet}
-
- {#snippet unavailable(reason)}
- Connect device
- {/snippet}
-
+{#if deviceHolder.error}
+ {deviceHolder.error}
+{:else if !session}
+ Looking for a device…
+{:else if session.status === "unsupported"}
+ {session.error}
+{:else if session.status === "ready" && session.client}
+
+
+
+ Connected
+ {#if session.info}{session.info.hardwareRevision} {/if}
+
+
void session.disconnect()}>
+ Disconnect
+
+
+
+ {#await loadSurfaces()}
+ Loading…
+ {:then { default: Surfaces }}
+
+ {:catch}
+
+ The device tools could not be loaded. Check your connection and reload the page.
+
+ {/await}
+{:else if session.status === "connecting"}
+ Connecting…
+{:else}
+ {#if deviceHolder.interrupted}
+ {deviceHolder.interrupted}
+ {/if}
+
+
+ Connect device
+
+
Connect by USB, then choose your device.
+
+ {#if session.status === "error" && session.error}
+ {session.error}
+ {/if}
+{/if}
diff --git a/builder/web/src/components/device/PopMenu.svelte b/builder/web/src/components/device/PopMenu.svelte
deleted file mode 100644
index 68e00e3156..0000000000
--- a/builder/web/src/components/device/PopMenu.svelte
+++ /dev/null
@@ -1,148 +0,0 @@
-
-
-
-
-
-
-
-
diff --git a/builder/web/src/components/device/PreviewModal.svelte b/builder/web/src/components/device/PreviewModal.svelte
deleted file mode 100644
index f29f99b7d2..0000000000
--- a/builder/web/src/components/device/PreviewModal.svelte
+++ /dev/null
@@ -1,932 +0,0 @@
-
-
-
-
-
- e.target === e.currentTarget && onclose()}>
-
-
-
{title}
-
- {#each stats as stat (stat.label)}
-
- {stat.label}
- {stat.value}
-
- {/each}
- {#if waypoints.length > 0}
-
- Waypoints
- {waypoints.length}
-
- {/if}
-
-
- {@render actions?.()}
-
- ✕
-
-
-
-
-
- {#if waypoints.length > 0}
-
-
Waypoints · {waypoints.length}
-
- {#each waypoints as w, i (i)}
- focusWaypoint(i)}
- >
-
- {w.name || "Waypoint"}
- {#if w.color}
-
- {/if}
- km {km(w.distM)}
-
- {/each}
-
-
- {/if}
-
-
- {#if hasProfile}
-
-
queueHover(null)}
- onpointercancel={() => (drag = null)}
- ondblclick={resetZoom}
- >
- {#if profile}
-
-
-
-
- {/if}
- {#each ribbon as span, i (i)}
-
- {/each}
- {#each axis.boundariesM as boundary, i (i)}
- {@const pct = pctInWindow(boundary)}
- {#if pct !== null}
-
- {/if}
- {/each}
- {#each waypoints as w, i (i)}
- {@const pct = pctInWindow(w.distM)}
- {#if pct !== null}
-
- {/if}
- {/each}
- {#if drag && drag.mode === "select" && Math.abs(drag.to - drag.from) >= MIN_DRAG_FRACTION}
-
- {/if}
- {#if hoverPct !== null}
-
- {#if hoverEle !== null}
-
-
- {Math.round(hoverEle).toLocaleString()} m
-
- {/if}
- {/if}
- {#if profile}
-
- Elevation · {Math.round(profile.minEle).toLocaleString()} –
- {Math.round(profile.maxEle).toLocaleString()} m
- {#if !isFullWindow(win)}
- · km {km(profile.startM)} – {km(profile.endM)} of {km(profile.totalM)}
- {:else}
- · {km(profile.totalM)} km
- {/if}
-
- {:else}
-
No elevation in this span — double-click to reset.
- {/if}
-
drag or scroll to zoom · ctrl/⌘-drag pans · double-click resets
-
- {/if}
-
-
-
-
diff --git a/builder/web/src/components/device/RideExport.svelte b/builder/web/src/components/device/RideExport.svelte
index 0c4ba692b5..bca13b876a 100644
--- a/builder/web/src/components/device/RideExport.svelte
+++ b/builder/web/src/components/device/RideExport.svelte
@@ -23,7 +23,6 @@
-->
-
-
-
-
Ride library
-
- {listed.length} ride{listed.length === 1 ? "" : "s"}{#if totalKm > 0} · {totalKm.toLocaleString()} km
- total{/if}
-
-
- view && void library.reveal(view.folder)}>
- {view?.folder ?? "…"}
-
- void relocate()}>Change…
- {#if rides && scope}
- void pull()}>
- ⤓ Pull rides from device
-
- {:else}
- Plug the device in to pull new rides.
- {/if}
-
-
-
-
-
- {#if error}
-
{error}
- {/if}
-
- {#if report && report.failed.length > 0}
-
- {report.failed.length} ride{report.failed.length === 1 ? "" : "s"} could not be saved and
- {report.failed.length === 1 ? "was" : "were"} left on the device:
- {report.failed.map((f) => `${f.name} — ${f.message}`).join("; ")}
-
- {/if}
- {#if report && report.recording > 0}
-
- {report.recording === 1 ? "One ride is" : `${report.recording} rides are`} still being
- recorded on the device and could not be copied. Finish
- {report.recording === 1 ? "it" : "them"} there, then pull again.
-
- {/if}
-
- {#if listed.length === 0}
-
- No rides here yet. Plug the device in and pull — each ride lands as a GPX file in the
- folder above, where you can back it up or drag it into anything that reads GPX.
-
- {:else}
-
- {#each listed as ride (ride.key)}
- {@const path = trackPath(ride.track, PREVIEW.width, PREVIEW.height)}
- (hovered = { key: ride.key, from: "list" })}
- onmouseleave={() => (hovered = null)}
- >
- onpreview?.(ride)}
- >
-
- {#if path}
-
-
-
- {/if}
-
-
- {ride.name || `Ride ${ride.objectId}`}
- {facts(ride)}
- {#if !ride.present}
-
- not on this computer any more — pull from the device to restore it
-
- {/if}
-
-
- void showInFolder(ride)}
- >
-
-
-
-
-
- ›
-
- {/each}
-
-
- {#if missingArchive > 0}
-
- {missingArchive} ride{missingArchive === 1 ? "" : "s"} listed here
- {missingArchive === 1 ? "is" : "are"} no longer on this computer — pull from the
- device to restore {missingArchive === 1 ? "it" : "them"}.
-
- {/if}
- {/if}
-
-
-
- Copying a ride here does not tell the device anything — over the cable a ride is read and
- nothing more, so the device still counts every ride as un-copied and keeps it under its own
- rules. Check Settings → Rides on the device for how long it keeps one; the
- app cannot read that setting. The copies in this folder are yours and are never deleted by
- this app.
-
-
-
-
-
-
- (hovered = key ? { key, from: "map" } : null)}
- onopen={openByKey}
- />
-
-
-
-
-
diff --git a/builder/web/src/components/device/RideMap.svelte b/builder/web/src/components/device/RideMap.svelte
deleted file mode 100644
index 4c755dcc2c..0000000000
--- a/builder/web/src/components/device/RideMap.svelte
+++ /dev/null
@@ -1,209 +0,0 @@
-
-
-
-
-
-
diff --git a/builder/web/src/components/device/RideTiles.svelte b/builder/web/src/components/device/RideTiles.svelte
deleted file mode 100644
index 794575b205..0000000000
--- a/builder/web/src/components/device/RideTiles.svelte
+++ /dev/null
@@ -1,160 +0,0 @@
-
-
-
-
- {#each rides as ride (ride.objectId)}
- {@const recording = isRecording(ride)}
- {@const held = heldHere?.has(ride.objectId) ?? false}
-
onopen(ride)}
- >
- {#snippet thumb()}
- {@const track = trackFor(ride.objectId)}
-
-
- {#snippet tag()}
- {#if recording}
- recording
- {:else if heldHere}
- {#if held}
- in library
- {:else}
- not backed up
- {/if}
- {/if}
- {/snippet}
-
- {/snippet}
-
- {nameOf(ride)}
-
-
- {recording ? "still on the device" : formatBytes(Number(ride.payloadLength))}
-
-
- {#if onpull}
- {
- e.stopPropagation();
- onpull?.(ride);
- }}
- >
- ⤓
-
- {/if}
-
- {/each}
-
-
-
diff --git a/builder/web/src/components/device/RouteTiles.svelte b/builder/web/src/components/device/RouteTiles.svelte
deleted file mode 100644
index 46a243a8e0..0000000000
--- a/builder/web/src/components/device/RouteTiles.svelte
+++ /dev/null
@@ -1,152 +0,0 @@
-
-
-
-
- {#each routes as route (route.objectId)}
-
onopen(route)}>
- {#snippet thumb()}
- {@const track = trackFor(route.objectId)}
-
-
- {/snippet}
-
- {#if editing && editing.id === route.objectId}
-
- commitEdit(route)}
- onkeydown={(e) => onEditKey(e, route)}
- />
- {:else}
- {nameOf(route)}
- {/if}
- {formatBytes(Number(route.payloadLength))}
-
-
- menuPick(e, () => (editing = { id: route.objectId, value: route.displayName }))}
- >
- Rename…
-
- {#each trips as trip (trip.objectId)}
- menuPick(e, () => onaddtotrip(route, trip.objectId))}>
- Add to “{trip.displayName || `Trip ${trip.objectId}`}”
-
- {/each}
- menuPick(e, () => onaddtotrip(route, null))}>
- New trip from this route
-
- menuPick(e, () => ondelete(route))}>
- Delete…
-
-
-
- {/each}
- {@render children?.()}
-
-
-
diff --git a/builder/web/src/components/device/Tile.svelte b/builder/web/src/components/device/Tile.svelte
deleted file mode 100644
index e585030211..0000000000
--- a/builder/web/src/components/device/Tile.svelte
+++ /dev/null
@@ -1,118 +0,0 @@
-
-
-
-
- {@render thumb?.()}
-
- {@render children?.()}
-
-
-
-
diff --git a/builder/web/src/components/device/TrackThumb.svelte b/builder/web/src/components/device/TrackThumb.svelte
deleted file mode 100644
index 6eeecc39cc..0000000000
--- a/builder/web/src/components/device/TrackThumb.svelte
+++ /dev/null
@@ -1,127 +0,0 @@
-
-
-
-
- {#if drawn.length > 0}
-
- {#each drawn as segment, i (i)}
-
- {/each}
- {#if first}
-
- {/if}
- {#if last}
-
- {/if}
-
- {/if}
- {#if tag}
-
{@render tag()}
- {/if}
-
-
-
diff --git a/builder/web/src/components/device/TripBand.svelte b/builder/web/src/components/device/TripBand.svelte
deleted file mode 100644
index c80edca10d..0000000000
--- a/builder/web/src/components/device/TripBand.svelte
+++ /dev/null
@@ -1,356 +0,0 @@
-
-
-
-
-
-
- {#snippet tag()}
- trip
- {/snippet}
-
-
-
-
- {#if editing !== null}
-
-
- {:else}
-
{name}
- {/if}
-
- {#if stageCount !== null}{stageCount} stage{stageCount === 1 ? "" : "s"}{/if}
-
-
- menuPick(e, () => (editing = trip.displayName))}>
- Rename…
-
- menuPick(e, ondelete)}>Delete trip…
-
-
- {#if trip.detail === null}
-
The trip's stage list could not be read.
- {:else}
- {#each stages as stage, index (`${stage.id}-${index}`)}
-
-
- {#if stage.route}
- {@const route = stage.route}
- onopenstage(route)}
- >
- {route.displayName || `Route ${stage.id}`}
-
- {:else}
-
- Route {stage.id}
- no longer on the device
-
- {/if}
-
- onmovestage(index, -1)}>↑
- onmovestage(index, 1)}>↓
- onremovestage(index)}>×
-
-
- {/each}
- {/if}
-
-
-
-
diff --git a/builder/web/src/components/device/TripDropDialog.svelte b/builder/web/src/components/device/TripDropDialog.svelte
deleted file mode 100644
index 353f5d7a30..0000000000
--- a/builder/web/src/components/device/TripDropDialog.svelte
+++ /dev/null
@@ -1,302 +0,0 @@
-
-
-
-
-
- e.target === e.currentTarget && oncancel()}>
-
-
- {rows.length}
- GPX files → {good.length || rows.length}
- {(good.length || rows.length) === 1 ? "route" : "routes"}
-
-
-
- {#each rows as row, index (row.file)}
-
-
- move(index, -1)}>↑
- move(index, 1)}>↓
-
-
- {#if row.prepared}
- {row.prepared.header.name}
- {row.file.name} → {summary(row.prepared)}
- {:else if row.error}
- {row.file.name}
- {row.error}
- {:else}
- {row.file.name}
- converting…
- {/if}
-
- drop(index)}>×
-
- {/each}
-
-
- {#if failed.length > 0}
-
- {failed.length}
- {failed.length === 1 ? "file" : "files"} could not be converted and will be left out.
-
- {/if}
-
-
- Group them as a trip?
-
-
-
-
- Cancel
-
- add(false)}>
- Add as separate routes
-
- add(true)}>
- Add as a trip
-
-
-
-
-
-
-
diff --git a/builder/web/src/components/planner/CompareList.svelte b/builder/web/src/components/planner/CompareList.svelte
index 76d7c99e04..f2315d9cf9 100644
--- a/builder/web/src/components/planner/CompareList.svelte
+++ b/builder/web/src/components/planner/CompareList.svelte
@@ -1,7 +1,9 @@
+
+ { if (open && !box?.contains(event.target as Node)) open = false; }} />
+
+{#if credits.length}
+
+
+
{credits.join(' · ')}
+
{ if ('pointerType' in event && event.pointerType === 'touch') open = !open; }}>
+
+
+
+{/if}
+
+
diff --git a/builder/web/src/components/planner/DayRow.svelte b/builder/web/src/components/planner/DayRow.svelte
index f7d4925a3f..16cafaf897 100644
--- a/builder/web/src/components/planner/DayRow.svelte
+++ b/builder/web/src/components/planner/DayRow.svelte
@@ -7,6 +7,8 @@
import { kindLabel, sleepIcon } from '../../lib/planner/search/presentation';
import { dayStops, duration, planView, type ItineraryDay, type RoutePoint, type Trip, type Day } from '../../lib/planner/editor';
import type { RoutingLine } from '../../lib/planner/routing';
+ import { distanceIn, heightIn, heightUnit } from '../../lib/settings/format';
+ import { settings } from '../../lib/settings/settings.svelte';
let {
trip, line, day, days, theme, scale, expanded, choosing, conflict, selectedId, revealId, hoveredId = null, onHover, calendar,
@@ -79,9 +81,9 @@
{day.number}
Day {day.number}
- {duration(day.hours)} · ↑ {ascentKnown ? day.ascent : '—'} m · ↓ {ascentKnown ? day.descent : '—'} m{day.pinned?.placeKind ? ` · ${kindLabel(day.pinned.placeKind)}` : ''}
+ {duration(day.hours)} · ↑ {ascentKnown ? Math.round(heightIn(day.ascent)) : '—'} {heightUnit()} · ↓ {ascentKnown ? Math.round(heightIn(day.descent)) : '—'} {heightUnit()}{day.pinned?.placeKind ? ` · ${kindLabel(day.pinned.placeKind)}` : ''}
- {day.distance.toFixed(1)}km
+ {distanceIn(day.distance * 1000).toFixed(1)}{settings.units}
@@ -95,11 +97,11 @@
{#if expanded}
Stops along the day
- {#if stops.length}
{start} 0 km
{/if}
+ {#if stops.length}
{start} 0 {settings.units}
{/if}
{#each stops as { point, km } (point.id)}
onHover?.(point.id)} onmouseleave={() => onHover?.(null)} onfocus={() => onHover?.(point.id)} onblur={() => onHover?.(null)} onclick={() => onInspect(point)} {@attach reveal(point.id)}>
{point.label}
- {stopKinds[point.kind].label} · at {km.toFixed(1)} km
+ {stopKinds[point.kind].label} · at {distanceIn(km * 1000).toFixed(1)} {settings.units}
{/each}
{#if last || day.pinned}
@@ -108,7 +110,7 @@
{/if}
{#if stops.length && !last && !day.pinned}
-
Suggested day endChoose an overnight below {day.distance.toFixed(1)} km
+
Suggested day endChoose an overnight below {distanceIn(day.distance * 1000).toFixed(1)} {settings.units}
{/if}
{stops.length ? 'Click the map to add a stop. Drag the route to reshape it.' : 'No stops yet. Click the map to add one.'}
{#if choosing && !last}
diff --git a/builder/web/src/components/planner/LayerDateBar.svelte b/builder/web/src/components/planner/LayerDateBar.svelte
index 9fabf21242..4638adb37f 100644
--- a/builder/web/src/components/planner/LayerDateBar.svelte
+++ b/builder/web/src/components/planner/LayerDateBar.svelte
@@ -1,7 +1,7 @@
-
Distance {distance.toFixed(1)}km
-
Ascent {ascent ?? '—'}m
-
Descent {descent ?? '—'}m
+
Distance {distanceIn(distance * 1000).toFixed(1)}{settings.units}
+
Ascent {height(ascent)}{heightUnit()}
+
Descent {height(descent)}{heightUnit()}
{walking ? 'Walking time' : 'Riding time'} {minutes === null ? '—' : minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)}h ${minutes % 60}m`}
diff --git a/builder/web/src/components/planner/SignedRoutes.svelte b/builder/web/src/components/planner/SignedRoutes.svelte
index 6baa8e5443..4932414d30 100644
--- a/builder/web/src/components/planner/SignedRoutes.svelte
+++ b/builder/web/src/components/planner/SignedRoutes.svelte
@@ -1,7 +1,7 @@
+
+
+ {#each climbs as climb (climb.index)}
+
+ {/each}
+
+{#each climbs as climb (climb.index)}
+
+{/each}
+
+
diff --git a/builder/web/src/components/route/Detail.svelte b/builder/web/src/components/route/Detail.svelte
new file mode 100644
index 0000000000..19073dbeee
--- /dev/null
+++ b/builder/web/src/components/route/Detail.svelte
@@ -0,0 +1,211 @@
+
+
+
+ {#if message}
+
{message}
+
‹ Routes
+ {:else}
+
+ {#if failure}
{failure}
{/if}
+
+ {@render left?.()}
+ {@render picture?.()}
+
+ {@render children?.()}
+ {/if}
+
+
+
diff --git a/builder/web/src/components/route/ElevationRow.svelte b/builder/web/src/components/route/ElevationRow.svelte
new file mode 100644
index 0000000000..3bc129a2a0
--- /dev/null
+++ b/builder/web/src/components/route/ElevationRow.svelte
@@ -0,0 +1,164 @@
+
+
+
+
+
+
+ {#each bands as path, band (band)}
+ {#if path} {/if}
+ {/each}
+
+
{formatHeight(high)}
+
{formatHeight(low)}
+ {#each lines as share, i (i)}
+ {#if share > from && share <= to}
{/if}
+ {/each}
+ {#each shown as climb (climb.index)}
+
+ {#if climb.text}
+
{climb.text}
+ {/if}
+ {/each}
+
+
+
diff --git a/builder/web/src/components/route/Facts.svelte b/builder/web/src/components/route/Facts.svelte
new file mode 100644
index 0000000000..9a5a92cf57
--- /dev/null
+++ b/builder/web/src/components/route/Facts.svelte
@@ -0,0 +1,296 @@
+
+
+{#snippet number(label: string, value: string)}
+
{label} {value}
+{/snippet}
+
+{#snippet pin(stop: Waypoint, detail: string)}
+
{stop.number} {stop.point.label} {#if detail}{detail} {/if}
+{/snippet}
+
+{#snippet climbRow(climb: Climb)}
+ {@const numbers = `${at(climb.from)} · ${formatDistance((climb.to - climb.from) * 1000)} · ${grade(climb)}`}
+
+ onopen(climb)}>
+
+ {#await townOf(climb.top)}
+ {numbers}
+ {:then name}
+ {#if name}To {name} {numbers} {:else}{numbers} {/if}
+ {/await}
+
+
+
+
+{/snippet}
+
+{#snippet climbCard(climb: Climb, line: RoutingLine)}
+ {@const total = planView(trip, line).total}
+ {@const top = profileHeightAt(climb.to / total, profileSamples(line))}
+
onopen(undefined)}>‹ Climbs
+ {#await townOf(climb.top)}
+
Climb
+ {:then name}
+
{name ? `To ${name}` : 'Climb'}
+ {/await}
+
{formatAlong(climb.from * 1000)} to {formatAlong(climb.to * 1000)}
+
+ {@render number('Length', formatDistance((climb.to - climb.from) * 1000))}
+ {@render number('Climb', formatHeight(climb.ascent))}
+ {@render number('Mean grade', grade(climb))}
+ {@render number(`Steepest ${formatDistance(STEEPEST_KM * 1000)}`, formatPercent(climb.steepest))}
+ {@render number('Top', top === null ? '–' : formatHeight(top))}
+
+ {#if facts && facts.climbs.length > 1}
+
Other climbs
+
{#each facts.climbs.filter(other => other !== climb) as other (other.from)}{@render climbRow(other)}{/each}
+ {/if}
+{/snippet}
+
+
+
+ {#if shownClimb && line}
+ {@render climbCard(shownClimb, line)}
+ {:else}
+
+ {@render number('Length', summary ? formatDistance(summary.lengthM) : '–')}
+ {@render number('Climb', summary ? formatHeight(summary.climbM) : '–')}
+ {#if !days}
+ {@render number('Time', summary ? duration(summary.seconds / 3600) : '–')}
+ {@render number('Highest point', summary?.highestM != null ? formatHeight(summary.highestM) : '–')}
+ {/if}
+
+ {#if changed}Changed since the last save
{/if}
+
+ {#if error}
+ {error}
+ {:else if !facts}
+ Finding the climbs…
+ {:else if days}
+ Days
+
+ {#each days as day (day.number)}
+ {#if day.rest}
+ Day {day.number} {trip.restNames?.[day.restIndex!] || 'Rest day'}
+ {:else}
+ {@const from = day.ridingNumber === 1 ? ends[0]?.label : trip.points.find(p => p.kind === 'night' && p.night === day.ridingNumber - 1)?.label}
+ {@const last = day.ridingNumber === days.filter(d => !d.rest).length}
+
+ Day {day.number}
+
+ {dayTitle(from, last ? finish?.label : day.pinned?.label)}
+ {formatDistance(day.distance * 1000)} · {formatHeight(day.ascent)} up · {duration(day.hours)}
+
+
+ {#each day.stops as stop (stop.point.id)}{@render pin(stop, about(stop.point))}{/each}
+ {#if !last}
+ {day.pinned?.label ?? 'Not chosen'}Night
+ {/if}
+ {/if}
+ {/each}
+
+ {#if facts.climbs.length}
+ Climbs
+ {#each facts.climbs as climb (climb.from)}{@render climbRow(climb)}{/each}
+ {/if}
+ {:else}
+ {#if facts.climbs.length}
+ Climbs
+ {#each facts.climbs as climb (climb.from)}{@render climbRow(climb)}{/each}
+ {/if}
+ {#if facts.stops.length}
+ Waypoints
+ {#each facts.stops as stop (stop.point.id)}{@render pin(stop, [about(stop.point), at(stop.km)].filter(Boolean).join(' · '))}{/each}
+ {/if}
+ {/if}
+ {/if}
+
+
+
+
diff --git a/builder/web/src/components/route/Lanes.svelte b/builder/web/src/components/route/Lanes.svelte
new file mode 100644
index 0000000000..0dbbcfa80e
--- /dev/null
+++ b/builder/web/src/components/route/Lanes.svelte
@@ -0,0 +1,407 @@
+
+
+
+
+{#if header || (part && partText)}
+
+{/if}
+{#if rows.length}
+
+
row.scale)} class:bare={rows.every(row => !row.label)} bind:this={root} onpointermove={move} onpointerdown={start} onpointerup={end} onpointercancel={() => down = null}
+ onpointerleave={() => { if (!down) onpointer(null); }}>
+ {#each rows as row, i (i)}
+ {#if row.label}
+
+ {#if row.open}
+
+
{row.label} {#if row.note}{row.note} {/if}
+ {:else}
+ {row.label}{#if row.note}
{row.note} {/if}
+ {/if}
+
+ {/if}
+
{@render row.draw()}
+ {#if row.scale}
{row.scale[0]} {row.scale[1]}
{/if}
+ {/each}
+
+ {#if corner}
{@render corner()}
{/if}
+
+ {@render marks?.()}
+ {#each ticks as tick, i (i)}{tick.label} {/each}
+
+
+
onpointer(null)}>
+ {#if part}
+
+ {#if part[0] > 0} {/if}
+ {#if part[1] < 1} {/if}
+ {/if}
+ {#if pointer !== undefined}
+
+ {#if chip} .7}>{@render chip()} {/if}
+
+ {/if}
+
+
+{/if}
+
+
diff --git a/builder/web/src/components/route/Menu.svelte b/builder/web/src/components/route/Menu.svelte
new file mode 100644
index 0000000000..3fd5c7d3b1
--- /dev/null
+++ b/builder/web/src/components/route/Menu.svelte
@@ -0,0 +1,115 @@
+
+
+
{ if (open && !root?.contains(event.target as Node)) open = false; }}
+ onkeydowncapture={escape} onresize={() => open = false} />
+
+
+
+
diff --git a/builder/web/src/components/route/Picture.svelte b/builder/web/src/components/route/Picture.svelte
new file mode 100644
index 0000000000..9d57379f4f
--- /dev/null
+++ b/builder/web/src/components/route/Picture.svelte
@@ -0,0 +1,143 @@
+
+
+
+
+ {#if covered}
+
+ onpoint(metres === null || !summary.lengthM ? null : metres / summary.lengthM)} />
+ {#if !side && mapLarge} swapped = false}> {/if}
+
+
+ {/if}
+
+
+ {#if !side && !mapLarge} swapped = true}> {/if}
+
+
+
+
+
diff --git a/builder/web/src/components/route/Plot.svelte b/builder/web/src/components/route/Plot.svelte
new file mode 100644
index 0000000000..b3f14684ec
--- /dev/null
+++ b/builder/web/src/components/route/Plot.svelte
@@ -0,0 +1,154 @@
+
+
+
+
+ {#if area}
+
+ ({ a: from, b: to, index }))} {lit} {hover} />
+ {/if}
+ {#each lines as line (line.stroke)} {/each}
+
+ {#each rules as { zone, index } (index)}
+
{zone.name} from {format(zone.from)}
+ {/each}
+ {#if marked && mark !== undefined}
+
+
FLIP} style:left={`${mark * 100}%`}>{format(marked.value)}
+ {/if}
+
+
+
diff --git a/builder/web/src/components/route/RideFacts.svelte b/builder/web/src/components/route/RideFacts.svelte
new file mode 100644
index 0000000000..c6604817cb
--- /dev/null
+++ b/builder/web/src/components/route/RideFacts.svelte
@@ -0,0 +1,287 @@
+
+
+{#snippet number(label: string, value: string)}
+
{label} {value}
+{/snippet}
+
+{#snippet pair(label: string, selected: string, whole: string)}
+ {label} {selected} {whole}
+{/snippet}
+
+
+
+ {#if part && channels}
+
+ Selected Whole ride
+
+ {@render pair('Distance', formatDistance(part.lengthM), formatDistance(summary.lengthM))}
+ {@render pair('Climb', formatHeight(part.climbM), formatHeight(summary.climbM))}
+ {@render pair('Time moving', hours(part.movingS), hours(summary.movingS))}
+ {@render pair('Speed', speedText(part.speed), speedText(speed))}
+ {#each sensors as { key, label, unit, zoneUnit, missing } (key)}
+ {#if channels[key]}
+ {@render pair(label, mean(part.channels[key], unit), mean(channels[key], unit))}
+ {#if missing && part.channels[key]} {/if}
+ {/if}
+ {/each}
+
+
+ {:else}
+
+ {@render number('Distance', formatDistance(summary.lengthM))}
+ {@render number('Climb', formatHeight(summary.climbM))}
+ {@render number('Time moving', hours(summary.movingS))}
+ {@render number('Speed', speedText(speed))}
+
+
+ {#if unreadable}
+ The file of this ride cannot be read.
+ {:else if channels && climbs}
+ channels[key])}>
+ {#each sensors as { key, label, unit, zoneUnit, missing } (key)}
+ {@const channel = channels[key]}
+ {#if channel}
+
+ {label} {mean(channel, unit)} {missing ? `max ${Math.round(channel.max)}` : ''}
+ {#if missing}
{/if}
+
+ {/if}
+ {/each}
+
+ {#if climbs.length}
+
+
Climbs{#if climbs.length > 1}{climbs.length} {/if}
+
+ {#each climbs as climb (climb.first)}
+ {@const numbers = [formatDistance((climb.to - climb.from) * 1000), hours(climb.seconds), climb.powerW === undefined ? '' : `${Math.round(climb.powerW)} W`].filter(Boolean).join(' · ')}
+
+ onclimb(climb)}>
+ {#await townOf(climb.top)}
+ Climb
+ {:then name}
+ {name ? `To ${name}` : 'Climb'}
+ {/await}
+ {numbers}
+
+
+ {/each}
+
+
+ {/if}
+ {/if}
+ {/if}
+
+
+
+
diff --git a/builder/web/src/components/route/RideLarge.svelte b/builder/web/src/components/route/RideLarge.svelte
new file mode 100644
index 0000000000..4f4e5c1dc0
--- /dev/null
+++ b/builder/web/src/components/route/RideLarge.svelte
@@ -0,0 +1,310 @@
+
+
+
+
+{#snippet plot()}
+
+{/snippet}
+
+{#snippet chip()}{pointer === undefined ? '' : formatDistance((view[0] + pointer * length) * lengthM)}{/snippet}
+
+{#snippet beside()}
+ {#if zoomed}
+
+ Whole ride
+
+ {/if}
+{/snippet}
+
+
+ {#snippet children(close)}
+
+
+
drag = null} ondblclick={showWhole}>
+ drag = next} onclick={click} onpointer={x => pointer = x ?? undefined} />
+
+ {#if shown.times?.zones}
+
+ {/if}
+
+
+
+ {#if shown.times && !shown.times.zones && missing}
+
+ { if ((event.target as Element).closest('a')) close(); }}>
+ {/if}
+ {/snippet}
+
+
+
diff --git a/builder/web/src/components/route/RideLines.svelte b/builder/web/src/components/route/RideLines.svelte
new file mode 100644
index 0000000000..2c2c486ec9
--- /dev/null
+++ b/builder/web/src/components/route/RideLines.svelte
@@ -0,0 +1,311 @@
+
+
+
+
+{#snippet plot(key: Key)}
+ = 0 ? chosen : undefined} hover={key === 'elevation' && hovered >= 0 ? hovered : undefined} mark={pointer} format={series[key].format} bind:width />
+{/snippet}
+{#snippet elevationRow()}{@render plot('elevation')}{/snippet}
+{#snippet speedRow()}{@render plot('speed')}{/snippet}
+{#snippet hrRow()}{@render plot('hr')}{/snippet}
+{#snippet powerRow()}{@render plot('power')}{/snippet}
+{#snippet cadenceRow()}{@render plot('cadence')}{/snippet}
+
+{#snippet chip()}{foot}{/snippet}
+
+{#snippet marks()}
+ {#each found as stop (stop.first)}
+ {@const { left, wide } = markOf(stop)}
+
+ {/each}
+{/snippet}
+
+{#snippet corner()}
+ { byTime = !byTime; }}>
+ {byTime ? 'Time' : 'Distance'}
+
+{/snippet}
+
+{#snippet header()}
+
+ {#each present as key (key)}
+ on[key] = !on[key]}>{series[key].label}
+ {/each}
+
+{/snippet}
+
+{#if large}
+ {@const key = large}
+ largeOf(key, stretch)} unit={series[key].unit} missing={series[key].limit} grades={key === 'elevation'}
+ part={part && [axis.xs[part[0]], axis.xs[part[1]]]} {start} onClose={() => large = null} />
+{/if}
+
+= 0 ? 'pointer' : undefined}>
+
+ { over = x === null ? null : { x, row }; onpoint(x === null ? null : shares[sampleAt(xs, x)]); }}
+ onpart={next => onpart(next && partOf(next))} />
+
+
+
+
diff --git a/builder/web/src/components/route/RouteMap.svelte b/builder/web/src/components/route/RouteMap.svelte
new file mode 100644
index 0000000000..29c3ab5ef5
--- /dev/null
+++ b/builder/web/src/components/route/RouteMap.svelte
@@ -0,0 +1,219 @@
+
+
+ { if (!(event.target as Element).closest('.route-pin')) opened = undefined; }} />
+
+
+
+ {#each shownPins as pin (pin.index)}
+
+ opened = pin.index} onfocus={() => opened = pin.index} onblur={() => opened = undefined}
+ onkeydown={event => { if (event.key === 'Escape') opened = undefined; }}>
+ {#if pin.number}{pin.number}{:else} {/if}
+
+ {#if opened === pin.index}{pinName(pin)} {/if}
+
+ {/each}
+
+
+
+
diff --git a/builder/web/src/components/route/Rows.svelte b/builder/web/src/components/route/Rows.svelte
new file mode 100644
index 0000000000..e521a227d9
--- /dev/null
+++ b/builder/web/src/components/route/Rows.svelte
@@ -0,0 +1,535 @@
+
+
+
+
+ {
+ if (open !== undefined && !(event.target as Element).closest('.pin')) open = undefined;
+ if (openPlace && !(event.target as Element).closest('.place')) openPlace = undefined;
+}} />
+
+{#snippet about(point: RoutePoint)}
+ {@const found = point.placeId ? details[point.placeId] : undefined}
+ {@const own = point as Partial}
+ {@const website = websiteLink(found?.website ?? own.website)}
+ {@const phone = found?.phone ?? own.phone}
+ {@const hours = found?.opening_hours ?? own.openingHours}
+
+
{point.label}
+ {#if point.placeKind}
{kindLabel(point.placeKind)} {/if}
+ {#if point.note}
{point.note}
{/if}
+ {#if hours}
{/if}
+ {#if website || phone}
+
+ {#if website}Website {/if}
+ {#each phoneNumbers(phone) as number (number)}
+ {@const link = phoneLink(number)}
+ {#if link}{number} {:else}{number} {/if}
+ {/each}
+
+ {/if}
+
+{/snippet}
+
+{#snippet waypoints()}
+
+ {#each shownPins as pin, i (i)}
+ {#if pin.number}
+
+
+ { if (event.pointerType === 'mouse') show(event.currentTarget, pin.number); }}
+ onpointerleave={event => { if (event.pointerType === 'mouse' && !event.currentTarget.contains(document.activeElement)) open = undefined; }}
+ onfocusout={event => { if (!event.currentTarget.contains(event.relatedTarget as Node | null)) open = undefined; }}
+ onkeydown={event => { if (event.key === 'Escape') { event.currentTarget.querySelector('button')!.focus(); open = undefined; } }}>
+ show(event.currentTarget.parentElement!, pin.number)}>{pin.number}
+ {#if open === pin.number && pin.point}{@render about(pin.point)}{/if}
+
+ {:else}
+
+ {@const gap = shownPins.map(other => other.number ? (x(pin.share) - x(other.share)) * width : Infinity).find(px => Math.abs(px) < NIGHT_PX)}
+ .97 ? 'translate(-100%, -50%)' : x(pin.share) < .03 ? 'translate(0, -50%)' : undefined}>
+ {/if}
+ {/each}
+{/snippet}
+
+{#snippet elevation()}
+
+{/snippet}
+
+{#snippet surface()}
+
+ {#each runs as run, i (i)} {/each}
+
+
+ {#each surfaces as surface (surface)} {surface} {/each}
+
+{/snippet}
+
+{#snippet placeRow()}
+
+ {#if category && tooLong}
+
{days.length > 1 && day === 'all' ? 'Choose one day to see places' : 'Too long to show places'}
+ {:else if places.failed}
+
Places are unavailable.
+ {:else if places.found && !groups.length}
+
None within {formatDistance(PLACE_M)}
+ {:else if category}
+ {#each groups as group, i (i)}
+
width - 40 ? 'translate(-100%, -50%)' : undefined}>
+ place.label).join(', ')} aria-expanded={openPlace?.group === i}
+ onclick={event => { show(event.currentTarget.parentElement!, undefined); openPlace = openPlace?.group === i ? undefined : { group: i }; }}>
+
+ {#if group.places.length > 1}{group.places.length} {/if}
+
+ {#if openPlace?.group === i}
+ {#if chosenPlace}
+ {@render about(chosenPlace)}
+ {:else}
+
+ {#each group.places.slice(0, LIST_NAMES) as place, j (j)}
+
openPlace = { group: i, place: j }}>{place.label} {kmOf(place)}
+ {/each}
+ {#if group.places.length > LIST_NAMES}
and {group.places.length - LIST_NAMES} more
{/if}
+
+ {/if}
+ {/if}
+
+ {/each}
+ {/if}
+
+{/snippet}
+
+{#snippet pointer()}{chip}{/snippet}
+
+{#snippet header()}
+ {#if days.length > 1}
+ { day = value; onpart(null); }}
+ options={[{ value: 'all', label: days.length === 2 ? 'Both days' : 'All days' }, ...days.map(item => ({ value: String(item.number), label: `Day ${item.number}` }))]} />
+ {/if}
+ ({ label: placeCategories[id].label, checked: category === id, run: () => { category = id; openPlace = undefined; } })),
+ ...category ? [{ label: 'Hide places', rule: true, run: () => { category = ''; openPlace = undefined; } }] : [],
+ ]} />
+{/snippet}
+
+
+
+ onpart(next && [shown.from + next[0] * span, shown.from + next[1] * span])}
+ rows={[
+ { label: 'Waypoints', draw: waypoints, height: 24 },
+ { label: 'Elevation', draw: elevation, height: elevationHeight },
+ ...runs.length ? [{ label: 'Surface', draw: surface }] : [],
+ ...category ? [{ label: placeCategories[category].label, draw: placeRow, height: 28 }] : [],
+ ]} />
+
+
+
+
diff --git a/builder/web/src/components/route/ZoneTimes.svelte b/builder/web/src/components/route/ZoneTimes.svelte
new file mode 100644
index 0000000000..0980d0cd70
--- /dev/null
+++ b/builder/web/src/components/route/ZoneTimes.svelte
@@ -0,0 +1,91 @@
+
+
+{#if !channel.zones}
+ Set your {missing} in Settings to see zones.
+{:else if list}
+
+ {#each [...zones].reverse() as zone (zone.name)}
+ {zone.name} {time(zone.seconds)}
+ {/each}
+
+{:else}
+ zone.text).join(', ')}>
+ {#each zones as zone (zone.name)} {/each}
+
+{/if}
+
+
diff --git a/builder/web/src/components/route/download.ts b/builder/web/src/components/route/download.ts
new file mode 100644
index 0000000000..b0991d545a
--- /dev/null
+++ b/builder/web/src/components/route/download.ts
@@ -0,0 +1,9 @@
+/** Saves a file that the page made, named after a route or a ride. */
+export function download(content: BlobPart, type: string, name: string, extension: string): void {
+ const url = URL.createObjectURL(new Blob([content], { type }));
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = `${name.replace(/[^\p{L}\p{N} _-]/gu, '').slice(0, 80) || 'route'}.${extension}`;
+ link.click();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+}
diff --git a/builder/web/src/components/route/ticks.test.ts b/builder/web/src/components/route/ticks.test.ts
new file mode 100644
index 0000000000..cd2547b767
--- /dev/null
+++ b/builder/web/src/components/route/ticks.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from 'vitest';
+import { distanceTicks } from './ticks';
+
+describe('the ticks of a stretch of a line', () => {
+ it('are at round distances from the start of the line, not of the stretch', () => {
+ const ticks = distanceTicks(14_400, 21_300, 730);
+ expect(ticks.map(tick => tick.label)).toEqual(['km 15', 'km 16', 'km 17', 'km 18', 'km 19', 'km 20', 'km 21']);
+ expect(ticks[0].at).toBeCloseTo(600 / 6900);
+ });
+
+ it('have steps under one kilometre for a short stretch only when the ticks are fine', () => {
+ expect(distanceTicks(16_500, 17_900, 730, true).map(tick => tick.label)).toEqual(['km 16.6', 'km 16.8', 'km 17.0', 'km 17.2', 'km 17.4', 'km 17.6', 'km 17.8']);
+ expect(distanceTicks(16_500, 17_900, 730).map(tick => tick.label)).toEqual(['km 17']);
+ });
+});
diff --git a/builder/web/src/components/route/ticks.ts b/builder/web/src/components/route/ticks.ts
new file mode 100644
index 0000000000..0af3c9c75d
--- /dev/null
+++ b/builder/web/src/components/route/ticks.ts
@@ -0,0 +1,36 @@
+/** The ticks under the rows of a detail page: round distances in the unit of the rider, and the ticks that fit. */
+import { distanceIn } from '../../lib/settings/format';
+import { settings } from '../../lib/settings/settings.svelte';
+
+export interface Tick { at: number; label: string }
+
+/** A tick label is about TICK_CHAR_PX wide for each character, and keeps TICK_GAP_PX from the next one. */
+const TICK_CHAR_PX = 7, TICK_GAP_PX = 12;
+
+/** Ticks at round distances from `fromM` to `toM` along a line, about one for each 80 px of `width`. With `fine`, a
+ * short stretch has steps under one unit, as a view into a line needs them. */
+export function distanceTicks(fromM: number, toM: number, width: number, fine = false): Tick[] {
+ const first = distanceIn(fromM), length = distanceIn(toM - fromM);
+ const step = [...fine ? [.1, .2, .5] : [], 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000].find(size => length / size <= Math.max(1, width / 80)) ?? 2000;
+ const ticks = [];
+ // The count of steps is whole, so a step under one unit adds no rounding error.
+ for (let k = Math.ceil(first / step - 1e-9); k * step < first + length; k++) {
+ ticks.push({ at: (k * step - first) / length, label: `${settings.units} ${step < 1 ? (k * step).toFixed(1) : k * step}` });
+ }
+ return ticks;
+}
+
+/** The ticks of `wanted` that fit on `width` pixels, the first ones first: a tick that would touch a kept one is left
+ * out. A label sits as `Lanes` places it: shifted left by its share of the axis. */
+export function fitTicks(wanted: Tick[], width: number): Tick[] {
+ const extent = ({ at, label }: Tick) => {
+ const size = label.length * TICK_CHAR_PX;
+ return [at * width - at * size, at * width + (1 - at) * size];
+ };
+ const kept: Tick[] = [];
+ for (const tick of wanted) {
+ const [left, right] = extent(tick);
+ if (kept.every(other => { const [a, b] = extent(other); return right + TICK_GAP_PX <= a || left >= b + TICK_GAP_PX; })) kept.push(tick);
+ }
+ return kept;
+}
diff --git a/builder/web/src/components/route/towns.ts b/builder/web/src/components/route/towns.ts
new file mode 100644
index 0000000000..c1ec6ee320
--- /dev/null
+++ b/builder/web/src/components/route/towns.ts
@@ -0,0 +1,21 @@
+/** The town at the top of a climb, for the name "To ". */
+import type { Coordinate } from '../../lib/planner/geo';
+import { townName } from '../../lib/planner/point-names';
+
+/** At most SEARCHES place searches run at a time: each search has a time limit. */
+const SEARCHES = 3;
+const towns = new Map>(), waiting: (() => void)[] = [];
+let searching = 0;
+
+/** One place search for each top while the app lives. A search that finds no town, or fails, is not kept. */
+export function townOf(top: Coordinate): Promise {
+ const key = top.join();
+ if (!towns.has(key)) towns.set(key, new Promise(resolve => {
+ const search = () => {
+ searching++;
+ void townName(top).then(name => { if (name === null) towns.delete(key); resolve(name); }).finally(() => { searching--; waiting.shift()?.(); });
+ };
+ if (searching < SEARCHES) search(); else waiting.push(search);
+ }));
+ return towns.get(key)!;
+}
diff --git a/builder/web/src/lib/assemble/bridge.ts b/builder/web/src/lib/assemble/bridge.ts
index a7e18eb945..1c803ccd5b 100644
--- a/builder/web/src/lib/assemble/bridge.ts
+++ b/builder/web/src/lib/assemble/bridge.ts
@@ -36,10 +36,13 @@ export class AssembleError extends Error {
}
/**
- * Which stage of the assembly is running. Mirrors `Phase::as_str` in
+ * The stages of the assembly, in the order they run. Mirrors `Phase::as_str` in
* `builder/wasm/src/driver.rs`. `nav`, `write` and `verify` are the long phases.
*/
-export type AssemblePhase = "open" | "poi" | "nav" | "plan" | "write" | "verify" | "done";
+export const ASSEMBLE_PHASES = ["open", "poi", "nav", "plan", "write", "verify", "done"] as const;
+
+/** Which stage of the assembly is running. */
+export type AssemblePhase = (typeof ASSEMBLE_PHASES)[number];
/**
* Progress sink. `fraction` is overall completion (0..1), not progress within `phase`. Return
diff --git a/builder/web/src/lib/catalog/articles.test.ts b/builder/web/src/lib/catalog/articles.test.ts
index c49e26823e..0c28b98021 100644
--- a/builder/web/src/lib/catalog/articles.test.ts
+++ b/builder/web/src/lib/catalog/articles.test.ts
@@ -24,7 +24,7 @@ async function digest(body: string) {
function selection(catalog = exampleCatalog) {
const indices = fixtureIndices(catalog, { network: [{ id, bytes: 19 }] });
const box = cellSquare(parseCellId(id));
- const resolution = resolveSelection({ parts: [{ kind: "box", id: "pick", name: "Pick", box }], corridorRadiusM: 0 },
+ const resolution = resolveSelection({ parts: [{ kind: "box", id: "pick", name: "Pick", box }] },
{ catalog, indices, regionCells: new Map() });
return { resolution, indices };
}
diff --git a/builder/web/src/lib/catalog/client.test.ts b/builder/web/src/lib/catalog/client.test.ts
index a93b4218c7..ac94e209cf 100644
--- a/builder/web/src/lib/catalog/client.test.ts
+++ b/builder/web/src/lib/catalog/client.test.ts
@@ -62,9 +62,9 @@ describe("CatalogClient.load", () => {
});
it("refuses a relative URL rather than guessing a base", async () => {
- // Resolving one is a host's job: the web host has a `document.baseURI`,
- // the desktop host does not, and a client that guessed would resolve a
- // CDN path against a Tauri asset scheme.
+ // Resolving one is a host's job: the web host resolves it against its
+ // `document.baseURI`, and a client that guessed could resolve a CDN path
+ // against the wrong base.
await expect(CatalogClient.load("./data/catalog.json", { fetchImpl: serving({}).impl })).rejects.toThrow(
CatalogFormatError,
);
diff --git a/builder/web/src/lib/catalog/client.ts b/builder/web/src/lib/catalog/client.ts
index a020c40e49..4d7646ad81 100644
--- a/builder/web/src/lib/catalog/client.ts
+++ b/builder/web/src/lib/catalog/client.ts
@@ -86,8 +86,8 @@ export class CatalogClient {
* Fetch and parse the root.
*
* `url` must be absolute: resolving a relative one is a host's job — the web host
- * has a `document.baseURI`, the desktop host does not — and a client that guessed
- * would resolve a CDN path against a Tauri asset scheme.
+ * resolves it against its `document.baseURI` — and a client that guessed could
+ * resolve a CDN path against the wrong base.
*
* The root is fetched on trust, since there is no document above it to pin it,
* which is why it is short-cached and everything else is content-addressed.
diff --git a/builder/web/src/lib/catalog/corridor.test.ts b/builder/web/src/lib/catalog/corridor.test.ts
deleted file mode 100644
index 96c8afffb9..0000000000
--- a/builder/web/src/lib/catalog/corridor.test.ts
+++ /dev/null
@@ -1,363 +0,0 @@
-// Corridor buffering: the cells within R of a route.
-//
-// The interesting assertions here are the *boundary* ones — a cell just inside
-// the radius and the same cell just outside it — because that is where an error
-// in the metre-per-microdegree conversion or in the segment-to-rectangle
-// distance would show, and nowhere else. A factor-of-1e6 slip does not make the
-// result subtly wrong; it makes it select the world or nothing.
-
-import { describe, expect, it } from "vitest";
-import { corridorCells, M_PER_DEG, type LatLon } from "./corridor";
-import {
- cellsIntersecting,
- cellSize,
- cellSquare,
- formatCellId,
- GridError,
- parseCellId,
- type CellId,
-} from "../core/grid";
-
-const CELL = parseCellId("18/1204/1052");
-const SQUARE = cellSquare(CELL);
-const CENTRE: LatLon = {
- lat: (SQUARE.minLat + SQUARE.maxLat) / 2,
- lon: (SQUARE.minLon + SQUARE.maxLon) / 2,
-};
-
-/** µdeg of longitude that span `metres` at the cell's centre latitude. */
-function lonUdegFor(metres: number): number {
- const perUdeg = (M_PER_DEG / 1e6) * Math.cos((CENTRE.lat / 1e6) * (Math.PI / 180));
- return Math.round(metres / perUdeg);
-}
-
-/** µdeg of latitude that span `metres` — no cosine, by definition. */
-function latUdegFor(metres: number): number {
- return Math.round(metres / (M_PER_DEG / 1e6));
-}
-
-/** The radius at which `cell` first comes into a one-point route's corridor,
- * bisected to a metre. */
-function radiusAdmitting(point: LatLon, id: string): number {
- const hits = (r: number) => corridorCells(18, [point], r).some((c) => formatCellId(c) === id);
- let lo = 0;
- let hi = 20_000;
- for (let k = 0; k < 40; k++) {
- const mid = (lo + hi) / 2;
- if (hits(mid)) hi = mid;
- else lo = mid;
- }
- return hi;
-}
-
-describe("corridorCells", () => {
- it("selects the cells a zero-width route crosses, and only those", () => {
- // A line inside one cell: a corridor of no width is still a corridor.
- const route = [
- { lat: CENTRE.lat, lon: SQUARE.minLon + 1000 },
- { lat: CENTRE.lat, lon: SQUARE.maxLon - 1000 },
- ];
- expect(corridorCells(18, route, 0).map(formatCellId)).toEqual(["18/1204/1052"]);
- });
-
- it("reaches the neighbour once the radius does", () => {
- const route = [{ lat: CENTRE.lat, lon: SQUARE.maxLon - lonUdegFor(1000) }];
- expect(corridorCells(18, route, 500).map(formatCellId)).toEqual(["18/1204/1052"]);
- expect(corridorCells(18, route, 1500).map(formatCellId)).toEqual([
- "18/1204/1052",
- "18/1204/1053",
- ]);
- });
-
- it("puts the radius where it says it does, to within a percent", () => {
- // A point 5 km west of the cell's west edge, at the cell's own latitude.
- // Bisect for the radius at which the cell first comes in: the projection
- // is the same equirectangular one the module documents, so this pins the
- // constant and the unit handling rather than re-deriving geodesy.
- const point = { lat: CENTRE.lat, lon: SQUARE.minLon - lonUdegFor(5000) };
- expect(corridorCells(18, [point], 4000).map(formatCellId)).not.toContain("18/1204/1052");
- expect(corridorCells(18, [point], 6000).map(formatCellId)).toContain("18/1204/1052");
- const admitted = radiusAdmitting(point, "18/1204/1052");
- expect(admitted).toBeGreaterThan(4950);
- expect(admitted).toBeLessThan(5050);
- });
-
- it("puts the same radius due south, which is where the latitude scale shows", () => {
- // The mirror of the test above, and not redundant with it: the due-west
- // probe multiplies the latitude scale by cos(φ) and divides by it again
- // when the test converts back, so a wrong `sy` — 3× wrong, even —
- // survives it untouched. Due south, `sy` is the only number in the
- // arithmetic. 5 km of latitude is 5 km at every latitude, by definition.
- const point = { lat: SQUARE.minLat - latUdegFor(5000), lon: CENTRE.lon };
- const admitted = radiusAdmitting(point, "18/1204/1052");
- expect(admitted).toBeGreaterThan(4950);
- expect(admitted).toBeLessThan(5050);
- // …and the two agree with each other, which is the statement that a
- // scale error in either axis breaks.
- const west = radiusAdmitting({ lat: CENTRE.lat, lon: SQUARE.minLon - lonUdegFor(5000) }, "18/1204/1052");
- expect(Math.abs(admitted - west)).toBeLessThan(50);
- });
-
- it("buffers a single point into a disc", () => {
- const point = [{ lat: SQUARE.minLat + 500, lon: SQUARE.minLon + 500 }];
- // Small radius: the cell it sits in. Large: the three neighbours across
- // the corner too, since the point is 500 µdeg (~50 m) from both edges.
- expect(corridorCells(18, point, 10).map(formatCellId)).toEqual(["18/1204/1052"]);
- expect(corridorCells(18, point, 2000).map(formatCellId)).toEqual([
- "18/1203/1051",
- "18/1203/1052",
- "18/1204/1051",
- "18/1204/1052",
- ]);
- });
-
- it("is generous at the coarse band with no extra rule", () => {
- // The same route, the same radius, one band up: whole covering cells, i.e.
- // context beyond the corridor.
- const route = [
- { lat: CENTRE.lat, lon: SQUARE.minLon + 1000 },
- { lat: CENTRE.lat, lon: SQUARE.maxLon - 1000 },
- ];
- const coarse = corridorCells(20, route, 0);
- expect(coarse).toHaveLength(1);
- const square = cellSquare(coarse[0]);
- expect(square.minLat).toBeLessThanOrEqual(SQUARE.minLat);
- expect(square.maxLat).toBeGreaterThanOrEqual(SQUARE.maxLat);
- });
-
- it("ignores ground the route never approaches", () => {
- const route = [
- { lat: CENTRE.lat, lon: CENTRE.lon },
- { lat: CENTRE.lat + 100, lon: CENTRE.lon + 100 },
- ];
- const ids = corridorCells(18, route, 20_000).map(formatCellId);
- expect(ids).not.toContain("18/1200/1052");
- expect(ids.length).toBeLessThan(10);
- });
-
- it("follows a route across many cells, in (i, j) order", () => {
- // A diagonal over ~1.5 cells in each axis.
- const route: LatLon[] = [];
- for (let k = 0; k <= 20; k++) {
- route.push({
- lat: SQUARE.minLat + (k * (SQUARE.maxLat - SQUARE.minLat) * 3) / 40,
- lon: SQUARE.minLon + (k * (SQUARE.maxLon - SQUARE.minLon) * 3) / 40,
- });
- }
- const ids = corridorCells(18, route, 0).map(formatCellId);
- expect(ids).toEqual([...ids].sort());
- expect(ids).toContain("18/1204/1052");
- expect(ids).toContain("18/1205/1053");
- // A diagonal touches the off-diagonal cells it actually enters and no
- // more: this is a distance test, not a bbox fill.
- expect(ids).not.toContain("18/1206/1052");
- });
-
- it("has nothing to say about an empty route", () => {
- expect(corridorCells(18, [], 5000)).toEqual([]);
- });
-
- it("refuses a route that spans the antimeridian instead of buffering the world", () => {
- // The grid does not wrap, so a route written from one side of the seam to
- // the other is two selections and two maps. Buffering it as one box would
- // quietly select — and price — every cell in between.
- const acrossTheSeam = [
- { lat: 60_000_000, lon: 179_000_000 },
- { lat: 60_000_000, lon: -179_000_000 },
- ];
- expect(() => corridorCells(18, acrossTheSeam, 5000)).toThrow(GridError);
- expect(() => corridorCells(18, acrossTheSeam, 5000)).toThrow(/antimeridian/);
- // A genuinely long route that does not cross it is fine.
- expect(() =>
- corridorCells(20, [
- { lat: 47_000_000, lon: -10_000_000 },
- { lat: 55_000_000, lon: 30_000_000 },
- ], 5000),
- ).not.toThrow();
- });
-
- it("treats a negative radius as zero", () => {
- const route = [
- { lat: CENTRE.lat, lon: SQUARE.minLon + 1000 },
- { lat: CENTRE.lat, lon: SQUARE.maxLon - 1000 },
- ];
- expect(corridorCells(18, route, -1000).map(formatCellId)).toEqual(["18/1204/1052"]);
- });
-});
-
-// --- the prefilter must never decide anything -------------------------------
-//
-// `corridorCells` is two tests in a trench coat: a cheap box prefilter that picks
-// candidates, and the exact segment-to-rectangle distance that decides. The whole design
-// only holds if the first is a superset of the second — a candidate that is never
-// generated is never tested, never selected, and never reported as a hole either. So the
-// prefilter dropping one cell is a silent hole in the corridor.
-
-/** The module's own per-cell acceptance test, spelled out here with no prefilter in
- * front of it: the oracle the real function must agree with. */
-function acceptsCell(cell: CellId, points: readonly LatLon[], radiusM: number): boolean {
- const square = cellSquare(cell);
- const lat0 = (square.minLat + square.maxLat) / 2;
- const lon0 = (square.minLon + square.maxLon) / 2;
- const sx = (M_PER_DEG / 1e6) * Math.max(Math.cos((lat0 / 1e6) * (Math.PI / 180)), Math.cos((85 * Math.PI) / 180));
- const sy = M_PER_DEG / 1e6;
- const r2 = Math.max(radiusM, 0) ** 2;
- const x = (lon: number) => (lon - lon0) * sx;
- const y = (lat: number) => (lat - lat0) * sy;
- const minX = x(square.minLon);
- const maxX = x(square.maxLon);
- const minY = y(square.minLat);
- const maxY = y(square.maxLat);
-
- const dist2 = (ax: number, ay: number, bx: number, by: number): number => {
- const toRect = (px: number, py: number) => {
- const dx = Math.max(minX - px, 0, px - maxX);
- const dy = Math.max(minY - py, 0, py - maxY);
- return dx * dx + dy * dy;
- };
- const toSeg = (px: number, py: number) => {
- const vx = bx - ax;
- const vy = by - ay;
- const len2 = vx * vx + vy * vy;
- const t = len2 > 0 ? Math.min(1, Math.max(0, ((px - ax) * vx + (py - ay) * vy) / len2)) : 0;
- return (px - (ax + t * vx)) ** 2 + (py - (ay + t * vy)) ** 2;
- };
- let best = Math.min(toRect(ax, ay), toRect(bx, by));
- for (const [cx, cy] of [
- [minX, minY],
- [maxX, minY],
- [maxX, maxY],
- [minX, maxY],
- ]) {
- best = Math.min(best, toSeg(cx, cy));
- }
- return best;
- };
-
- const segments: [LatLon, LatLon][] = points.length === 1 ? [[points[0], points[0]]] : [];
- for (let k = 1; k < points.length; k++) segments.push([points[k - 1], points[k]]);
- return segments.some(([a, b]) => dist2(x(a.lon), y(a.lat), x(b.lon), y(b.lat)) <= r2);
-}
-
-/**
- * Brute force: every cell in a deliberately over-wide box, tested exactly.
- *
- * The box is padded by the latitude reach **and by `1/cos(85°)` of it** — the
- * largest longitude reach any latitude can ask for — plus two whole cells, so it
- * cannot itself be the thing that drops a cell.
- */
-function exactCorridorCells(log2: number, points: readonly LatLon[], radiusM: number): string[] {
- const lats = points.map((p) => p.lat);
- const lons = points.map((p) => p.lon);
- const dLat = Math.ceil(Math.max(radiusM, 0) / (M_PER_DEG / 1e6)) + 2 * cellSize(log2);
- const dLon = Math.ceil(dLat / Math.cos((85 * Math.PI) / 180)) + 2 * cellSize(log2);
- return cellsIntersecting(log2, {
- minLat: Math.min(...lats) - dLat,
- minLon: Math.min(...lons) - dLon,
- maxLat: Math.max(...lats) + dLat,
- maxLon: Math.max(...lons) + dLon,
- })
- .filter((c) => acceptsCell(c, points, radiusM))
- .map(formatCellId);
-}
-
-/** mulberry32 — deterministic, so a red run names a vector rather than a mood. */
-function seededRandom(seed: number): () => number {
- let s = seed;
- return () => {
- s = (s + 0x6d2b_79f5) | 0;
- let t = Math.imul(s ^ (s >>> 15), 1 | s);
- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
- return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
- };
-}
-
-describe("the candidate prefilter is never the decision", () => {
- it("keeps a cell whose own latitude reaches further than the route's", () => {
- // The regression vector. The route sits 1 µdeg south of coarse cell
- // 20/0300/0263 and 65 100 µdeg west of it. The cell's centre is half a cell
- // further north, where a degree of longitude is ~1 % shorter — so 65 100 µdeg
- // is inside 5 km measured at the *cell*, and outside 5 km measured at the
- // *route*. Padding the candidate box with the route's latitude drops this
- // cell across a ~48 m window, with nothing anywhere reporting a hole.
- const cell = cellSquare(parseCellId("20/0300/0263"));
- const route = [{ lat: cell.minLat - 1, lon: cell.minLon - 65_100 }];
- expect(acceptsCell(parseCellId("20/0300/0263"), route, 5000)).toBe(true);
- expect(corridorCells(20, route, 5000).map(formatCellId)).toContain("20/0300/0263");
- expect(corridorCells(20, route, 5000).map(formatCellId)).toEqual(
- exactCorridorCells(20, route, 5000),
- );
- });
-
- it("agrees with the brute-force test across the whole window that used to fail", () => {
- const cell = cellSquare(parseCellId("20/0300/0263"));
- for (let delta = 64_000; delta < 66_500; delta += 7) {
- const route = [{ lat: cell.minLat - 1, lon: cell.minLon - delta }];
- expect(corridorCells(20, route, 5000).map(formatCellId)).toEqual(
- exactCorridorCells(20, route, 5000),
- );
- }
- });
-
- it("agrees with the brute-force test on 400 pseudo-random routes", () => {
- // Seeded, so a failure is a vector someone can paste into the test above
- // rather than a story about a flake. Latitudes run from the far south to
- // the high arctic on purpose: the bug this pins is a cos(latitude) one,
- // and it is invisible at the equator.
- const rnd = seededRandom(0x1657_1030);
- const between = (lo: number, hi: number) => Math.round(lo + rnd() * (hi - lo));
-
- for (let n = 0; n < 400; n++) {
- const log2 = rnd() < 0.5 ? 18 : 20;
- const s = cellSize(log2);
- const lat = between(-55_000_000, 78_000_000);
- const lon = between(-170_000_000, 170_000_000);
- const points: LatLon[] = [];
- for (let k = 0, kn = 1 + Math.floor(rnd() * 4); k < kn; k++) {
- points.push({ lat: lat + between(-2 * s, 2 * s), lon: lon + between(-2 * s, 2 * s) });
- }
- const radius = between(0, 20_000);
- expect(
- corridorCells(log2, points, radius).map(formatCellId),
- `log2 ${log2}, radius ${radius} m, route ${JSON.stringify(points)}`,
- ).toEqual(exactCorridorCells(log2, points, radius));
- }
- });
-
- it("agrees at the acceptance boundary itself, on both sides of the equator", () => {
- // Uniformly random routes almost never land in the ~1 % of longitude
- // where the two latitudes disagree, so this probe aims straight at it:
- // a point one µdeg off a cell's *equatorward* edge, at the longitude
- // offset that puts the cell's near corner within a hair of the radius,
- // jittered either side of it. That is the geometry the fringe bug lived
- // in, and it is worth ~600 µdeg of longitude — about 48 m — per cell.
- const rnd = seededRandom(0x0300_0263);
- const mPerUdeg = M_PER_DEG / 1e6;
- for (let n = 0; n < 300; n++) {
- const log2 = rnd() < 0.5 ? 18 : 20;
- const axis = 2 ** 29 / cellSize(log2);
- // Cells covering roughly ±75° of latitude, any longitude.
- const span = Math.floor((75_000_000 / 2 ** 29) * axis);
- const i = Math.floor(axis / 2) + Math.floor((rnd() * 2 - 1) * span);
- const j = Math.floor(rnd() * axis);
- const square = cellSquare({ log2, i, j });
- const centreLat = (square.minLat + square.maxLat) / 2;
- const north = centreLat > 0;
- const radius = 500 + Math.round(rnd() * 19_500);
- // What the cell's own latitude admits, in µdeg of longitude.
- const need = radius / (mPerUdeg * Math.cos((centreLat / 1e6) * (Math.PI / 180)));
- for (const jitter of [-900, -300, 0, 300]) {
- const route = [
- {
- lat: north ? square.minLat - 1 : square.maxLat + 1,
- lon: square.minLon - Math.round(need + jitter),
- },
- ];
- expect(
- corridorCells(log2, route, radius).map(formatCellId),
- `log2 ${log2}, cell ${i}/${j}, radius ${radius} m, jitter ${jitter}`,
- ).toEqual(exactCorridorCells(log2, route, radius));
- }
- }
- });
-});
diff --git a/builder/web/src/lib/catalog/corridor.ts b/builder/web/src/lib/catalog/corridor.ts
deleted file mode 100644
index c6edf040e0..0000000000
--- a/builder/web/src/lib/catalog/corridor.ts
+++ /dev/null
@@ -1,250 +0,0 @@
-// Buffering a route into cells: which cells of a band lie within `radius` of a
-// polyline, at one global corridor width for every route in the map.
-//
-// It is a distance-from-polyline test evaluated against whole cell squares, not a
-// polygon buffer: nothing here builds an offset ring, so there is no geometry
-// library, no dependency and no arc-tolerance parameter to get wrong. The question
-// a cell asks is binary — is any part of my square within R of the route? — and the
-// answer is a segment-to-rectangle distance, elementary and exact in its plane.
-//
-// The distance is computed in a local equirectangular plane per cell, with 111 320
-// the metres-per-degree the packer and the firmware already use. Over the ~30 km a
-// cell spans that is accurate to well under a percent. What the error buys or costs
-// is one *whole cell*, and the coverage outline the user sees before downloading is
-// drawn from the same cell set this returns, so there is no silent failure mode.
-//
-// Latitude is *not* corrected per point of the polyline, only per cell: a route
-// point that matters to a cell's answer is by definition within the corridor width
-// of it, so it shares the cell's latitude to within a fraction of a degree.
-
-import { cellsIntersecting, cellSize, cellSquare, GridError, type CellId, type UBox } from "../core/grid";
-
-/** A coordinate in integer microdegrees, `lat, lon` — the catalog's order. */
-export interface LatLon {
- lat: number;
- lon: number;
-}
-
-/** Metres per degree of latitude. The same value `host/obc-pack/src/geom.rs` and
- * `obc-map-scene` use, so a metre means one thing across the project. */
-export const M_PER_DEG = 111_320;
-
-/** Metres per µdeg of latitude. */
-const M_PER_UDEG = M_PER_DEG / 1e6;
-
-/** cos(latitude) never divides by less than this. At ±85° the grid's cells are
- * narrower than a corridor is wide; the clamp keeps the *candidate* box generous
- * rather than infinite, and the exact test below still decides. */
-const MIN_COS = Math.cos((85 * Math.PI) / 180);
-
-/**
- * The east–west scale factor at a latitude, and — the load-bearing part — a
- * function that is **non-increasing in `|lat|` everywhere**.
- *
- * The latitude is clamped to ±90° before the cosine, so a coordinate outside the
- * geographic domain cannot make the cosine climb back towards 1 and hand out a
- * *smaller* padding than a cell nearer the equator got. The prefilter below is only
- * provably generous because this function never goes back up.
- */
-function cosLat(latUdeg: number): number {
- const clamped = Math.min(Math.max(latUdeg, -90_000_000), 90_000_000);
- return Math.max(Math.cos((clamped / 1e6) * (Math.PI / 180)), MIN_COS);
-}
-
-/** Squared distance from a point to an axis-aligned rectangle; zero inside. */
-function pointRectDist2(px: number, py: number, r: PlaneRect): number {
- const dx = Math.max(r.minX - px, 0, px - r.maxX);
- const dy = Math.max(r.minY - py, 0, py - r.maxY);
- return dx * dx + dy * dy;
-}
-
-/** Squared distance from a point to a segment. */
-function pointSegDist2(px: number, py: number, ax: number, ay: number, bx: number, by: number): number {
- const vx = bx - ax;
- const vy = by - ay;
- const len2 = vx * vx + vy * vy;
- let t = 0;
- if (len2 > 0) t = Math.min(1, Math.max(0, ((px - ax) * vx + (py - ay) * vy) / len2));
- const dx = px - (ax + t * vx);
- const dy = py - (ay + t * vy);
- return dx * dx + dy * dy;
-}
-
-interface PlaneRect {
- minX: number;
- minY: number;
- maxX: number;
- maxY: number;
-}
-
-/**
- * Smallest distance between a segment and an axis-aligned rectangle.
- *
- * Zero when they touch; otherwise the closest approach is realised either at a
- * segment endpoint or at a rectangle corner — there is no third case for convex
- * shapes, which is why this needs no iteration.
- */
-function segRectDist2(ax: number, ay: number, bx: number, by: number, r: PlaneRect): number {
- let best = Math.min(pointRectDist2(ax, ay, r), pointRectDist2(bx, by, r));
- if (best === 0) return 0;
- const corners: [number, number][] = [
- [r.minX, r.minY],
- [r.maxX, r.minY],
- [r.maxX, r.maxY],
- [r.minX, r.maxY],
- ];
- for (const [cx, cy] of corners) {
- best = Math.min(best, pointSegDist2(cx, cy, ax, ay, bx, by));
- if (best === 0) return 0;
- }
- return best;
-}
-
-/** The µdeg box a polyline's points span. */
-function polylineBox(points: readonly LatLon[]): UBox {
- let minLat = Infinity;
- let minLon = Infinity;
- let maxLat = -Infinity;
- let maxLon = -Infinity;
- for (const p of points) {
- minLat = Math.min(minLat, p.lat);
- minLon = Math.min(minLon, p.lon);
- maxLat = Math.max(maxLat, p.lat);
- maxLon = Math.max(maxLon, p.lon);
- }
- return { minLat, minLon, maxLat, maxLon };
-}
-
-/** How far, in µdeg, a cell can sit from the route and still be accepted. */
-interface Padding {
- dLat: number;
- dLon: number;
-}
-
-/**
- * The padding the prefilter must use to be **provably at least** the exact test's
- * acceptance region.
- *
- * The exact test measures a cell's distance in a plane scaled at *that cell's
- * centre* latitude, so a cell accepts a route point up to
- * `R / (M_PER_UDEG · cosLat(φ_cell))` µdeg away in longitude. Padding by the
- * *route's* latitude is smaller than that whenever the cell sits poleward of the
- * route, and a candidate the prefilter drops is never tested, never selected and
- * never reported as missing: a silent hole in the corridor.
- *
- * So the padding is computed at the worst latitude any *candidate cell centre* can
- * have: the route's own extent, grown by the exact latitude padding, then by a whole
- * cell. Because {@link cosLat} never increases with `|lat|`, the cosine there is
- * ≤ the cosine at every candidate's centre, so `dLon` is ≥ every candidate's own
- * requirement.
- */
-function paddingFor(box: UBox, radiusM: number, log2: number): Padding {
- const dLat = Math.ceil(radiusM / M_PER_UDEG);
- const worstLat =
- Math.max(Math.abs(box.minLat - dLat), Math.abs(box.maxLat + dLat)) + cellSize(log2);
- return { dLat, dLon: Math.ceil(dLat / cosLat(worstLat)) };
-}
-
-/** A box grown by a padding, in µdeg. Only ever selects candidates for the
- * exact test. */
-function grow(box: UBox, pad: Padding): UBox {
- return {
- minLat: box.minLat - pad.dLat,
- minLon: box.minLon - pad.dLon,
- maxLat: box.maxLat + pad.dLat,
- maxLon: box.maxLon + pad.dLon,
- };
-}
-
-function boxesIntersect(a: UBox, b: UBox): boolean {
- return a.minLat <= b.maxLat && b.minLat <= a.maxLat && a.minLon <= b.maxLon && b.minLon <= a.maxLon;
-}
-
-/**
- * The widest a route may reach in longitude, µdeg: half the world.
- *
- * Past this a polyline is a route written across the antimeridian — the seam the
- * grid deliberately does not wrap over. Buffering it as one box would silently
- * select every cell from one side of the world to the other and price them. Two
- * sides of the seam are two selections, so this refuses rather than guessing.
- */
-export const MAX_CORRIDOR_LON_SPAN = 180_000_000;
-
-/**
- * Every cell of size `2^log2` within `radiusM` of the polyline, in ascending
- * `(i, j)` order.
- *
- * A single-point "polyline" buffers to a disc, which is what a one-point GPX
- * track means. A zero or negative radius still selects the cells the line
- * crosses — a corridor of no width is still a corridor.
- *
- * Throws a {@link GridError} for a route spanning more than half the world in
- * longitude ({@link MAX_CORRIDOR_LON_SPAN}), and for a corridor whose candidate
- * box exceeds what `cellsIntersecting` will enumerate.
- */
-export function corridorCells(log2: number, points: readonly LatLon[], radiusM: number): CellId[] {
- if (points.length === 0) return [];
- const radius = Math.max(radiusM, 0);
- const box = polylineBox(points);
- if (box.maxLon - box.minLon > MAX_CORRIDOR_LON_SPAN) {
- throw new GridError(
- `this route spans ${((box.maxLon - box.minLon) / 1e6).toFixed(1)}° of longitude — the cell grid does ` +
- "not wrap at the antimeridian, so a route crossing it is two selections and two maps",
- );
- }
- // One padding for the whole run, computed at the worst latitude any candidate
- // can reach — see `paddingFor`. A per-segment latitude here would reintroduce
- // exactly the under-selection it exists to prevent.
- const pad = paddingFor(box, radius, log2);
- const candidates = cellsIntersecting(log2, grow(box, pad));
- if (candidates.length === 0) return [];
-
- // One padded box per segment, in µdeg, so a cell nowhere near a segment costs
- // four comparisons instead of a projection. A long route over a wide selection
- // is otherwise O(cells × points) of pointless arithmetic.
- const segments: { a: LatLon; b: LatLon }[] =
- points.length === 1 ? [{ a: points[0], b: points[0] }] : [];
- for (let k = 1; k < points.length; k++) segments.push({ a: points[k - 1], b: points[k] });
- const padded = segments.map((s) =>
- grow(
- {
- minLat: Math.min(s.a.lat, s.b.lat),
- minLon: Math.min(s.a.lon, s.b.lon),
- maxLat: Math.max(s.a.lat, s.b.lat),
- maxLon: Math.max(s.a.lon, s.b.lon),
- },
- pad,
- ),
- );
-
- const r2 = radius * radius;
- return candidates.filter((cell) => {
- const square = cellSquare(cell);
- // Half-open squares meet the closed boxes above at their shared edge; the one
- // µdeg of slack is far below the metre this is accurate to, and it errs toward
- // including a cell.
- const lat0 = (square.minLat + square.maxLat) / 2;
- const lon0 = (square.minLon + square.maxLon) / 2;
- const sx = M_PER_UDEG * cosLat(lat0);
- const sy = M_PER_UDEG;
- const rect: PlaneRect = {
- minX: (square.minLon - lon0) * sx,
- minY: (square.minLat - lat0) * sy,
- maxX: (square.maxLon - lon0) * sx,
- maxY: (square.maxLat - lat0) * sy,
- };
- for (let k = 0; k < segments.length; k++) {
- if (!boxesIntersect(square, padded[k])) continue;
- const { a, b } = segments[k];
- const d2 = segRectDist2(
- (a.lon - lon0) * sx,
- (a.lat - lat0) * sy,
- (b.lon - lon0) * sx,
- (b.lat - lat0) * sy,
- rect,
- );
- if (d2 <= r2) return true;
- }
- return false;
- });
-}
diff --git a/builder/web/src/lib/catalog/download.test.ts b/builder/web/src/lib/catalog/download.test.ts
index 202889cbb0..70db8b72db 100644
--- a/builder/web/src/lib/catalog/download.test.ts
+++ b/builder/web/src/lib/catalog/download.test.ts
@@ -49,7 +49,7 @@ async function fixtures() {
box: { minLat: A.minLat + 1, minLon: A.minLon + 1, maxLat: A.maxLat - 1, maxLon: B.maxLon - 1 },
};
const ctx: SelectionContext = { catalog: exampleCatalog, indices, regionCells: new Map() };
- const resolution = resolveSelection({ parts: [part], corridorRadiusM: 0 }, ctx);
+ const resolution = resolveSelection({ parts: [part] }, ctx);
return { indices, plan: planCells(resolution, exampleCatalog, indices) };
}
@@ -111,7 +111,7 @@ describe("planCells", () => {
box: { minLat: A.minLat + 1, minLon: A.minLon - 1, maxLat: A.maxLat - 1, maxLon: A.minLon + 1 },
};
const resolution = resolveSelection(
- { parts: [westOfA], corridorRadiusM: 0 },
+ { parts: [westOfA] },
{ catalog: exampleCatalog, indices, regionCells: new Map() },
);
const plan = planCells(resolution, exampleCatalog, indices);
@@ -149,7 +149,7 @@ describe("planCells", () => {
},
};
const resolution = resolveSelection(
- { parts: [part], corridorRadiusM: 0 },
+ { parts: [part] },
{ catalog: exampleCatalog, indices, regionCells: new Map() },
);
const plan = planCells(resolution, exampleCatalog, indices);
diff --git a/builder/web/src/lib/catalog/lasso.test.ts b/builder/web/src/lib/catalog/lasso.test.ts
deleted file mode 100644
index 4e38c3d287..0000000000
--- a/builder/web/src/lib/catalog/lasso.test.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-// Lasso cells: the cells a drawn ring overlaps.
-//
-// The assertions worth having are the shape ones — a diagonal ring must select its
-// stair of cells and NOT the bounding box's rectangle, because "better than a box for
-// diagonal shapes" is the whole reason the tool exists — and the containment ones: a
-// cell wholly inside the ring has no edge near it, so it is selected by the even-odd
-// corner test alone, and a ring drawn wholly inside one cell has no boundary crossing
-// either, so it exercises the segment-inside-square half of the overlap test.
-
-import { describe, expect, it } from "vitest";
-import type { LatLon } from "./corridor";
-import { cellSize, cellSquare, formatCellId, GridError, parseCellId } from "../core/grid";
-import { lassoCells, MAX_LASSO_LON_SPAN } from "./lasso";
-
-const CELL = parseCellId("18/1204/1052");
-const SQUARE = cellSquare(CELL);
-const S = cellSize(18);
-const at = (di: number, dj: number): LatLon => ({
- lat: SQUARE.minLat + di * S,
- lon: SQUARE.minLon + dj * S,
-});
-
-describe("lassoCells", () => {
- it("selects nothing for a degenerate ring", () => {
- expect(lassoCells(18, [])).toEqual([]);
- expect(lassoCells(18, [at(0.5, 0.5)])).toEqual([]);
- expect(lassoCells(18, [at(0.5, 0.5), at(0.6, 0.6)])).toEqual([]);
- });
-
- it("selects the one cell a small ring is drawn inside", () => {
- // No ring edge crosses the square's boundary: the edge-in-square half
- // of the overlap test is what admits it.
- const ring = [at(0.3, 0.3), at(0.3, 0.7), at(0.7, 0.7), at(0.7, 0.3)];
- expect(lassoCells(18, ring).map(formatCellId)).toEqual(["18/1204/1052"]);
- });
-
- it("selects a cell wholly inside the ring by containment alone", () => {
- // A 3×3-cell ring: the centre cell touches no edge, so only the
- // even-odd corner test can admit it.
- const ring = [at(-1, -1), at(-1, 2), at(2, 2), at(2, -1)];
- const ids = lassoCells(18, ring).map(formatCellId);
- expect(ids).toContain("18/1204/1052");
- // 3×3 of cells plus the ring's own edges grazing the next row/column
- // at the closed/half-open boundary — the centre and its 8 neighbours
- // are the ones that matter and must all be there.
- for (let di = -1; di <= 1; di++) {
- for (let dj = -1; dj <= 1; dj++) {
- expect(ids).toContain(formatCellId({ log2: 18, i: CELL.i + di, j: CELL.j + dj }));
- }
- }
- });
-
- it("selects a diagonal stair, not the bounding rectangle", () => {
- // A thin diagonal band across 6×6 cells of ground. The bounding box
- // covers 36+ cells; the band itself must come back far smaller, and the
- // far corners must not be in it.
- const ring = [at(0.5, 0.1), at(0.1, 0.5), at(5.5, 5.9), at(5.9, 5.5)];
- const ids = lassoCells(18, ring).map(formatCellId);
- expect(ids).toContain("18/1204/1052");
- expect(ids).toContain(formatCellId({ log2: 18, i: CELL.i + 5, j: CELL.j + 5 }));
- // Off-diagonal corners of the bbox: outside the band.
- expect(ids).not.toContain(formatCellId({ log2: 18, i: CELL.i, j: CELL.j + 5 }));
- expect(ids).not.toContain(formatCellId({ log2: 18, i: CELL.i + 5, j: CELL.j }));
- expect(ids.length).toBeLessThan(30);
- });
-
- it("closes the ring itself — last point back to first", () => {
- // An open L: as a closed ring it is a triangle covering the corner
- // cell diagonal's other side.
- const ring = [at(0.5, 0.5), at(0.5, 3.5), at(3.5, 3.5)];
- const ids = lassoCells(18, ring).map(formatCellId);
- // The closing edge runs (3.5,3.5)→(0.5,0.5): its cells must be there.
- expect(ids).toContain(formatCellId({ log2: 18, i: CELL.i + 2, j: CELL.j + 2 }));
- // …and the corner far from the hypotenuse must not.
- expect(ids).not.toContain(formatCellId({ log2: 18, i: CELL.i + 3, j: CELL.j }));
- });
-
- it("refuses a ring across the antimeridian's half-world span", () => {
- const ring = [
- { lat: SQUARE.minLat, lon: -90_000_100 },
- { lat: SQUARE.minLat, lon: 90_000_100 },
- { lat: SQUARE.maxLat, lon: 90_000_100 },
- ];
- expect(ring[1].lon - ring[0].lon).toBeGreaterThan(MAX_LASSO_LON_SPAN);
- expect(() => lassoCells(18, ring)).toThrow(GridError);
- });
-
- it("agrees with the coarse band without a special case", () => {
- // The same ring at 2^20 selects the covering coarse cells — generous
- // context is a consequence of cell size, exactly as for boxes.
- const ring = [at(0.3, 0.3), at(0.3, 0.7), at(0.7, 0.7), at(0.7, 0.3)];
- const coarse = lassoCells(20, ring);
- expect(coarse.length).toBe(1);
- expect(coarse[0].log2).toBe(20);
- });
-});
diff --git a/builder/web/src/lib/catalog/lasso.ts b/builder/web/src/lib/catalog/lasso.ts
deleted file mode 100644
index f35a01663b..0000000000
--- a/builder/web/src/lib/catalog/lasso.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-// A drawn ring into cells: which cells of a band intersect the closed polygon a lasso
-// gesture traced.
-//
-// It is a polygon-vs-square overlap test evaluated per candidate cell, all in integer
-// microdegrees. It is not a metric buffer and needs no projection: unlike the corridor's
-// distance-in-metres question, "does my square overlap this ring" is an affine question
-// the lat/lon plane answers exactly, so there is no cosine anywhere in this file.
-//
-// The overlap test has exactly two cases, and together they are complete for a simple
-// ring against a convex square:
-//
-// * **An edge of the ring overlaps the square** — decided by Liang–Barsky clipping.
-// This covers every partial overlap, and a ring drawn entirely *inside* one cell.
-// * **The square lies entirely inside the ring** — no edge touches it, so one corner
-// standing in for all four is tested even-odd against the ring.
-//
-// Edges are treated as closed against the half-open cell squares; the µdeg of slack that
-// costs errs toward including a cell.
-
-import { cellsIntersecting, cellSquare, GridError, type CellId, type UBox } from "../core/grid";
-import type { LatLon } from "./corridor";
-
-/** The widest a lasso may reach in longitude, µdeg: half the world — the same
- * antimeridian refusal the corridor makes, because the grid does not wrap and a ring
- * across the seam is two selections. */
-export const MAX_LASSO_LON_SPAN = 180_000_000;
-
-/** The µdeg box a ring's points span. */
-function ringBox(points: readonly LatLon[]): UBox {
- let minLat = Infinity;
- let minLon = Infinity;
- let maxLat = -Infinity;
- let maxLon = -Infinity;
- for (const p of points) {
- minLat = Math.min(minLat, p.lat);
- minLon = Math.min(minLon, p.lon);
- maxLat = Math.max(maxLat, p.lat);
- maxLon = Math.max(maxLon, p.lon);
- }
- return { minLat, minLon, maxLat, maxLon };
-}
-
-/** Even-odd containment of a point in the ring, closed implicitly. The same rule as the
- * map's even-odd fill, so what this selects is what the drawing showed. */
-function pointInRing(lat: number, lon: number, points: readonly LatLon[]): boolean {
- let inside = false;
- for (let k = 0; k < points.length; k++) {
- const a = points[k];
- const b = points[(k + 1) % points.length];
- if (a.lat > lat === b.lat > lat) continue;
- const crossLon = a.lon + ((lat - a.lat) / (b.lat - a.lat)) * (b.lon - a.lon);
- if (lon < crossLon) inside = !inside;
- }
- return inside;
-}
-
-/** Whether the segment `a→b` overlaps the filled box — Liang–Barsky: clip the segment's
- * parameter interval against each slab and see whether anything is left. */
-function segOverlapsBox(a: LatLon, b: LatLon, box: UBox): boolean {
- const dLat = b.lat - a.lat;
- const dLon = b.lon - a.lon;
- let t0 = 0;
- let t1 = 1;
- const clip = (p: number, q: number): boolean => {
- if (p === 0) return q >= 0;
- const r = q / p;
- if (p < 0) {
- if (r > t1) return false;
- if (r > t0) t0 = r;
- } else {
- if (r < t0) return false;
- if (r < t1) t1 = r;
- }
- return true;
- };
- return (
- clip(-dLat, a.lat - box.minLat) &&
- clip(dLat, box.maxLat - a.lat) &&
- clip(-dLon, a.lon - box.minLon) &&
- clip(dLon, box.maxLon - a.lon)
- );
-}
-
-/**
- * Every cell of size `2^log2` whose square intersects the closed ring, in
- * ascending `(i, j)` order.
- *
- * The ring closes itself: the last point connects back to the first, so callers
- * hand over the gesture's points as drawn. Fewer than three points select
- * nothing — a degenerate lasso has no inside, and returning the cells under a
- * stray click would turn a slip into a part.
- *
- * Throws a {@link GridError} for a ring spanning more than half the world in
- * longitude ({@link MAX_LASSO_LON_SPAN}), and for a ring whose candidate box
- * exceeds what `cellsIntersecting` will enumerate.
- */
-export function lassoCells(log2: number, points: readonly LatLon[]): CellId[] {
- if (points.length < 3) return [];
- const box = ringBox(points);
- if (box.maxLon - box.minLon > MAX_LASSO_LON_SPAN) {
- throw new GridError(
- `this lasso spans ${((box.maxLon - box.minLon) / 1e6).toFixed(1)}° of longitude — the cell grid does ` +
- "not wrap at the antimeridian, so a ring crossing it is two selections and two maps",
- );
- }
- const candidates = cellsIntersecting(log2, box);
- return candidates.filter((cell) => {
- const square = cellSquare(cell);
- for (let k = 0; k < points.length; k++) {
- if (segOverlapsBox(points[k], points[(k + 1) % points.length], square)) return true;
- }
- // No edge touches the square, so it is wholly inside or wholly outside
- // the ring — any one corner answers for all four.
- return pointInRing(square.minLat, square.minLon, points);
- });
-}
diff --git a/builder/web/src/lib/catalog/ledger.test.ts b/builder/web/src/lib/catalog/ledger.test.ts
index ab837cace6..45d2ba6976 100644
--- a/builder/web/src/lib/catalog/ledger.test.ts
+++ b/builder/web/src/lib/catalog/ledger.test.ts
@@ -37,7 +37,7 @@ const overA = box("a", { minLat: A.minLat + 1, minLon: A.minLon + 1, maxLat: A.m
const overAB = box("ab", { minLat: A.minLat + 1, minLon: A.minLon + 1, maxLat: A.maxLat - 1, maxLon: B.maxLon - 1 });
function ledgerOf(...parts: BoxPart[]) {
- return ledgerFor(resolveSelection({ parts, corridorRadiusM: 0 }, ctx), exampleCatalog, indices);
+ return ledgerFor(resolveSelection({ parts }, ctx), exampleCatalog, indices);
}
describe("ledgerFor", () => {
@@ -113,7 +113,7 @@ describe("ledgerFor", () => {
{ fine: [{ start: "18/1204/1055", end: "18/1204/1055" }] },
);
const resolution = resolveSelection(
- { parts: [emptyBox], corridorRadiusM: 0 },
+ { parts: [emptyBox] },
{ catalog: exampleCatalog, indices: emptyIndices, regionCells: new Map() },
);
const ledger = ledgerFor(resolution, exampleCatalog, emptyIndices);
@@ -126,7 +126,7 @@ describe("ledgerFor", () => {
it("says nothing is final while a band's index is missing", () => {
const partial = { ...ctx, indices: new Map([["fine", indices.get("fine")!]]) };
const ledger = ledgerFor(
- resolveSelection({ parts: [overA], corridorRadiusM: 0 }, partial),
+ resolveSelection({ parts: [overA] }, partial),
exampleCatalog,
partial.indices,
);
@@ -144,7 +144,7 @@ describe("ledgerFor", () => {
regionId: "europe/switzerland",
};
const ledger = ledgerFor(
- resolveSelection({ parts: [region], corridorRadiusM: 0 }, ctx),
+ resolveSelection({ parts: [region] }, ctx),
exampleCatalog,
indices,
);
diff --git a/builder/web/src/lib/catalog/selection.test.ts b/builder/web/src/lib/catalog/selection.test.ts
index d953ba8934..fbdd5a18bc 100644
--- a/builder/web/src/lib/catalog/selection.test.ts
+++ b/builder/web/src/lib/catalog/selection.test.ts
@@ -14,11 +14,9 @@ import {
emptySelection,
resolveSelection,
SelectionResolver,
- withCorridorRadius,
withoutPart,
withPart,
type BoxPart,
- type CorridorPart,
type RegionPart,
type SelectionContext,
} from "./selection";
@@ -74,7 +72,7 @@ const region: RegionPart = {
describe("selection composition", () => {
it("adds, replaces by id, and removes", () => {
- let selection = emptySelection(5000);
+ let selection = emptySelection();
selection = withPart(selection, insideA);
selection = withPart(selection, region);
expect(selection.parts.map((p) => p.id)).toEqual(["box-1", "region-1"]);
@@ -87,16 +85,11 @@ describe("selection composition", () => {
// Nothing mutates: a stale reference is still the selection it was.
expect(selection.parts).toHaveLength(2);
});
-
- it("keeps one global corridor width, never a negative one", () => {
- expect(withCorridorRadius(emptySelection(0), 2500).corridorRadiusM).toBe(2500);
- expect(withCorridorRadius(emptySelection(0), -10).corridorRadiusM).toBe(0);
- });
});
describe("resolveSelection", () => {
it("resolves a box per band, precisely at fine and generously at coarse", () => {
- const r = resolveSelection({ parts: [insideA], corridorRadiusM: 0 }, ctx);
+ const r = resolveSelection({ parts: [insideA] }, ctx);
expect(r.cellsByBand.get("fine")).toEqual(["18/1204/1052"]);
expect(r.cellsByBand.get("network")).toEqual(["18/1204/1052"]);
expect(r.cellsByBand.get("mid")).toEqual(["19/0602/0526"]);
@@ -106,37 +99,11 @@ describe("resolveSelection", () => {
});
it("reads a region's stored cell list rather than deriving one", () => {
- const r = resolveSelection({ parts: [region], corridorRadiusM: 0 }, ctx);
+ const r = resolveSelection({ parts: [region] }, ctx);
expect(r.cellsByBand.get("fine")).toEqual(["18/1204/1052", "18/1204/1053", "18/1204/1055"]);
expect(r.parts[0].bytes).toBe(2088 + 1064 + 552 + 424 + 296 + 168);
});
- it("resolves a lasso ring per band through the same union", () => {
- // A triangle strictly inside cell A: one fine cell, generous coarse
- // coverage — the same consequence-of-cell-size the box test pins.
- const r = resolveSelection(
- {
- parts: [
- {
- kind: "lasso",
- id: "lasso-1",
- name: "Drawn ring",
- points: [
- { lat: A.minLat + 1000, lon: A.minLon + 1000 },
- { lat: A.minLat + 1000, lon: A.maxLon - 1000 },
- { lat: A.maxLat - 1000, lon: (A.minLon + A.maxLon) / 2 },
- ],
- },
- ],
- corridorRadiusM: 0,
- },
- ctx,
- );
- expect(r.cellsByBand.get("fine")).toEqual(["18/1204/1052"]);
- expect(r.cellsByBand.get("coarse")).toEqual(["20/0301/0263"]);
- expect(r.missingByBand.size).toBe(0);
- });
-
it("treats verified-empty ground as zero-byte coverage rather than a hole", () => {
const emptyBox: BoxPart = {
kind: "box",
@@ -149,14 +116,14 @@ describe("resolveSelection", () => {
maxLon: EMPTY.maxLon - 1,
},
};
- const r = resolveSelection({ parts: [emptyBox], corridorRadiusM: 0 }, ctx);
+ const r = resolveSelection({ parts: [emptyBox] }, ctx);
expect(r.cellsByBand.get("fine")).toEqual(["18/1204/1055"]);
expect(r.missingByBand.get("fine")).toBeUndefined();
expect(r.parts[0].cellsByBand.get("fine")).toEqual(["18/1204/1055"]);
});
it("counts a shared cell once in the union and in both parts' gross bytes", () => {
- const r = resolveSelection({ parts: [insideA, region], corridorRadiusM: 0 }, ctx);
+ const r = resolveSelection({ parts: [insideA, region] }, ctx);
expect(r.cellsByBand.get("fine")).toEqual(["18/1204/1052", "18/1204/1053", "18/1204/1055"]);
const [box, whole] = r.parts;
// Gross: everything the part covers, shared or not — so these overlap.
@@ -182,33 +149,15 @@ describe("resolveSelection", () => {
name: "Over the edge",
box: { minLat: A.minLat + 1000, minLon: A.minLon - 1000, maxLat: A.maxLat - 1000, maxLon: A.minLon + 1000 },
};
- const r = resolveSelection({ parts: [westOfA], corridorRadiusM: 0 }, ctx);
+ const r = resolveSelection({ parts: [westOfA] }, ctx);
expect(r.cellsByBand.get("fine")).toEqual(["18/1204/1052"]);
expect(r.missingByBand.get("fine")).toEqual(["18/1204/1051"]);
expect(r.parts[0].missingCount).toBeGreaterThan(0);
});
- it("buffers a corridor by the selection's global radius", () => {
- const route: CorridorPart = {
- kind: "corridor",
- id: "route-1",
- name: "Day 3 — Basel to Olten",
- points: [
- { lat: (A.minLat + A.maxLat) / 2, lon: A.maxLon - 200 },
- { lat: (A.minLat + A.maxLat) / 2, lon: A.maxLon - 100 },
- ],
- };
- const tight = resolveSelection({ parts: [route], corridorRadiusM: 0 }, ctx);
- expect(tight.cellsByBand.get("fine")).toEqual(["18/1204/1052"]);
- // Widen the one slider and the neighbour joins — with no change to the
- // part itself, which is what "one global width" means.
- const wide = resolveSelection({ parts: [route], corridorRadiusM: 4000 }, ctx);
- expect(wide.cellsByBand.get("fine")).toEqual(["18/1204/1052", "18/1204/1053"]);
- });
-
it("contributes nothing for a region whose cell list has not arrived, and says so", () => {
const pending: SelectionContext = { ...ctx, regionCells: new Map() };
- const r = resolveSelection({ parts: [region], corridorRadiusM: 0 }, pending);
+ const r = resolveSelection({ parts: [region] }, pending);
expect(r.cellsByBand.size).toBe(0);
expect(r.parts[0].cellCount).toBe(0);
// 0 B is a perfectly ordinary number, and a card that prints it without
@@ -218,11 +167,11 @@ describe("resolveSelection", () => {
expect(r.unresolvedParts).toEqual(["region-1"]);
// Once the list is in hand the flag clears, with no other change.
- const arrived = resolveSelection({ parts: [region], corridorRadiusM: 0 }, ctx);
+ const arrived = resolveSelection({ parts: [region] }, ctx);
expect(arrived.parts[0].pending).toBe(false);
expect(arrived.unresolvedParts).toEqual([]);
- // Boxes and corridors are never pending: their answer is arithmetic.
- expect(resolveSelection({ parts: [insideA], corridorRadiusM: 0 }, pending).unresolvedParts).toEqual([]);
+ // Boxes are never pending: their answer is arithmetic.
+ expect(resolveSelection({ parts: [insideA] }, pending).unresolvedParts).toEqual([]);
});
it("names the bands whose index is missing instead of pricing without them", () => {
@@ -230,7 +179,7 @@ describe("resolveSelection", () => {
...ctx,
indices: new Map([["fine", indices.get("fine")!]]),
};
- const r = resolveSelection({ parts: [insideA], corridorRadiusM: 0 }, partial);
+ const r = resolveSelection({ parts: [insideA] }, partial);
expect(r.unresolvedBands).toEqual(["coarse", "mid", "network"]);
expect(r.cellsByBand.get("fine")).toEqual(["18/1204/1052"]);
});
@@ -255,15 +204,15 @@ describe("resolveSelection", () => {
],
}),
};
- expect(() => resolveSelection({ parts: [region], corridorRadiusM: 0 }, broken)).toThrow(
+ expect(() => resolveSelection({ parts: [region] }, broken)).toThrow(
CatalogFormatError,
);
- expect(() => resolveSelection({ parts: [region], corridorRadiusM: 0 }, broken)).toThrow(
+ expect(() => resolveSelection({ parts: [region] }, broken)).toThrow(
/18\/1204\/1053 is not in band "fine"'s index/,
);
// Composed with other parts, and with the region second: still refused,
// rather than quietly counted once as a hole.
- expect(() => resolveSelection({ parts: [insideA, region], corridorRadiusM: 0 }, broken)).toThrow(
+ expect(() => resolveSelection({ parts: [insideA, region] }, broken)).toThrow(
CatalogFormatError,
);
// A band whose index has not loaded is not evidence of anything, so it
@@ -272,27 +221,24 @@ describe("resolveSelection", () => {
...broken,
indices: new Map([["network", broken.indices.get("network")!]]),
};
- expect(() => resolveSelection({ parts: [region], corridorRadiusM: 0 }, stillLoading)).not.toThrow();
+ expect(() => resolveSelection({ parts: [region] }, stillLoading)).not.toThrow();
});
it("has nothing to resolve for an empty selection", () => {
- const r = resolveSelection(emptySelection(5000), ctx);
+ const r = resolveSelection(emptySelection(), ctx);
expect(r.parts).toEqual([]);
expect(r.cellsByBand.size).toBe(0);
});
});
describe("SelectionResolver", () => {
- const route: CorridorPart = {
- kind: "corridor",
- id: "route-1",
- name: "Day 3",
- points: [
- { lat: (A.minLat + A.maxLat) / 2, lon: A.maxLon - 200 },
- { lat: (A.minLat + A.maxLat) / 2, lon: A.maxLon - 100 },
- ],
+ const edge: BoxPart = {
+ kind: "box",
+ id: "box-2",
+ name: "Edge of A",
+ box: { minLat: A.minLat + 1000, minLon: A.maxLon - 200, maxLat: A.maxLat - 1000, maxLon: A.maxLon - 100 },
};
- const selection = { parts: [insideA, region, route], corridorRadiusM: 2000 };
+ const selection = { parts: [insideA, region, edge] };
const bands = exampleCatalog.schema.bands.length;
/** Every list in a resolution, flattened, so two answers can be compared
@@ -322,21 +268,6 @@ describe("SelectionResolver", () => {
expect(resolver.stats.reused).toBe(3 * bands);
});
- it("recomputes only the corridors when the one global width moves", () => {
- // The slider case, and the whole reason this class exists: a map of a
- // region and a box recomputing three parts to answer a question about
- // none of them is tens of milliseconds per frame.
- const resolver = new SelectionResolver();
- resolver.resolve(selection, ctx);
- resolver.stats.computed = 0;
- resolver.stats.reused = 0;
- const wider = withCorridorRadius(selection, 6000);
- const memoised = resolver.resolve(wider, ctx);
- expect(resolver.stats.computed).toBe(bands);
- expect(resolver.stats.reused).toBe(2 * bands);
- expect(shape(memoised)).toEqual(shape(resolveSelection(wider, ctx)));
- });
-
it("recomputes only the part that was edited", () => {
const resolver = new SelectionResolver();
resolver.resolve(selection, ctx);
@@ -386,12 +317,12 @@ describe("SelectionResolver", () => {
const resolver = new SelectionResolver();
resolver.resolve(selection, ctx);
expect(resolver.size).toBe(3 * bands);
- resolver.resolve(withoutPart(selection, "route-1"), ctx);
+ resolver.resolve(withoutPart(selection, "box-2"), ctx);
expect(resolver.size).toBe(2 * bands);
resolver.stats.computed = 0;
resolver.invalidate("box-1");
- resolver.resolve(withoutPart(selection, "route-1"), ctx);
+ resolver.resolve(withoutPart(selection, "box-2"), ctx);
expect(resolver.stats.computed).toBe(bands);
resolver.invalidateAll();
@@ -410,7 +341,7 @@ describe("SelectionResolver", () => {
name: "Terrain box",
box: { minLat: first.minLat + 1, minLon: first.minLon + 1, maxLat: first.maxLat - 1, maxLon: first.maxLon + 2 * 8192 },
};
- const r = resolveSelection({ parts: [wide], corridorRadiusM: 0 }, { ...ctx, terrain });
+ const r = resolveSelection({ parts: [wide] }, { ...ctx, terrain });
expect(r.terrain.cells).toEqual(["13/38528/33664", "13/38528/33665"]);
expect(r.terrain.knownEmpty).toEqual(["13/38528/33667"]);
expect(r.terrain.missing).toEqual(["13/38528/33666"]);
@@ -420,7 +351,7 @@ describe("SelectionResolver", () => {
it("takes a region's terrain from its published list, never from its outline", () => {
const terrain = exampleTerrainIndex();
- const r = resolveSelection({ parts: [region], corridorRadiusM: 0 }, { ...ctx, terrain });
+ const r = resolveSelection({ parts: [region] }, { ...ctx, terrain });
// Exactly the region satellite's `terrain` array — two objects and the
// one canonically void square.
expect([...r.terrain.cells, ...r.terrain.knownEmpty].sort()).toEqual(swissCells.terrain);
@@ -428,7 +359,7 @@ describe("SelectionResolver", () => {
});
it("names no terrain at all when the catalog publishes none (§13)", () => {
- const r = resolveSelection({ parts: [region], corridorRadiusM: 0 }, ctx);
+ const r = resolveSelection({ parts: [region] }, ctx);
expect(r.terrain.cells).toEqual([]);
expect(r.terrain.bytes).toBe(0);
});
@@ -444,7 +375,7 @@ describe("SelectionResolver", () => {
}),
};
const resolver = new SelectionResolver();
- expect(() => resolver.resolve({ parts: [region], corridorRadiusM: 0 }, broken)).toThrow(
+ expect(() => resolver.resolve({ parts: [region] }, broken)).toThrow(
CatalogFormatError,
);
});
diff --git a/builder/web/src/lib/catalog/selection.ts b/builder/web/src/lib/catalog/selection.ts
index 02e2a6e696..369d69bb07 100644
--- a/builder/web/src/lib/catalog/selection.ts
+++ b/builder/web/src/lib/catalog/selection.ts
@@ -17,9 +17,7 @@
// * **Overlap is free.** Two parts sharing ground share the *same cells*, and
// the union counts them once, which is why per-part bytes need two answers.
-import { corridorCells, type LatLon } from "./corridor";
import { cellsIntersecting, formatCellId, type UBox } from "../core/grid";
-import { lassoCells } from "./lasso";
import type { BandEntry, Catalog } from "./manifest";
import {
assertRegionCellsIndexed,
@@ -30,14 +28,12 @@ import {
type TerrainIndexDocument,
} from "./satellites";
-export type { LatLon } from "./corridor";
-
interface PartBase {
/** Stable within a session; the UI's key for the row and the remove button. */
id: string;
/**
* What the parts list calls it. Held by the part rather than derived, because
- * the three kinds get their names from three different places, and a list
+ * the kinds get their names from different places, and a list
* that renamed a row when the catalog reloaded would be a list that cannot be
* trusted to be the same list.
*/
@@ -56,31 +52,11 @@ export interface BoxPart extends PartBase {
box: UBox;
}
-/** One route, buffered by the selection's global corridor radius. */
-export interface CorridorPart extends PartBase {
- kind: "corridor";
- points: LatLon[];
-}
-
-/** A freehand ring drawn on the map, in integer microdegrees. Closed
- * implicitly — the last point connects back to the first. */
-export interface LassoPart extends PartBase {
- kind: "lasso";
- points: LatLon[];
-}
-
-export type SelectionPart = RegionPart | BoxPart | CorridorPart | LassoPart;
+export type SelectionPart = RegionPart | BoxPart;
-/**
- * A selection: the parts, and the one corridor width that applies to every route
- * in the map.
- *
- * The radius is on the selection rather than on each corridor part because it is
- * a single global slider. Per-part widths would be a different UI.
- */
+/** A selection: the parts, in the order they were added. */
export interface Selection {
parts: SelectionPart[];
- corridorRadiusM: number;
}
/** Everything a resolution needs that is not in the selection itself. */
@@ -172,8 +148,8 @@ export interface SelectionResolution {
}
/** A selection with nothing in it. */
-export function emptySelection(corridorRadiusM: number): Selection {
- return { parts: [], corridorRadiusM };
+export function emptySelection(): Selection {
+ return { parts: [] };
}
/**
@@ -198,11 +174,6 @@ export function withoutPart(selection: Selection, partId: string): Selection {
return { ...selection, parts: selection.parts.filter((p) => p.id !== partId) };
}
-/** Set the one global corridor width. */
-export function withCorridorRadius(selection: Selection, radiusM: number): Selection {
- return { ...selection, corridorRadiusM: Math.max(0, radiusM) };
-}
-
/**
* Re-apply the cross-document rule over the full set of loaded indices — the set
* the client could not check when it fetched the region list one round trip
@@ -229,7 +200,7 @@ function assertRegionListsIndexed(selection: Selection, ctx: SelectionContext):
* The cell ids one part contributes to one band, before any published/missing
* distinction — pure geometry, or for a region pure lookup.
*/
-function partCells(part: SelectionPart, bandEntry: BandEntry, ctx: SelectionContext, radiusM: number): string[] {
+function partCells(part: SelectionPart, bandEntry: BandEntry, ctx: SelectionContext): string[] {
switch (part.kind) {
case "region": {
const list = ctx.regionCells.get(part.regionId);
@@ -242,10 +213,6 @@ function partCells(part: SelectionPart, bandEntry: BandEntry, ctx: SelectionCont
}
case "box":
return cellsIntersecting(bandEntry.cell_log2, part.box).map(formatCellId);
- case "corridor":
- return corridorCells(bandEntry.cell_log2, part.points, radiusM).map(formatCellId);
- case "lasso":
- return lassoCells(bandEntry.cell_log2, part.points).map(formatCellId);
}
}
@@ -253,21 +220,17 @@ function partCells(part: SelectionPart, bandEntry: BandEntry, ctx: SelectionCont
* The terrain squares one part covers — the same coverage rule, applied to the
* terrain grid.
*
- * There is no terrain special case here and there must never be one: a box and a
- * corridor resolve through exactly the test the bands use, and a region reads its
+ * There is no terrain special case here and there must never be one: a box
+ * resolves through exactly the test the bands use, and a region reads its
* published list, because deriving one from the drawable boundary would let a
* simplification error drop an edge square.
*/
-function partTerrainCells(part: SelectionPart, log2: number, ctx: SelectionContext, radiusM: number): string[] {
+function partTerrainCells(part: SelectionPart, log2: number, ctx: SelectionContext): string[] {
switch (part.kind) {
case "region":
return [...(ctx.regionCells.get(part.regionId)?.terrain ?? [])];
case "box":
return cellsIntersecting(log2, part.box).map(formatCellId);
- case "corridor":
- return corridorCells(log2, part.points, radiusM).map(formatCellId);
- case "lasso":
- return lassoCells(log2, part.points).map(formatCellId);
}
}
@@ -284,12 +247,11 @@ function classify(
part: SelectionPart,
bandEntry: BandEntry,
ctx: SelectionContext,
- radiusM: number,
index: CellIndexDocument,
): BandCells {
const published: string[] = [];
const missing: string[] = [];
- for (const id of new Set(partCells(part, bandEntry, ctx, radiusM))) {
+ for (const id of new Set(partCells(part, bandEntry, ctx))) {
(cellIndexHas(index, id) ? published : missing).push(id);
}
return { published: published.sort(), missing: missing.sort() };
@@ -302,14 +264,12 @@ type CellSource = (part: SelectionPart, bandEntry: BandEntry, index: CellIndexDo
* Resolve a selection into the cells it names, per band, with per-part
* attribution.
*
- * The one-shot path: it computes every part from scratch. A UI holding a slider
- * does not want that sixty times a second — see {@link SelectionResolver}.
+ * The one-shot path: it computes every part from scratch. A UI that resolves on
+ * every change does not want that — see {@link SelectionResolver}.
*/
export function resolveSelection(selection: Selection, ctx: SelectionContext): SelectionResolution {
assertRegionListsIndexed(selection, ctx);
- return resolveWith(selection, ctx, (part, bandEntry, index) =>
- classify(part, bandEntry, ctx, selection.corridorRadiusM, index),
- );
+ return resolveWith(selection, ctx, (part, bandEntry, index) => classify(part, bandEntry, ctx, index));
}
function resolveWith(selection: Selection, ctx: SelectionContext, cellsFor: CellSource): SelectionResolution {
@@ -367,9 +327,7 @@ function resolveWith(selection: Selection, ctx: SelectionContext, cellsFor: Cell
if (terrainIndex) {
const seen = new Set();
for (const part of selection.parts) {
- for (const id of partTerrainCells(part, terrainIndex.cell_log2, ctx, selection.corridorRadiusM)) {
- seen.add(id);
- }
+ for (const id of partTerrainCells(part, terrainIndex.cell_log2, ctx)) seen.add(id);
}
for (const id of [...seen].sort()) {
const entry = terrainIndex.byId.get(id);
@@ -421,7 +379,6 @@ function sortedLists(source: Map>): Map {
* comparison rather than a convention. */
interface CachedBand {
part: SelectionPart;
- radiusM: number;
index: CellIndexDocument;
regionList: RegionCellsDocument | undefined;
cells: BandCells;
@@ -430,15 +387,14 @@ interface CachedBand {
/**
* `resolveSelection`, but remembering what it worked out.
*
- * The reason is the corridor slider. Resolving a bikepacking-sized selection is
- * tens of milliseconds and a slider asks for a new answer on every frame it
- * moves, yet almost none of that work is new: a global corridor width changes
- * what the *corridor* parts cover and nothing else.
+ * Resolving a bikepacking-sized selection is tens of milliseconds, and the
+ * selection changes one part at a time: an added box or region, or a region's
+ * cell list that arrives, leaves the answer of every other part as it was.
*
* So the cache is keyed per **(part, band)** — the finest grain at which an
* answer is reusable — and an entry is reused only when everything it was
* computed from is still the same object: the part itself, the band's index
- * document, the region's cell list, and for corridors the radius. Parts are
+ * document and the region's cell list. Parts are
* values here, replaced rather than edited by `withPart`, so identity is the
* right test; a caller that does edit one in place says so with
* {@link invalidate}.
@@ -481,15 +437,14 @@ export class SelectionResolver {
hit &&
hit.part === part &&
hit.index === index &&
- hit.regionList === regionList &&
- (part.kind !== "corridor" || hit.radiusM === selection.corridorRadiusM)
+ hit.regionList === regionList
) {
this.stats.reused += 1;
return hit.cells;
}
this.stats.computed += 1;
- const cells = classify(part, bandEntry, ctx, selection.corridorRadiusM, index);
- this.cache.set(key, { part, radiusM: selection.corridorRadiusM, index, regionList, cells });
+ const cells = classify(part, bandEntry, ctx, index);
+ this.cache.set(key, { part, index, regionList, cells });
return cells;
});
// A removed part must not keep its answers alive: a session that adds
diff --git a/builder/web/src/lib/cells/workBarrier.ts b/builder/web/src/lib/cells/workBarrier.ts
index 84b2d13a83..c6f75c9844 100644
--- a/builder/web/src/lib/cells/workBarrier.ts
+++ b/builder/web/src/lib/cells/workBarrier.ts
@@ -1,16 +1,29 @@
-// OPFS map work is origin-global, while DownloadStep is only component-local.
-// A remount (or a second builder surface) must therefore wait for the previous
-// component's uninterruptible writes and cleanup before it clears or reuses the
-// same directories.
+// OPFS map work is origin-global, while a map run belongs to one component of one tab. A remount, the map send of
+// the planner and a second tab must therefore wait for the uninterruptible writes and the cleanup of the owner before
+// them, before they clear or reuse the same directories. The Web Lock orders them in the whole browser.
+
+const LOCK = "obc-map-work";
let tail: Promise = Promise.resolve();
-/** Acquire exclusive ownership of the builder's OPFS map-work directories. */
-export async function acquireMapWorkStorage(): Promise<() => void> {
+/** The order of one tab, for a host with no Web Locks. */
+async function inTab(): Promise<() => void> {
const previous = tail;
let unlock!: () => void;
tail = new Promise((resolve) => (unlock = resolve));
await previous;
+ return unlock;
+}
+
+/** Acquire exclusive ownership of the OPFS map-work directories. `signal` ends the wait with its reason. */
+export async function acquireMapWorkStorage(signal?: AbortSignal): Promise<() => void> {
+ const locks = globalThis.navigator?.locks;
+ const unlock = locks
+ ? await new Promise<() => void>((resolve, reject) => {
+ // The lock is held until the promise of the callback resolves.
+ locks.request(LOCK, { signal }, () => new Promise((release) => resolve(release))).catch(reject);
+ })
+ : await inTab();
let released = false;
return () => {
if (released) return;
@@ -18,3 +31,9 @@ export async function acquireMapWorkStorage(): Promise<() => void> {
unlock();
};
}
+
+/** Whether another owner holds the map-work directories now, in this tab or in another one. */
+export async function mapWorkBusy(): Promise {
+ const state = await globalThis.navigator?.locks?.query();
+ return !!state?.held?.some((lock) => lock.name === LOCK);
+}
diff --git a/builder/web/src/lib/constants.ts b/builder/web/src/lib/constants.ts
index 68d40e60a6..1207ff0874 100644
--- a/builder/web/src/lib/constants.ts
+++ b/builder/web/src/lib/constants.ts
@@ -6,8 +6,8 @@
* deployed. `VITE_SITE_BASE` is that fact:
*
* * unset — the default — means the site is somewhere else, so name it
- * absolutely. That is the dev server and the desktop app: neither is served
- * from the site, and a relative link there would point at nothing.
+ * absolutely. That is the dev server: it is not served from the site, and a
+ * relative link there would point at nothing.
* * set to a relative prefix (the deploy passes `../`, because the builder is
* published at `/builder/` beside `/docs/`) means the site is right here.
* Nothing absolute is baked in, so the whole artifact survives the move to a
@@ -35,12 +35,9 @@ export const LINKS = {
github: "https://github.com/timohueser/OpenBikeComputer",
/**
* The bundle's own third-party notices, emitted beside it at build time by
- * `vite/third-party-licenses.ts` — so it stays relative in every tier, including the
- * desktop app, where the file sits next to `index.html` inside the Tauri bundle.
+ * `vite/third-party-licenses.ts` — so it stays relative in every tier.
* `vite dev` has no bundle and therefore no file; the link 404s there by design,
* because a stale checked-in copy would be worse than an absent one.
*/
licenses: "./third-party-licenses.txt",
- /** Where the desktop installers are published. */
- releases: "https://github.com/timohueser/OpenBikeComputer/releases",
};
diff --git a/builder/web/src/lib/convert/bridge.test.ts b/builder/web/src/lib/convert/bridge.test.ts
index 33e3271c7d..469c80d505 100644
--- a/builder/web/src/lib/convert/bridge.test.ts
+++ b/builder/web/src/lib/convert/bridge.test.ts
@@ -19,7 +19,7 @@ import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { beforeAll, describe, expect, it } from "vitest";
-import { ConvertError, gpxToObcr, initConvert, routeTrack, routeWaypoints, trackToGpx } from "./bridge";
+import { ConvertError, gpxToObcr, initConvert, trackToGpx } from "./bridge";
/**
* The OBCR header's name field, and the GPX ``, are inputs to the conversion, so they have
@@ -124,108 +124,6 @@ describe("trackToGpx", () => {
});
});
-describe("routeTrack", () => {
- it("reads back the polyline the converter stored, elevation included", async () => {
- // The fixture's OBCR is byte-pinned above, so the read-back is checked against the same
- // source of truth: what the GPX said, within the format's microdegree resolution.
- const points = await routeTrack(vector("route-waypoints.obcr"));
- expect(points.length).toBeGreaterThan(2);
- for (const p of points) {
- expect(p.lat).toBeGreaterThan(-90);
- expect(p.lat).toBeLessThan(90);
- expect(p.lon).toBeGreaterThan(-180);
- expect(p.lon).toBeLessThan(180);
- expect(Number.isFinite(p.ele)).toBe(true);
- }
- // Round-trip a fresh conversion: a stored point count equals the read-back count.
- const gpx = text("host/obc-vectors/src/route-source.gpx");
- const obcr = await gpxToObcr(new TextEncoder().encode(gpx), ROUTE_NAME, 0);
- const view = new DataView(obcr.buffer, obcr.byteOffset, obcr.byteLength);
- expect((await routeTrack(obcr)).length).toBe(view.getUint32(32, true));
- });
-
- it("refuses bytes that are not a route, with the stable code", async () => {
- const failure = await routeTrack(new Uint8Array(200)).catch((e: unknown) => e);
- expect(failure).toBeInstanceOf(ConvertError);
- expect((failure as ConvertError).code).toBe("not-route");
- });
-});
-
-describe("routeWaypoints", () => {
- it("reads back the fixture's waypoint table, decoded and in route order", async () => {
- // `route-source.gpx` carries two ``s: "Pass Summit" (`Viewpoint ` —
- // deliberately unmapped, so generic) and "Brunnen" (`Drinking Water ` → water).
- const wps = await routeWaypoints(vector("route-waypoints.obcr"));
- expect(wps.map((w) => w.name).sort()).toEqual(["Brunnen", "Pass Summit"]);
- for (let i = 1; i < wps.length; i++) {
- expect(wps[i].distAlongM).toBeGreaterThanOrEqual(wps[i - 1].distAlongM);
- }
-
- const brunnen = wps.find((w) => w.name === "Brunnen")!;
- expect(brunnen.category).toBe(1);
- expect(brunnen.ele).toBe(238);
- expect(brunnen.lat).toBeCloseTo(48.0001, 4);
- expect(brunnen.lon).toBeCloseTo(7.8201, 4);
-
- const summit = wps.find((w) => w.name === "Pass Summit")!;
- expect(summit.category).toBe(0);
- expect(summit.ele).toBeNull();
-
- // The absolute distances, not just their order — the modal's `km x.y` labels rest on
- // this field. The fixture is byte-pinned, so these are exact stored `uint32` metres:
- // Brunnen anchors at the first raw track point, the summit ~1.7 km in.
- expect(brunnen.distAlongM).toBe(0);
- expect(summit.distAlongM).toBe(1700);
- });
-
- it("agrees with a fresh conversion of the same GPX", async () => {
- // The other way the device gets waypoints: `gpxToObcr` on a GPX with ``s. The
- // fixture is byte-pinned to that conversion above, so the tables must agree exactly.
- const gpx = text("host/obc-vectors/src/route-source.gpx");
- const obcr = await gpxToObcr(new TextEncoder().encode(gpx), ROUTE_NAME, 0);
- expect(await routeWaypoints(obcr)).toEqual(await routeWaypoints(vector("route-waypoints.obcr")));
- });
-
- it("resolves to an empty list for a route without waypoints", async () => {
- expect(await routeWaypoints(vector("route-plain.obcr"))).toEqual([]);
- });
-
- it("refuses bytes that are not a route, with the stable code", async () => {
- const failure = await routeWaypoints(new Uint8Array(200)).catch((e: unknown) => e);
- expect(failure).toBeInstanceOf(ConvertError);
- expect((failure as ConvertError).code).toBe("not-route");
- });
-});
-
-describe("captured planner exports", () => {
- /**
- * `fixtures/sources/route-import/` holds the real files, with their provenance and licence. The
- * names and the order below are the list `obc-route` and `obc-app` assert on the same bytes, so
- * a browser import and a device import agree on what a planner actually sent.
- */
- it("reads the komoot export's waypoints the way the Rust importer does", async () => {
- const gpx = text("fixtures/sources/route-import/komoot-schwarzwald.gpx");
- const obcr = await gpxToObcr(new TextEncoder().encode(gpx), "Schwarzwald", 0);
- const wps = await routeWaypoints(obcr);
-
- expect(wps.length).toBe(gpx.split(" w.name)).toEqual([
- "Steiler Abschnitt auf de",
- "Freudenst\u00e4dter Wasserfo",
- "Feuerstelle Schmidsberge",
- "Blick auf die Landschaft",
- "Fuxxbau",
- ]);
- // `Restaurant` is resupply; `Fishing Hot Spot Facility` has no home among the six and stays
- // generic instead of being dropped or forced into the nearest one.
- expect(wps.map((w) => w.category)).toEqual([0, 0, 0, 0, 4]);
- for (let i = 1; i < wps.length; i++) {
- expect(wps[i].distAlongM).toBeGreaterThanOrEqual(wps[i - 1].distAlongM);
- }
- });
-});
-
describe("failures", () => {
const bytes = (s: string): Uint8Array => new TextEncoder().encode(s);
diff --git a/builder/web/src/lib/convert/bridge.ts b/builder/web/src/lib/convert/bridge.ts
index a00ce9bd7b..96a2dc6587 100644
--- a/builder/web/src/lib/convert/bridge.ts
+++ b/builder/web/src/lib/convert/bridge.ts
@@ -26,7 +26,6 @@ import { initCore } from "../core/bridge";
* - `not-ride` — the bytes are not one complete ride object.
* - `ride-no-points` — the finished ride has no recorded samples.
* - `input-truncated` — a read ran off the end of the file.
- * - `not-route` — the bytes handed to the route read-back are not an OBCR route.
*/
export type ConvertErrorCode =
| "empty-file"
@@ -36,7 +35,6 @@ export type ConvertErrorCode =
| "not-ride"
| "ride-no-points"
| "input-truncated"
- | "not-route"
| "internal";
/** A conversion failure: a stable {@link ConvertErrorCode} plus a message written for a rider. */
@@ -95,88 +93,46 @@ export async function gpxToObcr(gpx: Uint8Array, name: string, bike: number): Pr
}
}
-/**
- * Convert a finished ride-v6 object's bytes into a GPX 1.1 document naming the track `name`.
- *
- * @throws {ConvertError} with an actionable message; see {@link ConvertErrorCode}.
- */
-export async function trackToGpx(ride: Uint8Array, name: string): Promise {
- const mod = await ensure();
- try {
- return mod.obc_convert_track_to_gpx(ride, name);
- } catch (cause) {
- throw asConvertError(cause);
- }
-}
-
-/** One point of a decoded route polyline, degrees and metres. */
-export interface TrackPoint {
- readonly lat: number;
- readonly lon: number;
- readonly ele: number;
+/** A waypoint on a calculated line: microdegrees, metres along the line, and an OBCR category (`0` generic). */
+export interface LineWaypoint {
+ lon: number;
+ lat: number;
+ distanceM: number;
+ category: number;
+ /** Cut to the 24-byte field on a character boundary. */
+ name: string;
}
/**
- * Read a `.obcr` route's polyline back out — the preview's direction. The wasm side returns flat
- * `[lat°, lon°, ele m]` triples in one `Float64Array`; this unpacks them into points.
+ * Encode a calculated line into a `.obcr` route named `name` and typed `bike` (`0..=3`). `coordinates` holds longitude
+ * and latitude in microdegrees for each point, `heights` metres or null, and `surfaces[i]` the surface class of the
+ * segment that ends at point `i`.
*
* @throws {ConvertError} with an actionable message; see {@link ConvertErrorCode}.
*/
-export async function routeTrack(obcr: Uint8Array): Promise {
+export async function lineToObcr(line: { coordinates: Int32Array; heights: (number | null)[]; surfaces: Uint8Array },
+ waypoints: LineWaypoint[], name: string, bike: number): Promise {
const mod = await ensure();
- let flat: Float64Array;
try {
- flat = mod.obc_convert_obcr_to_track(obcr);
+ const heights = Int16Array.from(line.heights, height => height === null ? -0x8000 : Math.round(height));
+ return mod.obc_convert_line_to_obcr(line.coordinates, heights, line.surfaces, JSON.stringify(waypoints), name, bike);
} catch (cause) {
throw asConvertError(cause);
}
- const points: TrackPoint[] = [];
- for (let i = 0; i + 2 < flat.length; i += 3) {
- points.push({ lat: flat[i], lon: flat[i + 1], ele: flat[i + 2] });
- }
- return points;
}
/**
- * One waypoint of a route: a point of interest pinned along the track, with the position it was
- * pinned at.
- */
-export interface RouteWaypoint {
- /** The stored short name (≤ 24 UTF-8 bytes; may be empty). */
- readonly name: string;
- /** The waypoint's own coordinate, degrees — may sit off the polyline. */
- readonly lat: number;
- readonly lon: number;
- /** Metres, or null where the source carried none. */
- readonly ele: number | null;
- /** The stored category byte raw: 0 = generic, 1..=6 the POI category ids. Render anything else
- * as generic. */
- readonly category: number;
- /** Metres from the route start to the waypoint's position on the track — the stored
- * placement-time distance, not a recomputation. */
- readonly distAlongM: number;
-}
-
-/**
- * Read a `.obcr` route's waypoint table back out, in route order (ascending {@link
- * RouteWaypoint.distAlongM}). A route without waypoints resolves to `[]`.
+ * Convert a finished ride-v6 object's bytes into a GPX 1.1 document naming the track `name`.
*
* @throws {ConvertError} with an actionable message; see {@link ConvertErrorCode}.
*/
-export async function routeWaypoints(obcr: Uint8Array): Promise {
+export async function trackToGpx(ride: Uint8Array, name: string): Promise {
const mod = await ensure();
- let raw: unknown[];
try {
- raw = mod.obc_convert_obcr_to_waypoints(obcr);
+ return mod.obc_convert_track_to_gpx(ride, name);
} catch (cause) {
throw asConvertError(cause);
}
- // The wasm side builds these objects field by field, so the cast is a statement about that code
- // rather than about arbitrary input; the copy keeps the result plain-JS-owned.
- return raw.map((entry) => {
- const w = entry as RouteWaypoint;
- return { name: w.name, lat: w.lat, lon: w.lon, ele: w.ele, category: w.category, distAlongM: w.distAlongM };
- });
}
function ensure(): Promise {
@@ -191,7 +147,6 @@ const CODES: ReadonlySet = new Set([
"not-ride",
"ride-no-points",
"input-truncated",
- "not-route",
"internal",
]);
diff --git a/builder/web/src/lib/core/fit.test.ts b/builder/web/src/lib/core/fit.test.ts
new file mode 100644
index 0000000000..0216b30e11
--- /dev/null
+++ b/builder/web/src/lib/core/fit.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vitest";
+import { FitError, readFit, writeFitCourse, writeFitRide, type FitCourse, type FitRide } from "./fit";
+
+describe("FIT", () => {
+ it("reads a written ride with the same values", () => {
+ const ride: FitRide = {
+ sport: "gravel",
+ samples: [
+ { timeS: 1_760_000_000, lat: 46_571_234, lon: 8_100_000, segmentStart: true, elevationM: 2164.4 },
+ {
+ timeS: 1_760_000_001, lat: 46_571_300, lon: 8_100_010, segmentStart: false,
+ speedMps: 7.25, hrBpm: 142, cadenceRpm: 88, powerW: 231, temperatureC: -3,
+ },
+ { timeS: 1_760_000_400, lat: 46_571_400, lon: 8_100_020, segmentStart: true },
+ ],
+ };
+ expect(readFit(writeFitRide(ride), "x")).toEqual(ride);
+ });
+
+ it("reads a written course with the same values, and names it from the fallback when it has no name", () => {
+ const course: FitCourse = {
+ name: "",
+ points: [{ lat: 46_560_000, lon: 8_400_000, ele: 1708.2 }, { lat: 46_570_000, lon: 8_400_000 }],
+ waypoints: [{ lat: 46_570_000, lon: 8_400_000, name: "Wasser" }],
+ elapsedS: 3600,
+ };
+ expect(readFit(writeFitCourse(course), "Furka")).toEqual({ ...course, name: "Furka" });
+ });
+
+ it("throws a FitError with a code", () => {
+ const read = () => readFit(new TextEncoder().encode(" "), "x");
+ expect(read).toThrow(FitError);
+ expect(read).toThrow(expect.objectContaining({ code: "not-fit" }));
+ });
+});
diff --git a/builder/web/src/lib/core/fit.ts b/builder/web/src/lib/core/fit.ts
new file mode 100644
index 0000000000..df0059c04e
--- /dev/null
+++ b/builder/web/src/lib/core/fit.ts
@@ -0,0 +1,83 @@
+import { core } from "./bridge";
+import type { GpxImport, GpxPoint, GpxWaypoint, Sensors } from "./gpx";
+
+/** `unknown`: the file has no session, as after a power loss. It is written as `other`. */
+export type FitSport = "road" | "gravel" | "mtb" | "bike" | "foot" | "other" | "unknown";
+
+/** One recorded point of a ride, in microdegrees. An absent value has no key. */
+export interface FitSample extends Sensors {
+ /** Unix time in seconds. */
+ timeS: number;
+ lat: number;
+ lon: number;
+ /** True for the first sample of the ride and for the first sample after a pause. */
+ segmentStart: boolean;
+ elevationM?: number;
+ speedMps?: number;
+}
+
+export interface FitRide { sport: FitSport; samples: FitSample[] }
+/** A planned route, with the time of the whole course in seconds. */
+export type FitCourse = GpxImport & { elapsedS: number };
+
+export class FitError extends Error {
+ constructor(message: string, readonly code: string) { super(message); this.name = "FitError"; }
+}
+
+/** The optional values after time, lat, lon and segmentStart, in the order of the bridge. */
+const OPTIONAL = ["elevationM", "speedMps", "hrBpm", "cadenceRpm", "powerW", "temperatureC"] as const;
+const VALUES = 4 + OPTIONAL.length;
+
+type RawFit =
+ | { sport: FitSport; samples: Float64Array }
+ | { name: string; points: Float64Array; waypoints: Float64Array; names: (string | undefined)[]; elapsedS: number };
+
+/** Reads a FIT activity as a ride, or a FIT course as a route. A course with no name gets `fallback`. */
+export function readFit(bytes: Uint8Array, fallback: string): FitRide | FitCourse {
+ let raw: RawFit;
+ try { raw = core().obc_fit_read(bytes, fallback) as RawFit; } catch (cause) {
+ if (cause instanceof Error && cause.name === "FitError") {
+ throw new FitError(cause.message, (cause as Error & { code: string }).code);
+ }
+ throw cause;
+ }
+ if ("samples" in raw) {
+ const v = raw.samples;
+ const samples: FitSample[] = [];
+ for (let at = 0; at < v.length; at += VALUES) {
+ const sample: FitSample = { timeS: v[at], lat: v[at + 1], lon: v[at + 2], segmentStart: v[at + 3] === 1 };
+ OPTIONAL.forEach((key, k) => { if (!Number.isNaN(v[at + 4 + k])) sample[key] = v[at + 4 + k]; });
+ samples.push(sample);
+ }
+ return { sport: raw.sport, samples };
+ }
+ const points: GpxPoint[] = [];
+ for (let at = 0; at < raw.points.length; at += 3) {
+ const [lat, lon, ele] = raw.points.subarray(at, at + 3);
+ points.push(Number.isNaN(ele) ? { lat, lon } : { lat, lon, ele });
+ }
+ const waypoints: GpxWaypoint[] = raw.names.map((name, i) => {
+ const [lat, lon] = raw.waypoints.subarray(2 * i, 2 * i + 2);
+ return name === undefined ? { lat, lon } : { lat, lon, name };
+ });
+ return { name: raw.name, points, waypoints, elapsedS: raw.elapsedS };
+}
+
+export function writeFitRide(ride: FitRide): Uint8Array {
+ const values = new Float64Array(ride.samples.length * VALUES);
+ ride.samples.forEach((s, i) => {
+ values.set([s.timeS, s.lat, s.lon, s.segmentStart ? 1 : 0, ...OPTIONAL.map((key) => s[key] ?? NaN)], i * VALUES);
+ });
+ return core().obc_fit_write_ride(ride.sport, values);
+}
+
+/** Writes a course. A waypoint note is not written. */
+export function writeFitCourse(course: FitCourse): Uint8Array {
+ return core().obc_fit_write_course(
+ course.name,
+ Float64Array.from(course.points.flatMap((p) => [p.lat, p.lon, p.ele ?? NaN])),
+ Float64Array.from(course.waypoints.flatMap((w) => [w.lat, w.lon])),
+ course.waypoints.map((w) => w.name ?? ""),
+ course.elapsedS,
+ );
+}
diff --git a/builder/web/src/lib/core/gpx.test.ts b/builder/web/src/lib/core/gpx.test.ts
new file mode 100644
index 0000000000..d71063e6b2
--- /dev/null
+++ b/builder/web/src/lib/core/gpx.test.ts
@@ -0,0 +1,136 @@
+import { describe, expect, it } from "vitest";
+import { GpxError, readGpx, writeGpx, type GpxImport } from "./gpx";
+
+describe("writeGpx", () => {
+ it("writes a file that readGpx reads back unchanged", () => {
+ const route: GpxImport = {
+ name: "Lake & \"back\"",
+ points: [{ lat: 46_912_345, lon: -8_600_001, ele: 434.5, segmentStart: true }, { lat: 46_950_000, lon: 8_610_000 }, { lat: -46_960_000, lon: 8_620_000, ele: -2 }],
+ waypoints: [{ lat: 46_950_000, lon: 8_610_000, name: "Tell's chapel", note: "swim here" }, { lat: 46_960_000, lon: 8_620_000, name: undefined }],
+ };
+ expect(readGpx(writeGpx(route), "fallback")).toEqual(route);
+ });
+
+ it("keeps the times and the segments of a ride", () => {
+ const ride: GpxImport = {
+ name: "Ride",
+ points: [{ lat: 46_900_000, lon: 8_400_000, ele: 1000, time: 1_792_828_800, segmentStart: true }, { lat: 46_901_000, lon: 8_400_000, time: 1_792_828_801.5 },
+ { lat: 46_902_000, lon: 8_400_000, time: 1_792_829_400, segmentStart: true }],
+ waypoints: [],
+ };
+ expect(readGpx(writeGpx(ride), "fallback")).toEqual(ride);
+ });
+
+ it("keeps the sensors of a point, with heart rate and cadence as whole numbers", () => {
+ const point = { lat: 46_900_000, lon: 8_400_000, time: 1_792_828_800 };
+ const ride: GpxImport = { name: "Ride", waypoints: [], points: [{ ...point, segmentStart: true, hrBpm: 141.6, cadenceRpm: 87.2, powerW: 250.5, temperatureC: -3.5 }, point] };
+ expect(readGpx(writeGpx(ride), "fallback").points).toEqual([{ ...point, segmentStart: true, hrBpm: 142, cadenceRpm: 87, powerW: 250.5, temperatureC: -3.5 }, point]);
+ const outside = writeGpx({ ...ride, points: [{ ...point, hrBpm: 300, cadenceRpm: -1 }, point] });
+ expect(outside).not.toContain("");
+ });
+});
+
+const HEADER = '';
+
+function track(points: string, name?: string): string {
+ return `${HEADER}${name ? `${name} ` : ""}${points} `;
+}
+
+describe("readGpx", () => {
+ it("reads track points into integer microdegrees", () => {
+ const route = readGpx(
+ track('210 '),
+ "file",
+ );
+ expect(route.points).toEqual([
+ { lat: 47_500_000, lon: 7_750_000, ele: 210, segmentStart: true },
+ { lat: 47_600_000, lon: 7_800_000 },
+ ]);
+ });
+
+ it("accepts either attribute order, either quote style, self-closing or not", () => {
+ const route = readGpx(
+ track(""),
+ "file",
+ );
+ expect(route.points).toHaveLength(2);
+ expect(route.points[0]).toEqual({ lat: 47_000_000, lon: 8_000_000, segmentStart: true });
+ });
+
+ it("joins the segments and the tracks of a file, and marks the first point of each", () => {
+ const body = `${HEADER} `
+ + ' ';
+ expect(readGpx(body, "file").points.map(p => p.segmentStart ?? false)).toEqual([true, false, true, true, false]);
+ });
+
+ it("reads the time of each point as UTC Unix seconds, and the type of the track", () => {
+ const at = (time: string) => `${time} `;
+ const body = `${HEADER}Ride cycling ${
+ ["2026-08-01T07:00:00Z", "2026-08-01T09:00:01.5+02:00", "2026-08-01T07:00:02", " 2026-08-01T06:30:03-00:30 ", "1 August", "2026-13-01T00:00:00Z"].map(at).join("")
+ }other `;
+ const imported = readGpx(body, "file");
+ const start = Date.UTC(2026, 7, 1, 7) / 1000;
+ expect(imported.points.map(p => p.time)).toEqual([start, start + 1.5, start + 2, start + 3, undefined, undefined, undefined]);
+ expect(imported.kind).toBe("cycling");
+ expect(readGpx(track(' '), "file").kind).toBeUndefined();
+ });
+
+ it("falls back to route points when there are no track points", () => {
+ const body = `${HEADER} `;
+ expect(readGpx(body, "file").points).toHaveLength(2);
+ });
+
+ it("names the route from the track, un-escaping XML entities", () => {
+ const body = `${HEADER}The File Rhein & Rön `;
+ // Only the five predefined entities are un-escaped; numeric references
+ // stay as-is, which is the honest limit of a scanner.
+ expect(readGpx(body, "file").name).toBe("Rhein & Rön");
+ });
+
+ it("prefers the track's own name over the file-level metadata name", () => {
+ const body = `${HEADER}File Name Ride Name `;
+ expect(readGpx(body, "x").name).toBe("Ride Name");
+ });
+
+ it("keeps track-name precedence after a self-closing empty track", () => {
+ const body = `${HEADER}File Ride `;
+ expect(readGpx(body, "fallback").name).toBe("Ride");
+ });
+
+ it("uses the metadata name when the track has none, and the fallback last", () => {
+ const named = `${HEADER}File Name `;
+ expect(readGpx(named, "fallback").name).toBe("File Name");
+ expect(readGpx(track(' '), "fallback").name).toBe(
+ "fallback",
+ );
+ });
+
+ it("refuses a file with no points, naming the likely cause", () => {
+ expect(() => readGpx("not gpx", "x")).toThrow(GpxError);
+ expect(() => readGpx("not gpx", "x")).toThrow(/is this a GPX file/);
+ });
+
+ it("refuses a single point — that is a waypoint, not a route", () => {
+ expect(() => readGpx(track(' '), "x")).toThrow(/fewer than two/);
+ });
+
+ it("counts malformed coordinates instead of silently dropping the file's story", () => {
+ const body = track(' ');
+ expect(() => readGpx(body, "x")).toThrow(/2 of 2 carried malformed coordinates/);
+ });
+
+ it("drops out-of-range coordinates as malformed rather than folding them onto the globe", () => {
+ const body = track(' ');
+ expect(() => readGpx(body, "x")).toThrow(GpxError);
+ });
+ it("preserves full elevation precision, negative ties and waypoint text across the Rust boundary", () => {
+ const body = `${HEADER}Water Open & free Track 1.23456789123 `;
+ const imported = readGpx(body, "fallback");
+ expect(imported.name).toBe("Track");
+ expect(imported.points).toEqual([{ lat: -0, lon: -1, ele: 1.23456789123, segmentStart: true }, { lat: 47_100_000, lon: 8_000_000 }]);
+ expect(imported.waypoints).toEqual([
+ { lat: 47_000_000, lon: 8_000_000, name: "Water", note: "Open & free" },
+ { lat: 48_000_000, lon: 9_000_000, name: undefined },
+ ]);
+ });
+});
diff --git a/builder/web/src/lib/core/gpx.ts b/builder/web/src/lib/core/gpx.ts
index 58046de7f7..d18938a0f3 100644
--- a/builder/web/src/lib/core/gpx.ts
+++ b/builder/web/src/lib/core/gpx.ts
@@ -1,11 +1,24 @@
import { core } from "./bridge";
-import type { LatLon } from "../catalog/corridor";
-export type GpxPoint = LatLon & { ele?: number };
+/** A coordinate in integer microdegrees, `lat, lon` — the catalog's order. */
+export interface LatLon {
+ lat: number;
+ lon: number;
+}
+
+/** The sensor values of a point or a sample. An absent value has no key. */
+export interface Sensors {
+ hrBpm?: number;
+ cadenceRpm?: number;
+ powerW?: number;
+ temperatureC?: number;
+}
+
+/** `time` is in Unix seconds. `segmentStart` marks the first point of the file and of each track and track segment. */
+export type GpxPoint = LatLon & Sensors & { ele?: number; time?: number; segmentStart?: true };
export type GpxWaypoint = LatLon & { name?: string; note?: string };
-export interface GpxRoute { name: string; points: LatLon[]; distanceKm: number }
-export interface GpxImport { name: string; points: GpxPoint[]; waypoints: GpxWaypoint[] }
-export const MAX_ROUTE_POINTS = core().obc_builder_constants()[5];
+/** `kind` is the `` of the first track, such as `cycling`. */
+export interface GpxImport { name: string; points: GpxPoint[]; waypoints: GpxWaypoint[]; kind?: string }
export class GpxError extends Error {
constructor(message: string) { super(message); this.name = "GpxError"; }
@@ -18,12 +31,47 @@ function read(fn: () => string): T {
}
}
+// The five entities that `readGpx` reads.
+const ENTITIES: Record = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
+const escape = (text: string) => text.replace(/[&<>"']/g, c => ENTITIES[c]);
+const place = ({ lat, lon }: LatLon) => `lat="${(lat / 1e6).toFixed(6)}" lon="${(lon / 1e6).toFixed(6)}"`;
+const text = (tag: string, value: string | undefined) => value ? `<${tag}>${escape(value)}${tag}>` : "";
+
+const number = (tag: string, value: number | undefined) => value === undefined ? "" : `<${tag}>${value}${tag}>`;
+/** The schema types `hr` and `cad` as unsigned bytes: a value out of range has no element. */
+const byte = (value: number | undefined) => {
+ const whole = value === undefined ? -1 : Math.round(value);
+ return whole >= 0 && whole <= 255 ? whole : undefined;
+};
+
+/** The shape of the device export, with `atemp` first as in the schema. */
+function extensions(p: Sensors): string {
+ const garmin = number("gpxtpx:atemp", p.temperatureC) + number("gpxtpx:hr", byte(p.hrBpm)) + number("gpxtpx:cad", byte(p.cadenceRpm));
+ const body = (garmin && `${garmin} `) + number("power", p.powerW);
+ return body && `${body} `;
+}
+
+const point = (p: GpxPoint, i: number) => `${i && p.segmentStart ? "\n" : ""}`
+ + `${number("ele", p.ele)}${p.time === undefined ? "" : `${new Date(p.time * 1000).toISOString()} `}${extensions(p)} `;
+
+/** A GPX 1.1 file with one track and a `wpt` for each waypoint; a waypoint's note is its `desc`. A point with
+ * `segmentStart` after the first starts a new `trkseg`. */
+export function writeGpx(route: GpxImport): string {
+ return [
+ '',
+ '',
+ ...route.waypoints.map(w => `${text("name", w.name)}${text("desc", w.note)} `),
+ `${text("name", route.name)}`,
+ ...route.points.map(point),
+ " ",
+ " ",
+ "",
+ ].join("\n");
+}
+
export function readGpx(text: string, fallback: string): GpxImport {
const imported = read(() => core().obc_gpx_read(text, fallback));
for (const waypoint of imported.waypoints) waypoint.name ??= undefined;
return imported;
}
-
-export function parseGpx(text: string, fallback: string): GpxRoute {
- return read(() => core().obc_gpx_parse(text, fallback));
-}
diff --git a/builder/web/src/lib/coverage/gpx.test.ts b/builder/web/src/lib/coverage/gpx.test.ts
deleted file mode 100644
index 5cae062dbc..0000000000
--- a/builder/web/src/lib/coverage/gpx.test.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { GpxError, MAX_ROUTE_POINTS, parseGpx, readGpx } from "../core/gpx";
-
-const HEADER = '';
-
-function track(points: string, name?: string): string {
- return `${HEADER}${name ? `${name} ` : ""}${points} `;
-}
-
-describe("parseGpx", () => {
- it("reads track points into integer microdegrees", () => {
- const route = parseGpx(
- track('210 '),
- "file",
- );
- expect(route.points).toEqual([
- { lat: 47_500_000, lon: 7_750_000 },
- { lat: 47_600_000, lon: 7_800_000 },
- ]);
- });
-
- it("accepts either attribute order, either quote style, self-closing or not", () => {
- const route = parseGpx(
- track(""),
- "file",
- );
- expect(route.points).toHaveLength(2);
- expect(route.points[0]).toEqual({ lat: 47_000_000, lon: 8_000_000 });
- });
-
- it("joins multiple segments — a recorder losing fix is one ride, not two", () => {
- const body = `${HEADER} `;
- expect(parseGpx(body, "file").points).toHaveLength(2);
- });
-
- it("falls back to route points when there are no track points", () => {
- const body = `${HEADER} `;
- expect(parseGpx(body, "file").points).toHaveLength(2);
- });
-
- it("names the route from the track, un-escaping XML entities", () => {
- const body = `${HEADER}The File Rhein & Rön `;
- // Only the five predefined entities are un-escaped; numeric references
- // stay as-is, which is the honest limit of a scanner.
- expect(parseGpx(body, "file").name).toBe("Rhein & Rön");
- });
-
- it("prefers the track's own name over the file-level metadata name", () => {
- const body = `${HEADER}File Name Ride Name `;
- expect(parseGpx(body, "x").name).toBe("Ride Name");
- });
-
- it("keeps track-name precedence after a self-closing empty track", () => {
- const body = `${HEADER}File Ride `;
- expect(parseGpx(body, "fallback").name).toBe("Ride");
- });
-
- it("uses the metadata name when the track has none, and the fallback last", () => {
- const named = `${HEADER}File Name `;
- expect(parseGpx(named, "fallback").name).toBe("File Name");
- expect(parseGpx(track(' '), "fallback").name).toBe(
- "fallback",
- );
- });
-
- it("measures a degree of latitude as ~111 km", () => {
- const route = parseGpx(track(' '), "x");
- expect(route.distanceKm).toBeGreaterThan(110);
- expect(route.distanceKm).toBeLessThan(113);
- });
-
- it("decimates a dense track to the ceiling, keeping both ends", () => {
- const points = Array.from(
- { length: 10_000 },
- (_, k) => ` `,
- ).join("");
- const route = parseGpx(track(points), "x");
- expect(route.points).toHaveLength(MAX_ROUTE_POINTS);
- expect(route.points[0].lat).toBe(47_000_000);
- expect(route.points.at(-1)!.lat).toBe(47_999_900);
- });
-
- it("refuses a file with no points, naming the likely cause", () => {
- expect(() => parseGpx("not gpx", "x")).toThrow(GpxError);
- expect(() => parseGpx("not gpx", "x")).toThrow(/is this a GPX file/);
- });
-
- it("refuses a single point — that is a waypoint, not a route", () => {
- expect(() => parseGpx(track(' '), "x")).toThrow(/fewer than two/);
- });
-
- it("counts malformed coordinates instead of silently dropping the file's story", () => {
- const body = track(' ');
- expect(() => parseGpx(body, "x")).toThrow(/2 of 2 carried malformed coordinates/);
- });
-
- it("drops out-of-range coordinates as malformed rather than folding them onto the globe", () => {
- const body = track(' ');
- expect(() => parseGpx(body, "x")).toThrow(GpxError);
- });
-});
-
-describe("readGpx", () => {
- it("preserves full elevation precision, negative ties and waypoint text across the Rust boundary", () => {
- const body = `${HEADER}Water Open & free Track 1.23456789123 `;
- const imported = readGpx(body, "fallback");
- expect(imported.name).toBe("Track");
- expect(imported.points).toEqual([{ lat: -0, lon: -1, ele: 1.23456789123 }, { lat: 47_100_000, lon: 8_000_000 }]);
- expect(imported.waypoints).toEqual([
- { lat: 47_000_000, lon: 8_000_000, name: "Water", note: "Open & free" },
- { lat: 48_000_000, lon: 9_000_000, name: undefined },
- ]);
- });
-});
diff --git a/builder/web/src/lib/coverage/run.svelte.ts b/builder/web/src/lib/coverage/run.svelte.ts
new file mode 100644
index 0000000000..bd7488e899
--- /dev/null
+++ b/builder/web/src/lib/coverage/run.svelte.ts
@@ -0,0 +1,1112 @@
+// One map run: cells fetched and verified against the catalog, assembled into ONE `.obcm` by
+// wasm in a Worker, and either downloaded normally or streamed straight to a connected device.
+//
+// A map is one file, so there is nothing to order, nothing to package and nothing to
+// acknowledge: the only question left is where it lands.
+
+import { ASSEMBLE_PHASES, type AssemblePhase, type MemoryEstimate } from "../assemble/bridge";
+import {
+ isWorkerResponse,
+ requestTransferList,
+ type AssembleWorkerRequest,
+ type CellReadMode,
+ type MapWriteMode,
+ type WorkerCell,
+ type WorkerSourceCell,
+ type WorkerTerrainCell,
+} from "../assemble/workerProtocol";
+import {
+ cellStoreRevision,
+ cellStoreWritable,
+ clearAssemblyStorage,
+ clearCellStores,
+ clearMapWorkStorage,
+ discardCellStore,
+ discardMapOutput,
+ hasRoomFor,
+ isStorageQuotaError,
+ openCellInventory,
+ openCellStore,
+ readMapOutput,
+ reclaimableAssemblyBytes,
+ STORAGE_QUOTA_MESSAGE,
+ type CellInventory,
+} from "../cells/store";
+import { projectedRunDiskBytes } from "../cells/quota";
+import { acquireMapWorkStorage } from "../cells/workBarrier";
+import { saveBlob } from "../download";
+import {
+ downloadCells,
+ planCells,
+ type CellDownloadPlan,
+ type CellDownloadProgress,
+} from "../catalog/download";
+import type { CoverageStore } from "./store.svelte";
+import type { JobContext } from "../device/progress";
+import type { SendAssembledMap } from "../device/write";
+import { formatBytes, truncateUtf8 } from "../format";
+import type { FlatStoreClient } from "../usb/client";
+import type { PutResponse } from "../usb/protocol";
+
+const KEEP_CELLS_KEY = "obcm.keepMapCells";
+
+function loadKeepCells(): boolean {
+ try {
+ return globalThis.localStorage?.getItem(KEEP_CELLS_KEY) === "true";
+ } catch {
+ return false;
+ }
+}
+
+/** The engine's sort budget, which after the external merge **is** the wasm engine term. A
+ * chosen value: big enough that a DACH-scale sort is about a dozen runs, small enough that
+ * engine plus caches plus terrain stays a fraction of a tab's budget. Passed to both the
+ * assembly and the estimate, so the projection prices the run that will actually happen. */
+const SORT_BUDGET_BYTES = 256 * 1024 * 1024;
+
+/** A phone's tab gets nowhere near a desktop's 3 GiB before the browser
+ * evicts the page — and eviction loses the download with no error to
+ * show. 1 GiB is the bridge test's own phone-shaped judgement. */
+const isMobileUa = typeof navigator !== "undefined" && /Android|iPhone|iPad|Mobile/i.test(navigator.userAgent);
+const MOBILE_BUDGET = 1024 ** 3;
+
+/** Milliseconds from each phase's start to the next phase's start, in phase order. */
+function phaseDurations(starts: Partial>): Partial> {
+ const seen = ASSEMBLE_PHASES.filter((p) => starts[p] !== undefined);
+ const out: Partial> = {};
+ for (let i = 0; i + 1 < seen.length; i++) {
+ out[seen[i]] = Math.round(starts[seen[i + 1]]! - starts[seen[i]]!);
+ }
+ return out;
+}
+
+export type Phase =
+ | "idle"
+ | "downloading"
+ | "assembling"
+ | "saving"
+ | "finalizing"
+ | "done"
+ | "cancelled"
+ | "error";
+
+interface DeviceOutput {
+ readonly kind: "device";
+ readonly client: FlatStoreClient;
+ readonly ctx: JobContext;
+ readonly resolve: (result: PutResponse) => void;
+ readonly reject: (cause: unknown) => void;
+ removeAbort: () => void;
+ result: PutResponse | null;
+ settled: boolean;
+ failing: boolean;
+ runId: number | null;
+ transientCellRevision: string | null;
+ releaseWork: (() => void) | null;
+ readonly operations: Set>;
+}
+interface DownloadOutput {
+ readonly kind: "download";
+ runId: number | null;
+ transientCellRevision: string | null;
+ releaseWork: (() => void) | null;
+ readonly operations: Set>;
+}
+type Output = DownloadOutput | DeviceOutput;
+
+/**
+ * The same plan minus every cell already in the store, and the tally of what that saved.
+ *
+ * A cell is "already here" when a file named by its catalog digest exists at the catalog's
+ * length. The name **is** the SHA-256 `fetchVerified` matched before the file was written, and
+ * the length catches a write torn by a crash or a quota refusal. Re-hashing every cell on every
+ * run would cost seconds and a full read of exactly the bytes this exists to stop reading.
+ *
+ * Terrain is never skipped: it is not in the store.
+ */
+interface CachedPlan {
+ plan: CellDownloadPlan;
+ cells: number;
+ bytes: number;
+}
+
+async function scanCached(
+ plan: CellDownloadPlan,
+ cells: CellInventory,
+ runOp: (operation: () => Promise) => Promise = (operation) => operation(),
+): Promise {
+ const wanted: typeof plan.items = [];
+ let bytes = 0;
+ let have = 0;
+ let haveBytes = 0;
+ for (const item of plan.items) {
+ const present = item.band !== null && (await runOp(() => cells.has(item.cell.sha256, item.cell.bytes)));
+ if (present) {
+ have += 1;
+ haveBytes += item.cell.bytes;
+ continue;
+ }
+ wanted.push(item);
+ bytes += item.cell.bytes;
+ }
+ return {
+ plan: { ...plan, items: wanted, totalBytes: bytes },
+ cells: have,
+ bytes: haveBytes,
+ };
+}
+
+/** The build of one map from a coverage store. Call `start()` once, and `destroy()` when the
+ * owner goes away. */
+export class MapRun {
+ readonly #store: CoverageStore;
+ readonly #ledger = $derived.by(() => this.#store.ledger);
+
+ #worker: Worker | null = null;
+ #destroyed = false;
+ /** Ends the wait of `start()` for the map-work directories when this run is destroyed. */
+ readonly #startWait = new AbortController();
+
+ #phase = $state("idle");
+ #dlProgress = $state(null);
+ #asmPhase = $state("open");
+ #asmFraction = $state(0);
+ /** When each assembly phase began, for the run's debug ledger. */
+ #asmPhaseStart: Partial> = {};
+ /** The map, once there is one: what it is called and how big it is. */
+ #savedFile = $state<{ name: string; byteLength: number } | null>(null);
+ /** Whether the file actually reached the disk. Not `savedFile !== null`: it is
+ * set the moment the map is delivered, and a cancel that raced the delivery
+ * must not tell someone to go and discard a file nobody has. */
+ #persisted = $state(false);
+ /** The one delivery, so `done` can wait for a save/send that is still running rather
+ * than declare the map finished behind it. */
+ #delivery: Promise = Promise.resolve();
+ /** Set by `failRun`: a delivery that has not started must not write into an
+ * output that is being discarded. */
+ #sinkClosed = false;
+ /** How this run's cells reached the assembler, as the worker reports it before the assembly
+ * starts. Shown, because a bug report about a failed country-scale run has to say which. */
+ #readMode = $state(null);
+ /** …and where its map went, for the same reason. */
+ #writeMode = $state(null);
+ /** Cells this run did not have to fetch, because a previous one already put
+ * them in OPFS under the same digest. */
+ #cachedCells = $state(0);
+ #cachedBytes = $state(0);
+ /** Opt-in reuse. OPFS may still be the active run's necessary working disk when false. */
+ #keepCells = $state(loadKeepCells());
+ // Starts true so the first readiness cannot briefly enable a run before
+ // `start()` maintenance has joined the origin-global map-work barrier.
+ #clearingCells = $state(true);
+ #cellStorageNotice = $state(null);
+ #runWarnings = $state([]);
+ #errorMessage = $state(null);
+ #abortCtl: AbortController | null = null;
+ /** The name this run's file will be saved under, fixed when the run starts, so editing the
+ * selection mid-download cannot rename the map that is already being built from the old one. */
+ #runFileName = $state("OBC map.obcm");
+
+ #output = $state.raw(null);
+ #lastRunKind = $state("download");
+ #nextRunId = 0;
+ #activeRunId = 0;
+ #failure: Promise = Promise.resolve();
+ #paused = $state(false);
+
+ #estimate = $state(null);
+ #estimateLedger = $state.raw(null);
+ #estimateOnDisk = false;
+ #estimateGeneration = 0;
+ #estimatePending = $state(false);
+ /** The estimate's own failure channel, never mixed into the run's. Cleared by the next
+ * request; retried by bumping the nonce. */
+ #estimateError = $state(null);
+ #estimateNonce = $state(0);
+ readonly #disposeEstimate: () => void;
+
+ constructor(store: CoverageStore) {
+ this.#store = store;
+ this.#disposeEstimate = $effect.root(() => {
+ $effect(() => this.#estimateEffect());
+ });
+ }
+
+ get phase(): Phase { return this.#phase; }
+ get dlProgress(): CellDownloadProgress | null { return this.#dlProgress; }
+ get asmPhase(): AssemblePhase { return this.#asmPhase; }
+ get asmFraction(): number { return this.#asmFraction; }
+ get savedFile(): { name: string; byteLength: number } | null { return this.#savedFile; }
+ get persisted(): boolean { return this.#persisted; }
+ get readMode(): CellReadMode | null { return this.#readMode; }
+ get writeMode(): MapWriteMode | null { return this.#writeMode; }
+ get cachedCells(): number { return this.#cachedCells; }
+ get cachedBytes(): number { return this.#cachedBytes; }
+ get keepCells(): boolean { return this.#keepCells; }
+ get clearingCells(): boolean { return this.#clearingCells; }
+ get cellStorageNotice(): string | null { return this.#cellStorageNotice; }
+ get runWarnings(): string[] { return this.#runWarnings; }
+ get errorMessage(): string | null { return this.#errorMessage; }
+ get runFileName(): string { return this.#runFileName; }
+ get lastRunKind(): Output["kind"] { return this.#lastRunKind; }
+ get sendingToDevice(): boolean { return this.#output?.kind === "device"; }
+ get estimateError(): string | null { return this.#estimateError; }
+ get refreshBlocked(): boolean { return this.#refreshBlocked; }
+ get memoryCaution(): string | null { return this.#memoryCaution; }
+ get running(): boolean { return this.#running; }
+ get refusal(): string | null { return this.#refusal; }
+ get ready(): boolean { return this.#ready; }
+
+ #ensureWorker(): Worker {
+ if (!this.#worker) {
+ this.#worker = new Worker(new URL("../assemble/assemble.worker.ts", import.meta.url), {
+ type: "module",
+ });
+ const current = this.#worker;
+ this.#worker.onmessage = (event) => {
+ if (this.#worker === current) void this.#onWorkerMessage(event);
+ };
+ // The worker's own code answers every failure with an `error` message;
+ // these two fire for what that code never sees — the script failing to
+ // boot at all, and a message that could not be deserialized. Both arrive
+ // as the protocol's `{code: "internal"}` shape, and the worker is dropped,
+ // because one that could not boot stays broken.
+ this.#worker.onerror = (e) => {
+ if (this.#worker !== current) return;
+ this.#workerFailed(e.message || "the assembly worker failed to start");
+ };
+ this.#worker.onmessageerror = () => {
+ if (this.#worker !== current) return;
+ this.#workerFailed("a message to the assembly worker could not be delivered");
+ };
+ }
+ return this.#worker;
+ }
+
+ /** A worker-level failure, routed like a posted `error`. */
+ #workerFailed(message: string) {
+ this.#worker?.terminate();
+ this.#worker = null;
+ void this.#onWorkerMessage(
+ new MessageEvent("message", { data: { type: "error", code: "internal", message } }),
+ );
+ }
+
+ destroy(): void {
+ this.#destroyed = true;
+ const cause = new DOMException("the map builder was closed", "AbortError");
+ this.#startWait.abort(cause);
+ // Finalization starts only after the map is durable and its abort listener has been
+ // detached. Let that owner finish its cleanup. Every earlier teardown goes through the
+ // same barrier-owning failure path; independent close/discard calls here could race the
+ // owner's outstanding put or a newly started run.
+ if (this.#phase !== "finalizing") {
+ // Direct delivery is cancelled through the DeviceJob so the same signal reaches the
+ // in-flight PUT; its one abort listener enters failRun. Browser delivery has
+ // no outer controller, so it enters that owner path directly.
+ if (this.#output?.kind === "device" && !this.#output.settled) this.#output.ctx.cancel(cause);
+ else void this.#failRun(cause);
+ }
+ // With no run owner, the worker only serves the background estimate and can be dropped
+ // immediately. A finalizing owner still needs it to finish its `done` continuation, so
+ // that path terminates below only after cleanup and settlement.
+ if (!this.#output) {
+ this.#worker?.terminate();
+ this.#worker = null;
+ }
+ this.#disposeEstimate();
+ }
+
+ start(): void {
+ void this.#initializeStorage();
+ }
+
+ async #onWorkerMessage(e: MessageEvent) {
+ const msg = e.data as unknown;
+ if (!isWorkerResponse(msg)) {
+ // A message this protocol does not speak is droppable. A malformed `done` is not:
+ // it is the run's only ending, so dropping it leaves the screen waiting for a
+ // result that will never come again.
+ if (typeof msg === "object" && msg !== null && (msg as { type?: unknown }).type === "done") {
+ await this.#failRun(new Error("The assembly finished with a result this build cannot read."));
+ }
+ return;
+ }
+ switch (msg.type) {
+ case "estimate-result":
+ if (msg.estimateId !== this.#estimateGeneration || this.#estimateLedger !== this.#ledger) return;
+ this.#estimateOnDisk = msg.onDisk;
+ this.#estimate = msg.estimate;
+ this.#estimatePending = false;
+ this.#estimateError = null;
+ break;
+ case "progress":
+ this.#asmPhaseStart[msg.phase] ??= performance.now();
+ this.#asmPhase = msg.phase;
+ this.#asmFraction = msg.fraction;
+ break;
+ case "reading":
+ this.#readMode = msg.mode;
+ break;
+ case "writing":
+ this.#writeMode = msg.mode;
+ break;
+ case "stored-map":
+ // The map never crossed the port: it is in OPFS, the worker has
+ // let go of it, and this is where it becomes a file someone has.
+ // The phase moves before the delivery is assigned, because a
+ // ~9 GiB write outlives this handler and Cancel must dispatch on
+ // the right phase.
+ this.#phase = "saving";
+ this.#delivery = this.#deliverStoredMap(msg.byteLength);
+ void this.#delivery.catch(() => {});
+ break;
+ case "file":
+ // No sink was available, so the bytes came across instead. Same
+ // delivery, but direct device delivery keeps the worker's transferred
+ // buffer as its sole resident copy instead of snapshotting it into a Blob.
+ this.#phase = "saving";
+ this.#delivery = this.#output?.kind === "device"
+ ? this.#deliverResidentMap(msg.bytes, msg.byteLength)
+ : this.#deliverMap(new Blob([msg.bytes as unknown as BlobPart]), msg.byteLength);
+ void this.#delivery.catch(() => {});
+ break;
+ case "done":
+ // The run's ledger: OPFS traffic, the time each phase took and the linear
+ // memory the assembly ended on. For anyone profiling an assembly from
+ // DevTools — a worker's own console does not surface — and the only place
+ // these numbers are readable from outside the worker. Nothing on screen
+ // reads them.
+ console.debug("[assemble] run", {
+ wasmMemoryBytes: msg.wasmMemoryBytes,
+ io: msg.io,
+ phaseMs: phaseDurations(this.#asmPhaseStart),
+ });
+ this.#runWarnings = msg.warnings;
+ try {
+ await this.#delivery;
+ // A direct PUT is durable now. Detach its abort listener synchronously:
+ // cancellation after commit must not race `failRun` against host-side
+ // cleanup and turn success into "cancelled".
+ if (!this.#sinkClosed && this.#output?.kind === "device") {
+ this.#output.removeAbort();
+ this.#output.ctx.phase("finalizing");
+ this.#phase = "finalizing";
+ }
+ } catch (cause) {
+ await this.#failRun(cause);
+ break;
+ }
+ // A cancel that arrived *during* the save has already discarded the
+ // output and set the phase — `failRun` awaits this same delivery, so
+ // both paths resume here. Without this guard a discarded map could
+ // report "done". `sinkClosed` settles it, because it is set before
+ // the discard rather than after it.
+ if (this.#sinkClosed) break;
+ // Cleanup can recursively remove a country-sized temporary cell store. Keep the
+ // run closed while that awaits: declaring `done` here briefly re-enabled both
+ // delivery actions, and the older continuation could then clear a newer run's
+ // shared `output` after its cleanup finished.
+ this.#phase = "finalizing";
+ await this.#cleanupTransientCells();
+ if (this.#output?.kind === "device") {
+ if (!this.#output.result) {
+ await this.#failRun(new Error("The device did not commit the assembled map."));
+ break;
+ }
+ await this.#cleanupDirectOutput();
+ this.#settleDevice(this.#output.result);
+ }
+ this.#output?.releaseWork?.();
+ if (this.#output) this.#output.releaseWork = null;
+ this.#output = null;
+ this.#abortCtl = null;
+ this.#activeRunId = 0;
+ this.#phase = "done";
+ if (this.#destroyed) {
+ this.#worker?.terminate();
+ this.#worker = null;
+ }
+ break;
+ case "error":
+ if (
+ msg.estimateId !== undefined &&
+ (msg.estimateId !== this.#estimateGeneration || this.#estimateLedger !== this.#ledger)
+ ) return;
+ // Two conversations share this worker, and their failures are
+ // different facts: an error during a run belongs to the run, but an
+ // error answering the background *estimate* must not paint the screen
+ // with "Nothing was saved" about a download that never started.
+ if (this.#phase === "assembling" || this.#phase === "saving") {
+ await this.#failRun(new Error(msg.message));
+ } else {
+ this.#estimateError = msg.message;
+ }
+ this.#estimatePending = false;
+ break;
+ }
+ }
+
+ /**
+ * The map the assembly wrote into OPFS: its bytes were never in wasm memory and never crossed
+ * the worker port, and on the browser host they never enter the tab's heap either — a `Blob` on
+ * an OPFS file is a handle, and that is what the save is given.
+ */
+ async #deliverStoredMap(byteLength: number) {
+ const blob = await readMapOutput();
+ if (blob.size !== byteLength) {
+ throw new Error(
+ `The assembled map is ${blob.size} bytes in this browser's storage, not the ${byteLength} the ` +
+ `assembler wrote. Free some disk space and try again.`,
+ );
+ }
+ await this.#deliverMap(blob, byteLength);
+ }
+
+ /** Deliver the explicitly memory-priced fallback without creating a second full-map Blob. */
+ async #deliverResidentMap(bytes: Uint8Array, byteLength: number) {
+ if (this.#sinkClosed) return;
+ if (bytes.byteLength !== byteLength) {
+ throw new Error(
+ `The assembler announced ${byteLength} bytes but delivered ${bytes.byteLength}; the map was not sent.`,
+ );
+ }
+ if (this.#output?.kind !== "device") throw new Error("The direct map destination was closed.");
+ const { sendMapBytes } = await import("../device/write");
+ this.#output.result = await sendMapBytes(this.#output.client, bytes, this.#runFileName, this.#output.ctx);
+ }
+
+ /** Deliver the verified one-file result without ever materialising an OPFS
+ * map in the tab heap. Device PUT reads the Blob twice in bounded slices
+ * (CRC then transfer); browser download hands the same Blob to the browser. */
+ async #deliverMap(blob: Blob, byteLength: number) {
+ if (this.#sinkClosed) return;
+ if (blob.size !== byteLength) {
+ throw new Error(
+ `The assembler announced ${byteLength} bytes but delivered ${blob.size}; the map was not sent.`,
+ );
+ }
+ const name = this.#runFileName;
+ if (this.#output?.kind === "device") {
+ const { sendMapBlob } = await import("../device/write");
+ this.#output.result = await sendMapBlob(this.#output.client, blob, name, this.#output.ctx);
+ } else {
+ // No picker here: one file, one ordinary download, one prompt.
+ saveBlob(blob, name);
+ this.#savedFile = { name, byteLength };
+ }
+ if (this.#output?.kind !== "device") this.#persisted = true;
+ }
+
+ #settleDevice(result: PutResponse | unknown, failed = false) {
+ const current = this.#output;
+ if (current?.kind !== "device" || current.settled) return;
+ current.settled = true;
+ current.removeAbort();
+ if (failed) current.reject(result);
+ else current.resolve(result as PutResponse);
+ }
+
+ async #cleanupTransientCells(owner: Output | null = this.#output) {
+ const revision = owner?.transientCellRevision ?? null;
+ if (owner) owner.transientCellRevision = null;
+ if (!revision) return;
+ try {
+ await discardCellStore(revision);
+ } catch {
+ this.#runWarnings = [
+ ...this.#runWarnings,
+ "Temporary map cells could not be deleted; use ‘Delete stored map data’.",
+ ];
+ }
+ }
+
+ async #cleanupDirectOutput() {
+ try {
+ await discardMapOutput();
+ } catch {
+ this.#runWarnings = [
+ ...this.#runWarnings,
+ "The temporary assembled map could not be deleted; use ‘Delete stored map data’.",
+ ];
+ }
+ }
+
+ async setKeepCells(checked: boolean): Promise {
+ this.#keepCells = checked;
+ this.#cellStorageNotice = null;
+ try {
+ globalThis.localStorage?.setItem(KEEP_CELLS_KEY, String(checked));
+ } catch {
+ // The choice still applies to this page; denied storage means it resets to off later.
+ }
+ if (!checked && !this.#running) await this.clearStoredCells(true);
+ }
+
+ async #initializeStorage() {
+ let release: (() => void) | undefined;
+ try {
+ release = await acquireMapWorkStorage(this.#startWait.signal);
+ if (this.#destroyed) return;
+ if (!this.#keepCells) await clearMapWorkStorage();
+ } catch {
+ // Startup maintenance is best-effort, as it was before serialization. A later run's
+ // own probes give the actionable storage error.
+ } finally {
+ release?.();
+ if (!this.#destroyed) this.#clearingCells = false;
+ }
+ }
+
+ async clearStoredCells(announce = true): Promise {
+ this.#clearingCells = true;
+ if (announce) this.#cellStorageNotice = null;
+ const release = await acquireMapWorkStorage();
+ try {
+ await clearMapWorkStorage();
+ if (announce) this.#cellStorageNotice = "Stored map downloads deleted.";
+ } catch {
+ if (announce) {
+ this.#cellStorageNotice =
+ "Stored map downloads could not be deleted. Close other builder tabs and try again.";
+ }
+ } finally {
+ release();
+ this.#clearingCells = false;
+ }
+ }
+
+ #failRun(cause: unknown, runId = this.#activeRunId): Promise {
+ if (runId === 0 || this.#activeRunId !== runId || this.#output?.runId !== runId) return this.#failure;
+ this.#failure = this.#failRunOwned(cause, runId);
+ return this.#failure;
+ }
+
+ async #failRunOwned(cause: unknown, runId: number) {
+ // A cancelled preflight may resume after an unabortable OPFS call. Its
+ // continuation no longer owns any shared run state and must be a no-op.
+ const owner = this.#output;
+ if (runId === 0 || this.#activeRunId !== runId || owner?.runId !== runId) return;
+ const direct = owner.kind === "device";
+ if (owner.kind === "device") {
+ if (owner.failing || owner.settled) return;
+ owner.failing = true;
+ }
+ this.#activeRunId = 0;
+ const controller = this.#abortCtl;
+ this.#abortCtl = null;
+ controller?.abort();
+ this.#worker?.terminate();
+ this.#worker = null;
+ // Close the logical sink before the first await. A PUT can finish on the same microtask
+ // turn as cancellation; its `done` handler must already know that failure teardown won.
+ this.#sinkClosed = true;
+ // `clearCellStores`, OPFS probes/opens and cell writes cannot be interrupted. Keep the
+ // surface in its running state until every operation owned by this run has physically
+ // returned; only then may cleanup run and the next map action become available.
+ await waitForRunOperations(owner);
+ // A delivery that has not begun is now a no-op, but one may already be in
+ // flight — let it land before cleanup. It is bounded by one file's write.
+ const deliveryCause = await this.#delivery.then(
+ () => null,
+ (error: unknown) => error,
+ );
+ // Teardown cancellation can arrive while the physical link rejection is already
+ // unwinding. Preserve that stable cause so the DeviceJob can surface interruption.
+ if ((deliveryCause as { code?: unknown } | null)?.code === "link") cause = deliveryCause;
+ const cancelled = cause instanceof DOMException && cause.name === "AbortError";
+ await this.#cleanupTransientCells(owner);
+ if (direct) await this.#cleanupDirectOutput();
+ owner.releaseWork?.();
+ owner.releaseWork = null;
+ this.#errorMessage = cause instanceof Error ? cause.message : String(cause);
+ this.#phase = cancelled ? "cancelled" : "error";
+ this.#settleDevice(cause, true);
+ this.#output = null;
+ }
+
+ #assertRunActive(runId: number, out: Output, controller: AbortController) {
+ if (
+ this.#activeRunId !== runId ||
+ this.#output !== out ||
+ this.#abortCtl !== controller ||
+ controller.signal.aborted
+ ) {
+ throw controller.signal.reason ?? new DOMException("the map run is no longer active", "AbortError");
+ }
+ }
+
+ async #runOperation(
+ runId: number,
+ out: Output,
+ controller: AbortController,
+ operation: () => Promise,
+ onStale?: (value: T) => Promise,
+ ): Promise {
+ this.#assertRunActive(runId, out, controller);
+ let tracked!: Promise;
+ tracked = (async () => {
+ try {
+ const value = await operation();
+ try {
+ this.#assertRunActive(runId, out, controller);
+ } catch (cause) {
+ // Some operations create an artifact before cancellation can be observed.
+ // Their caller owns the value/revision needed to remove it, and that cleanup
+ // remains inside this tracked promise so failRun's barrier includes it.
+ await onStale?.(value);
+ throw cause;
+ }
+ return value;
+ } finally {
+ out.operations.delete(tracked);
+ }
+ })();
+ out.operations.add(tracked);
+ return tracked;
+ }
+
+ /** What the selection is called in the file and on the device. */
+ #mapName(): string {
+ const parts = this.#store.selection.parts;
+ const base = parts.length === 0 ? "OBC map" : parts[0].name;
+ const name = parts.length > 1 ? `${base} +${parts.length - 1}` : base;
+ return truncateUtf8(name, 48);
+ }
+
+ /**
+ * The map's filename. **JS owns this**: the assembler names nothing — what crosses its seam is
+ * a digest and a length — so the name is chosen here, where the selection is known. `.obcm`
+ * because that is what a map is, and what this app's own file picker accepts. What an OS
+ * forbids in a name becomes a dash.
+ */
+ #mapFileName(): string {
+ const stem = this.#mapName().replace(/[\\/:*?"<>|]/g, "-").trim();
+ return `${stem.length > 0 ? stem : "OBC map"}.obcm`;
+ }
+
+ async #begin(out: Output) {
+ const store = this.#store;
+ const resolution = store.resolution;
+ const indices = store.indices;
+ const l = this.#ledger;
+ if (!resolution || !indices || !l || !this.#ready || !this.#estimate?.fits) {
+ throw new Error("This map is not ready to assemble yet.");
+ }
+ const admittedEstimate = this.#estimate;
+ const admissionId = this.#estimateGeneration;
+ const requireDisk = this.#estimateOnDisk;
+ if (this.#destroyed) throw new DOMException("the map builder was closed", "AbortError");
+ if (this.#estimateGeneration !== admissionId || this.#estimate !== admittedEstimate || !this.#ready) {
+ throw new Error("The map selection changed. Wait for its memory check before trying again.");
+ }
+ const runId = ++this.#nextRunId;
+ out.runId = runId;
+ this.#activeRunId = runId;
+ this.#output = out;
+ this.#lastRunKind = out.kind;
+ this.#runFileName = this.#mapFileName();
+ this.#errorMessage = null;
+ this.#savedFile = null;
+ this.#persisted = false;
+ this.#delivery = Promise.resolve();
+ this.#sinkClosed = false;
+ this.#runWarnings = [];
+ this.#dlProgress = null;
+ this.#asmFraction = 0;
+ this.#readMode = null;
+ this.#writeMode = null;
+ this.#cachedCells = 0;
+ this.#cachedBytes = 0;
+ this.#phase = "downloading";
+ if (out.kind === "device") out.ctx.phase("downloading", l.totalBytes);
+
+ const plan = planCells(resolution, store.catalog, indices, store.terrain, store.articles);
+ const cells: WorkerCell[] = [];
+ const sourceCells: WorkerSourceCell[] = [];
+ const terrainCells: WorkerTerrainCell[] = [];
+ const articles = { landmarks: [] as Uint8Array[], peaks: [] as Uint8Array[] };
+ const runAbort = new AbortController();
+ this.#abortCtl = runAbort;
+ const assertActive = () => this.#assertRunActive(runId, out, runAbort);
+ const runOp = (operation: () => Promise, onStale?: (value: T) => Promise) =>
+ this.#runOperation(runId, out, runAbort, operation, onStale);
+
+ // Readiness only covers this instance. The lease also waits for an older,
+ // already-destroyed instance's put/finalization before this run touches shared OPFS.
+ out.releaseWork = await runOp(() => acquireMapWorkStorage(runAbort.signal), async (release) => release());
+
+ // Cells go to disk when this browser will take them, which keeps a country's
+ // worth out of the tab's heap, and with the opt-in above a later build can
+ // reuse them. The raster deliberately does not: its objects are small and it
+ // is downloaded last. Probed by writing and reading a file back, not by
+ // sniffing for a method: a store that cannot be written to is worse than none.
+ const revision = cellStoreRevision(store.catalog);
+ // Unchecked means no reuse in either direction. OPFS still carries this run when available,
+ // because that working disk is what makes country-sized assembly possible.
+ if (!this.#keepCells) {
+ await runOp(clearCellStores);
+ }
+ const writable = await runOp(cellStoreWritable);
+ out.transientCellRevision = writable && !this.#keepCells ? revision : null;
+ let cellStore = writable
+ ? await runOp(
+ () => openCellStore(revision),
+ async () => {
+ if (!out.transientCellRevision) return;
+ try {
+ await discardCellStore(out.transientCellRevision);
+ out.transientCellRevision = null;
+ } catch {
+ // failRun owns the same revision and retries after this barrier drains.
+ }
+ },
+ )
+ : null;
+ if (!cellStore) out.transientCellRevision = null;
+ let fetchPlan = plan;
+ if (cellStore) {
+ const cached = await scanCached(plan, cellStore, runOp);
+ fetchPlan = cached.plan;
+ this.#cachedCells = cached.cells;
+ this.#cachedBytes = cached.bytes;
+ // Asked once, before a byte is fetched, and about the WHOLE run — cells, the
+ // map the sink writes, the merge's spill — because all three live in OPFS: a
+ // store with room for the cells but not the output would fail at the first
+ // write, after the download.
+ const reclaimable = await runOp(reclaimableAssemblyBytes);
+ const hasRoom = await runOp(() => hasRoomFor(projectedRunDiskBytes(l, this.#cachedBytes), reclaimable));
+ if (!hasRoom) {
+ cellStore = null;
+ fetchPlan = plan;
+ this.#cachedCells = 0;
+ this.#cachedBytes = 0;
+ } else {
+ // Only an admitted run replaces the previous temporary output. A refused run leaves
+ // it alone, and accepted work reclaims the bytes before the first download.
+ await runOp(clearAssemblyStorage);
+ }
+ }
+
+ if (requireDisk && !cellStore) {
+ throw new Error("The storage required for this map is no longer available. Retry the memory check.");
+ }
+
+ try {
+ await runOp(() =>
+ downloadCells(fetchPlan, {
+ fetchImpl: store.client.fetchImpl,
+ onCell: async (item, bytes) => {
+ if (item.article) {
+ articles[item.article].push(bytes);
+ } else if (item.band === null) {
+ terrainCells.push({ id: item.cell.id, sha256: item.cell.sha256, bytes });
+ } else if (cellStore) {
+ // Verified once, on the way in: the file's name is the digest
+ // `fetchVerified` just checked. Awaited, so a slow disk applies
+ // backpressure instead of letting gigabytes queue behind it.
+ await runOp(() =>
+ cellStore.put(item.cell.sha256, bytes).catch((cause: unknown) => {
+ if (isStorageQuotaError(cause)) throw new Error(STORAGE_QUOTA_MESSAGE);
+ throw new Error(
+ `The map could not be written to this browser's storage (${
+ cause instanceof Error ? cause.message : String(cause)
+ }).`,
+ );
+ }),
+ );
+ } else {
+ cells.push({
+ id: item.cell.id,
+ band: item.band,
+ partial: "partial" in item.cell && item.cell.partial,
+ bytes,
+ });
+ }
+ },
+ onProgress: (p) => {
+ this.#dlProgress = p;
+ if (out.kind === "device") out.ctx.progress(p.receivedBytes, p.totalBytes);
+ },
+ signal: runAbort.signal,
+ }),
+ );
+ // In the plan's order, not the network's — cached and fetched cells
+ // are one list, and which of the two a cell came from must not be
+ // able to reach the bytes.
+ if (cellStore) {
+ for (const item of plan.items) {
+ if (item.band === null) continue;
+ sourceCells.push({
+ id: item.cell.id,
+ band: item.band,
+ partial: "partial" in item.cell && item.cell.partial,
+ byteLength: item.cell.bytes,
+ key: item.cell.sha256,
+ });
+ }
+ }
+ } catch (e) {
+ await this.#failRun(e, runId);
+ return;
+ }
+
+ this.#phase = "assembling";
+ if (out.kind === "device") out.ctx.phase("assembling", 0);
+ this.#asmPhase = "open";
+ this.#asmPhaseStart = { open: performance.now() };
+ const req: AssembleWorkerRequest = {
+ type: "assemble",
+ requireDisk,
+ cells,
+ // One or the other, never a mix: `cells` carries buffers when there was
+ // nowhere to put them, `sourceCells` names files in OPFS when there was.
+ // The worker decides how it reads the latter.
+ sourceCells: cellStore ? sourceCells : undefined,
+ cellStore: cellStore?.revision,
+ knownEmpty: plan.knownEmpty,
+ // Terrain travels as its own pair: the lattice the catalog states and the
+ // objects that were downloaded. A catalog with no terrain block sends
+ // neither, and the map is written with an empty terrain region.
+ terrain: store.terrain
+ ? { postingLog2: store.terrain.posting_log2, cellLog2: store.terrain.cell_log2 }
+ : undefined,
+ terrainCells: store.terrain ? terrainCells : undefined,
+ articles,
+ schemaJson: store.rootBody,
+ lightSkinJson: JSON.stringify(store.lightSkin),
+ darkSkinJson: JSON.stringify(store.darkSkin),
+ options: {
+ // The same budget the estimate was given, so the projection prices
+ // the run that actually happens rather than the engine's default.
+ mergeBudgetBytes: SORT_BUDGET_BYTES,
+ // Both were shown before this button unlocked. `acceptHoles` is derived
+ // from the *shown* set, not the ledger's raw count, so the assembly is
+ // never told to accept a hole the UI kept to itself. Partial cells exist
+ // in essentially every real map.
+ acceptHoles: store.holeCells().length > 0,
+ acceptPartial: true,
+ },
+ };
+ assertActive();
+ this.#ensureWorker().postMessage(req, { transfer: requestTransferList(req) });
+ }
+
+ download(): void {
+ const out: DownloadOutput = {
+ kind: "download",
+ runId: null,
+ transientCellRevision: null,
+ releaseWork: null,
+ operations: new Set(),
+ };
+ void this.#begin(out).catch((cause) => this.#failRun(cause, out.runId ?? 0));
+ }
+
+ /** Assemble this selection and stream its verified `.obcm` directly into
+ * the connected device's v4 flat-store PUT. The Blob is OPFS-backed when
+ * this host passed the writable-storage probe, and memory-priced otherwise. */
+ readonly sendToDevice: SendAssembledMap = (client, ctx) =>
+ new Promise((resolve, reject) => {
+ const onAbort = () =>
+ void this.#failRun(
+ ctx.signal.reason ?? new DOMException("cancelled", "AbortError"),
+ device.runId ?? 0,
+ );
+ const device: DeviceOutput = {
+ kind: "device",
+ client,
+ ctx,
+ resolve,
+ reject,
+ removeAbort: () => ctx.signal.removeEventListener("abort", onAbort),
+ result: null,
+ settled: false,
+ failing: false,
+ runId: null,
+ transientCellRevision: null,
+ releaseWork: null,
+ operations: new Set(),
+ };
+ ctx.signal.addEventListener("abort", onAbort, { once: true });
+ if (ctx.signal.aborted) {
+ device.removeAbort();
+ reject(ctx.signal.reason);
+ return;
+ }
+ void this.#begin(device).catch((cause) => {
+ if (this.#output === device) void this.#failRun(cause, device.runId ?? 0);
+ else {
+ device.removeAbort();
+ reject(cause);
+ }
+ });
+ });
+
+ readonly #refreshBlocked = $derived(this.#output?.kind === "device" || this.#phase === "finalizing");
+
+ /** Quiesce this catalog before a replacement can admit another assembly. */
+ async pauseForRefresh(): Promise<() => void> {
+ if (this.#refreshBlocked) throw new Error("Wait for the map send or cleanup to finish before refreshing.");
+ this.#paused = true;
+ this.#estimateGeneration += 1;
+ await this.#failRun(new DOMException("the map catalog is being refreshed", "AbortError"));
+ this.#worker?.terminate();
+ this.#worker = null;
+ return () => { this.#paused = false; };
+ }
+
+ cancel(): void {
+ const cause = new DOMException("cancelled", "AbortError");
+ // Direct assembly and PUT are one DeviceJob. Ask its controller to
+ // cancel so both this button and TransferBar cancel the same signal;
+ // merely aborting the cell downloader would let a live PUT commit and
+ // only then paint the run as cancelled.
+ if (this.#output?.kind === "device") {
+ this.#output.ctx.cancel(cause);
+ return;
+ }
+ if (this.#phase === "downloading") {
+ this.#abortCtl?.abort(cause);
+ } else if (this.#phase === "assembling" || this.#phase === "saving") {
+ // The worker is blocked inside one synchronous wasm call and cannot read
+ // a message — terminate IS the cancel. Nothing usable is left behind: a
+ // partial `.obcm` fails its own header checks, and the file is only saved
+ // once the run says it finished.
+ void this.#failRun(cause);
+ }
+ }
+
+ retryEstimate(): void {
+ this.#estimateNonce += 1;
+ }
+
+ #estimateEffect() {
+ void this.#estimateNonce; // the retry button's lever
+ const l = this.#ledger;
+ const estimateId = ++this.#estimateGeneration;
+ this.#estimate = null;
+ this.#estimateLedger = null;
+ const phase = this.#phase;
+ const idle = phase === "idle" || phase === "done" || phase === "cancelled" || phase === "error";
+ if (!l || !l.isFinal || l.cellCount === 0 || !idle || this.#clearingCells || this.#paused) {
+ // Every exit clears the pending flag: a selection that empties or a run
+ // that starts must not leave "waiting for an estimate" latched with
+ // nothing left to answer it.
+ this.#estimate = null;
+ this.#estimatePending = false;
+ return;
+ }
+ const networkBandBytes = l.core.bytes;
+ const totalCellBytes = l.totalBytes;
+ // Both artifact classes stay resident even when map cells stream from disk.
+ const terrainBytes = (l.terrain?.bytes ?? 0) + (l.articleBytes ?? 0);
+ const reuseCells = this.#keepCells;
+ const store = this.#store;
+ const resolution = store.resolution;
+ const indices = store.indices;
+ const catalog = store.catalog;
+ const plan = reuseCells && resolution && indices
+ ? planCells(resolution, catalog, indices, store.terrain, store.articles)
+ : null;
+ const revision = cellStoreRevision(catalog);
+ this.#estimatePending = true;
+ this.#estimateError = null;
+ // Debounced: a slider mid-drag changes the figures every frame, and the
+ // projection only matters once the selection settles.
+ const timer = setTimeout(() => {
+ // The main thread's half of both residency escapes, decided by the same
+ // two checks `begin` runs before a byte is fetched: a store this browser
+ // will write, with room for the WHOLE run. The worker ANDs in its own
+ // sync-handle probe.
+ void (async () => {
+ const writable = await cellStoreWritable();
+ let storedCellBytes = 0;
+ if (writable && plan) {
+ const cells = await openCellInventory(revision);
+ if (cells) storedCellBytes = (await scanCached(plan, cells)).bytes;
+ }
+ const reclaimable = writable ? await reclaimableAssemblyBytes() : 0;
+ const diskNeed = projectedRunDiskBytes(l, storedCellBytes);
+ const onDisk = writable && (await hasRoomFor(diskNeed, reclaimable));
+ if (this.#destroyed || estimateId !== this.#estimateGeneration || l !== this.#ledger) return;
+ this.#estimateLedger = l;
+ this.#ensureWorker().postMessage({
+ type: "estimate",
+ estimateId,
+ networkBandBytes,
+ totalCellBytes,
+ terrainBytes,
+ onDisk,
+ mergeBudgetBytes: SORT_BUDGET_BYTES,
+ budgetBytes: isMobileUa ? MOBILE_BUDGET : undefined,
+ } satisfies AssembleWorkerRequest);
+ })();
+ }, 500);
+ return () => {
+ clearTimeout(timer);
+ if (estimateId === this.#estimateGeneration) this.#estimateGeneration += 1;
+ };
+ }
+
+ readonly #memoryRefusal = $derived.by(() => {
+ const estimate = this.#estimate;
+ if (!estimate || estimate.fits) return null;
+ return (
+ `Assembling this selection needs about ${formatBytes(estimate.peakBytes)} of browser memory — more than ` +
+ `${isMobileUa ? "a phone's tab" : "a browser tab"} can be trusted with ` +
+ // A card carries **one** map, because the device has no way to choose
+ // between two. So "split it in two" is not a remedy that exists here,
+ // and the only honest instruction is to cover less ground.
+ `(${formatBytes(estimate.budgetBytes)}). Reduce the map selection.`
+ );
+ });
+
+ readonly #memoryCaution = $derived.by(() => {
+ const estimate = this.#estimate;
+ if (!estimate || !estimate.fits) return null;
+ if (estimate.headroomBytes >= estimate.budgetBytes * 0.15) return null;
+ return (
+ `Close to the browser's memory budget: about ${formatBytes(estimate.peakBytes)} projected of ` +
+ `${formatBytes(estimate.budgetBytes)}. It will probably assemble; a smaller area is the sure thing.`
+ );
+ });
+
+ readonly #running = $derived(
+ this.#phase === "downloading" || this.#phase === "assembling" || this.#phase === "saving" || this.#phase === "finalizing",
+ );
+ readonly #refusal = $derived.by(() => {
+ const l = this.#ledger;
+ if (!l || l.cellCount === 0) return null;
+ return this.#memoryRefusal;
+ });
+ readonly #ready = $derived.by(() => {
+ const l = this.#ledger;
+ return (
+ l !== null &&
+ l.isFinal &&
+ l.cellCount > 0 &&
+ this.#refusal === null &&
+ !this.#running &&
+ !this.#paused &&
+ !this.#clearingCells &&
+ this.#estimate !== null &&
+ this.#estimateLedger === l &&
+ !this.#estimatePending &&
+ // An unanswered projection keeps the mandatory pre-download check honest:
+ // the button waits for the retry, not forever.
+ this.#estimateError === null
+ );
+ });
+}
+
+async function waitForRunOperations(owner: Output) {
+ // Operations can start nested work (download callbacks start OPFS writes), so drain until
+ // the owned set remains empty after a microtask turn rather than trusting one snapshot.
+ for (;;) {
+ const pending = [...owner.operations];
+ if (pending.length > 0) await Promise.allSettled(pending);
+ await Promise.resolve();
+ if (owner.operations.size === 0) return;
+ }
+}
diff --git a/builder/web/src/lib/coverage/shape.test.ts b/builder/web/src/lib/coverage/shape.test.ts
index 4e90480160..d114437524 100644
--- a/builder/web/src/lib/coverage/shape.test.ts
+++ b/builder/web/src/lib/coverage/shape.test.ts
@@ -25,7 +25,7 @@ describe("patchCount", () => {
expect(patchCount([cellId(18, 100, 100), cellId(18, 100, 101), cellId(18, 101, 100), cellId(18, 101, 101)])).toBe(1);
});
- it("counts disjoint patches — the corridor panel's gaps are this minus one", () => {
+ it("counts disjoint patches — the proof's gaps are this minus one", () => {
expect(patchCount([cellId(18, 100, 100), cellId(18, 200, 200)])).toBe(2);
});
diff --git a/builder/web/src/lib/coverage/shape.ts b/builder/web/src/lib/coverage/shape.ts
index 64811be494..5d5b469936 100644
--- a/builder/web/src/lib/coverage/shape.ts
+++ b/builder/web/src/lib/coverage/shape.ts
@@ -88,8 +88,8 @@ function signedArea(ring: RingPoint[]): number {
}
/**
- * How many disjoint patches a cell set forms — the number the corridor panel turns into
- * "1 gap between routes" (patches − 1). Outer rings wind counter-clockwise and holes
+ * How many disjoint patches a cell set forms — the coverage proof calls patches − 1
+ * "separate parts". Outer rings wind counter-clockwise and holes
* clockwise, so patches are exactly the positive-area rings.
*/
export function patchCount(cells: Iterable): number {
diff --git a/builder/web/src/lib/coverage/store.svelte.test.ts b/builder/web/src/lib/coverage/store.svelte.test.ts
index 46468ae771..05d3038ce9 100644
--- a/builder/web/src/lib/coverage/store.svelte.test.ts
+++ b/builder/web/src/lib/coverage/store.svelte.test.ts
@@ -3,7 +3,7 @@
// These are the selection-to-UI adapters on top of the already-tested arithmetic: part
// lifecycle and naming, the pending/final story a summary card depends on, the refusals
// that must arrive as sentences rather than crashes, and — measured, not assumed — the
-// resolver reuse that keeps the corridor slider smooth.
+// resolver reuse that keeps an edit of one part from repricing the others.
import { describe, expect, it } from "vitest";
import { CatalogClient } from "../catalog/client";
@@ -84,34 +84,6 @@ describe("region parts", () => {
});
});
-describe("lasso parts", () => {
- it("adds a drawn ring as a part, named and priced like a box", () => {
- const store = makeStore();
- // A triangle over the published column: same ground as PUBLISHED_BOX.
- store.addLasso([
- { lat: 47_210_000, lon: 7_360_000 },
- { lat: 47_210_000, lon: 7_590_000 },
- { lat: 47_390_000, lon: 7_470_000 },
- ]);
- expect(store.selection.parts).toHaveLength(1);
- expect(store.selection.parts[0].kind).toBe("lasso");
- expect(store.selection.parts[0].name).toBe("Lasso — Switzerland");
- expect(store.ledger!.totalBytes).toBeGreaterThan(0);
- });
-
- it("refuses a world-sized ring as a sentence, not a crash", () => {
- const store = makeStore();
- store.addLasso([
- { lat: -60_000_000, lon: -85_000_000 },
- { lat: -60_000_000, lon: 85_000_000 },
- { lat: 60_000_000, lon: 0 },
- ]);
- expect(store.selection.parts).toHaveLength(0);
- expect(store.drawError).toMatch(/smaller one/);
- expect(store.ledger).not.toBeNull();
- });
-});
-
describe("box parts", () => {
it("names a box after the smallest region under its centre", () => {
const store = makeStore();
@@ -272,54 +244,30 @@ describe("partial-detail hatching (#1041 A9)", () => {
});
});
-describe("corridor previews", () => {
- const route = [
- { lat: 47_200_000, lon: 7_400_000 },
- { lat: 47_350_000, lon: 7_550_000 },
- ];
-
- it("commits one part per route, so the ground between two routes stays a hole", () => {
- const store = makeStore();
- store.previewParts = [
- store.makePreviewPart("r1", "Morning Loop", route),
- store.makePreviewPart("r2", "Evening Loop", route),
- ];
- store.commitPreview();
- expect(store.previewParts).toHaveLength(0);
- expect(store.selection.parts.map((p) => p.kind)).toEqual(["corridor", "corridor"]);
- expect(store.selection.parts.map((p) => p.name)).toEqual(["Morning Loop", "Evening Loop"]);
- });
-
- it("prices what a candidate adds on top of the committed selection", () => {
- const store = makeStore();
- withSwissList(store);
- store.previewParts = [store.makePreviewPart("r1", "Loop", route)];
- const alone = store.previewSummary(1)!;
- expect(alone.addsBytes).toBeGreaterThan(0);
-
- // With Switzerland already in the map, the same corridor adds nothing —
- // its cells are already paid for.
- store.addRegion("europe/switzerland");
- const covered = store.previewSummary(1)!;
- expect(covered.addsBytes).toBe(0);
- expect(covered.addsCells).toBe(0);
+describe("the area of a map", () => {
+ it("gives back the area it was set to, without a region or a skin that the catalog does not hold", () => {
+ const client = CatalogClient.fromBody(canonicalCatalogBody, ROOT_URL, { fetchImpl: offline });
+ const store = new CoverageStore(client, canonicalCatalogBody, null);
+ store.addRegion("europe/switzerland/basel-stadt");
+ store.setArea({ regions: ["europe/switzerland", "europe/atlantis"], boxes: [PUBLISHED_BOX], light: "custom-gone", dark: "dusk" });
+ expect(store.area()).toEqual({ regions: ["europe/switzerland"], boxes: [PUBLISHED_BOX], light: "default", dark: "dusk" });
});
+});
- it("reuses every non-corridor answer when the width slider moves", () => {
+describe("resolver reuse", () => {
+ it("reuses the region's answers when a box is added", () => {
const store = makeStore();
withSwissList(store);
store.addRegion("europe/switzerland");
- store.addCorridor("Loop", route);
void store.ledger; // settle the cache
const before = { ...store.resolverStats };
- store.setCorridorRadius(25_000);
+ store.addBox(PUBLISHED_BOX);
void store.ledger;
const after = store.resolverStats;
const bands = exampleCatalog.schema.bands.length;
- // The radius is global, so only the corridor part recomputes — one
- // answer per band — and the region's four are cache hits. This is the
- // measurement behind "the slider re-buffers live and stays smooth".
+ // Only the new box computes — one answer per band — and the region's
+ // answers are cache hits.
expect(after.computed - before.computed).toBe(bands);
expect(after.reused - before.reused).toBe(bands);
});
@@ -393,7 +341,7 @@ describe("custom skin admission", () => {
describe("catalog refresh", () => {
- it("preserves every selection kind, radius and compatible custom styles without old catalog caches", () => {
+ it("preserves every selection kind and compatible custom styles without old catalog caches", () => {
let saved: string | null = null;
const storage = { getItem: () => saved, setItem: (_key: string, value: string) => { saved = value; } };
const client = CatalogClient.fromBody(canonicalCatalogBody, ROOT_URL, { fetchImpl: offline });
@@ -402,10 +350,6 @@ describe("catalog refresh", () => {
withSwissList(store);
store.addRegion("europe/switzerland");
store.addBox(PUBLISHED_BOX);
- const points = [{ lat: 47_200_000, lon: 7_400_000 }, { lat: 47_350_000, lon: 7_550_000 }];
- store.addCorridor("Weekend GPX", points);
- store.addLasso([...points, { lat: 47_200_000, lon: 7_550_000 }]);
- store.setCorridorRadius(25_000);
store.saveCustomSkin(store.lightSkin, "My light", "default");
store.saveCustomSkin(store.darkSkin, "My dark", "dusk");
const root = JSON.parse(canonicalCatalogBody);
@@ -422,8 +366,8 @@ describe("catalog refresh", () => {
expect(next.darkSkin).toEqual(store.darkSkin);
expect(next.refreshNotice).toBeNull();
next.addBox(PUBLISHED_BOX);
- expect(new Set(next.selection.parts.map((p) => p.id)).size).toBe(5);
- expect(store.selection.parts).toHaveLength(4);
+ expect(new Set(next.selection.parts.map((p) => p.id)).size).toBe(3);
+ expect(store.selection.parts).toHaveLength(2);
});
it("keeps removed regions as blocked parts and reports an incompatible selected style", () => {
diff --git a/builder/web/src/lib/coverage/store.svelte.ts b/builder/web/src/lib/coverage/store.svelte.ts
index 845120de32..4d312fedda 100644
--- a/builder/web/src/lib/coverage/store.svelte.ts
+++ b/builder/web/src/lib/coverage/store.svelte.ts
@@ -4,13 +4,12 @@
// The arithmetic all lives in `lib/catalog/` — this class owns *state and
// lifetime*. Two `SelectionResolver`s, deliberately: each prunes cache entries
// that were not part of its latest answer, so one resolver alternating between
-// the committed selection and the selection plus the corridor panel's preview
-// would evict half its cache on every frame.
+// the committed selection and the box being dragged would evict the committed
+// answers on every move.
import type { ArticleIndexDocument } from "../catalog/articles";
import { CatalogClient } from "../catalog/client";
import { cellsIntersecting, coverageBbox, parseCellId, type UBox } from "../core/grid";
-import { lassoCells } from "../catalog/lasso";
import { cellsTouchingHoles, detailBandId } from "./shape";
import { ledgerFor, type Ledger } from "../catalog/ledger";
import type { Catalog, RegionEntry, SkinEntry } from "../catalog/manifest";
@@ -27,35 +26,13 @@ import {
import {
emptySelection,
SelectionResolver,
- withCorridorRadius,
withoutPart,
withPart,
- type CorridorPart,
- type LatLon,
type Selection,
- type SelectionPart,
type SelectionContext,
type SelectionResolution,
} from "../catalog/selection";
-/** The slider's range and default, metres. The default is a day-ride's "what if
- * I take the other valley" allowance — wide enough that a detour stays on the
- * map, narrow enough that a corridor stays corridor-shaped (cells are ~29 km,
- * so the first step past the route is already generous). */
-export const CORRIDOR_RADIUS_DEFAULT_M = 10_000;
-export const CORRIDOR_RADIUS_MIN_M = 2_000;
-export const CORRIDOR_RADIUS_MAX_M = 50_000;
-
-/** What the corridor panel's "adds …" line states about a candidate. */
-export interface PreviewSummary {
- /** Bytes the map grows by — the candidate's cells minus what the selection
- * already covers. */
- addsBytes: number;
- addsCells: number;
- /** Disjoint patches the candidate itself forms (2 routes far apart = 2). */
- patches: number;
-}
-
/** A boundary's bbox area in µdeg², the ladder's smallest-first sort key. Not a
* real area — but ordering nested admin regions only needs monotonicity, and a
* child's bbox never out-spans its parent's. */
@@ -114,15 +91,11 @@ export class CoverageStore {
/** Region list fetches that failed, by region id — the part row says so. */
regionErrors = $state>(new Map());
- selection = $state(emptySelection(CORRIDOR_RADIUS_DEFAULT_M));
+ selection = $state(emptySelection());
lightSkinId = $state("default");
darkSkinId = $state("dusk");
customSkinRecords = $state([]);
- /** The corridor panel's checked-but-not-yet-added routes, drawn dashed on
- * the map and priced by {@link previewSummary}. */
- previewParts = $state([]);
-
/** Somewhere the map should fly to — a warning row was clicked. Consumed
* (nulled) by the map after the flight. */
focus = $state(null);
@@ -131,14 +104,12 @@ export class CoverageStore {
highlightPartId = $state(null);
private readonly resolver = new SelectionResolver();
- private readonly previewResolver = new SelectionResolver();
- /** Prices the box being dragged, apart from the other two so a drag never
- * evicts the committed selection's warm cache. */
+ /** Prices the box being dragged, apart from the committed resolver so a drag
+ * never evicts the committed selection's warm cache. */
private readonly dragResolver = new SelectionResolver();
private readonly skinStorage: SkinStorage | null;
private nextPartId = 1;
private boxCount = 0;
- private lassoCount = 0;
constructor(client: CatalogClient, rootBody: string, skinStorage: SkinStorage | null = browserSkinStorage()) {
this.client = client;
@@ -155,7 +126,6 @@ export class CoverageStore {
next.selection = this.selection;
next.nextPartId = this.nextPartId;
next.boxCount = this.boxCount;
- next.lassoCount = this.lassoCount;
for (const part of next.selection.parts) {
if (part.kind !== "region") continue;
if (next.region(part.regionId)) void next.fetchRegionCells(part.regionId);
@@ -215,7 +185,7 @@ export class CoverageStore {
* be. A resolution *throws* for exactly two kinds of reason, and both are
* refusals rather than crashes: a broken publish (a region list naming a cell
* no band index carries), and a part outside what the grid enumerates (a box
- * over half the planet, a corridor crossing the antimeridian). The UI shows
+ * over half the planet). The UI shows
* the sentence and the parts list stays alive, so the offending part can be
* removed.
*/
@@ -242,25 +212,6 @@ export class CoverageStore {
return resolution && this.indices ? ledgerFor(resolution, this.catalog, this.indices, this.articles) : null;
});
- /** The selection plus the panel's preview routes — what the map draws while
- * the panel is open, and what the adds-line is priced from. Null (never a
- * throw) when a preview route cannot be resolved; the panel says so. */
- readonly previewed = $derived.by<{ resolution: SelectionResolution | null; error: string | null }>(() => {
- const ctx = this.ctx;
- if (!ctx || this.previewParts.length === 0) return { resolution: null, error: null };
- let candidate = this.selection;
- for (const part of this.previewParts) candidate = withPart(candidate, part);
- try {
- return { resolution: this.previewResolver.resolve(candidate, ctx), error: null };
- } catch (e) {
- return { resolution: null, error: e instanceof Error ? e.message : String(e) };
- }
- });
-
- get previewResolution(): SelectionResolution | null {
- return this.previewed.resolution;
- }
-
readonly skins = $derived.by(() => [
...this.catalog.skins,
...this.customSkinRecords.map((record) => record.skin),
@@ -322,19 +273,6 @@ export class CoverageStore {
if (this.darkSkinId === id) this.darkSkinId = "dusk";
}
- /** What the panel's candidate would add to the committed map. */
- previewSummary(patches: number): PreviewSummary | null {
- const withPreview = this.previewResolution;
- const ledger = this.ledger;
- if (!withPreview || !ledger || !this.indices) return null;
- const candidate = ledgerFor(withPreview, this.catalog, this.indices, this.articles);
- return {
- addsBytes: Math.max(0, candidate.totalBytes - ledger.totalBytes),
- addsCells: Math.max(0, candidate.cellCount - ledger.cellCount),
- patches,
- };
- }
-
/**
* The selection's holes, from **every** band, deduplicated.
*
@@ -435,8 +373,8 @@ export class CoverageStore {
void this.fetchRegionCells(regionId);
}
- /** Why the last drawn box or lasso was refused, shown as a map chip until
- * the next draw. */
+ /** Why the last drawn box was refused, shown as a map chip until the next
+ * draw. */
drawError = $state(null);
/**
@@ -447,21 +385,9 @@ export class CoverageStore {
* than a second pricing path that can drift.
*/
priceDraggedBox(box: UBox): { bytes: number; cells: number } | { refused: true } | null {
- return this.priceDragged({ kind: "box", id: "drag", name: "", box });
- }
-
- /** Price a lasso mid-draw — the live chip under the pen, same discipline. */
- priceDraggedLasso(points: LatLon[]): { bytes: number; cells: number } | { refused: true } | null {
- return this.priceDragged({ kind: "lasso", id: "drag", name: "", points });
- }
-
- private priceDragged(part: SelectionPart): { bytes: number; cells: number } | { refused: true } | null {
const ctx = this.ctx;
if (!ctx || !this.indices) return null;
- const candidate: Selection = {
- parts: [part],
- corridorRadiusM: this.selection.corridorRadiusM,
- };
+ const candidate: Selection = { parts: [{ kind: "box", id: "drag", name: "", box }] };
try {
const ledger = ledgerFor(this.dragResolver.resolve(candidate, ctx), this.catalog, this.indices, this.articles);
return { bytes: ledger.totalBytes, cells: ledger.cellCount };
@@ -493,31 +419,6 @@ export class CoverageStore {
});
}
- addLasso(points: LatLon[]): void {
- // Same pre-check as a box, through the ring's own enumeration: a part
- // the grid refuses must never make the whole ledger throw.
- try {
- for (const band of this.catalog.schema.bands) lassoCells(band.cell_log2, points);
- } catch {
- this.drawError = "That lasso covers more cells than a map can hold — draw a smaller one, or add a whole region instead.";
- return;
- }
- this.drawError = null;
- this.lassoCount += 1;
- let latSum = 0;
- let lonSum = 0;
- for (const p of points) {
- latSum += p.lat;
- lonSum += p.lon;
- }
- this.selection = withPart(this.selection, {
- kind: "lasso",
- id: `part-${this.nextPartId++}`,
- name: this.areaName("Lasso", latSum / points.length, lonSum / points.length, this.lassoCount),
- points,
- });
- }
-
/** "Box — ", because "Box 3"
* tells nobody which box to remove. Containment is tested against the
* region's actual boundary rings, not its bounding box: a box centred in the
@@ -528,38 +429,29 @@ export class CoverageStore {
return best ? `${prefix} — ${best.name}` : `${prefix} ${count}`;
}
- addCorridor(name: string, points: LatLon[]): void {
- this.selection = withPart(this.selection, {
- kind: "corridor",
- id: `part-${this.nextPartId++}`,
- name,
- points,
- });
+ /** The regions and the boxes of the selection, and the ids of the two skins, as plain values that a database can store. */
+ area(): { regions: string[]; boxes: UBox[]; light: string; dark: string } {
+ const parts = this.selection.parts;
+ return {
+ regions: parts.flatMap((part) => (part.kind === "region" ? [part.regionId] : [])),
+ boxes: parts.flatMap((part) => (part.kind === "box" ? [{ ...part.box }] : [])),
+ light: this.lightSkin.id,
+ dark: this.darkSkin.id,
+ };
+ }
+
+ /** Replaces the selection and the skins with `area`. A region that the catalog does not hold is left out, and a
+ * skin that is not there gives the first of its kind. */
+ setArea(area: { regions: string[]; boxes: UBox[]; light: string; dark: string }): void {
+ this.selection = emptySelection();
+ for (const regionId of area.regions) this.addRegion(regionId);
+ for (const box of area.boxes) this.addBox(box);
+ this.lightSkinId = area.light;
+ this.darkSkinId = area.dark;
}
removePart(partId: string): void {
this.selection = withoutPart(this.selection, partId);
if (this.highlightPartId === partId) this.highlightPartId = null;
}
-
- setCorridorRadius(radiusM: number): void {
- this.selection = withCorridorRadius(this.selection, radiusM);
- }
-
- /** A preview part with a stable id, so the panel can replace one route's
- * entry without perturbing the others' cache keys. */
- makePreviewPart(routeId: string, name: string, points: LatLon[]): CorridorPart {
- return { kind: "corridor", id: `preview-${routeId}`, name, points };
- }
-
- /** Commit the panel's checked routes: one corridor part per route, because a
- * part buffers a single polyline and joining two routes into one would
- * bridge the ground between them with corridor cells — the exact gap the
- * design promises stays a hole. */
- commitPreview(): void {
- for (const preview of this.previewParts) {
- this.addCorridor(preview.name, preview.points);
- }
- this.previewParts = [];
- }
}
diff --git a/builder/web/src/lib/covers/Cover.svelte b/builder/web/src/lib/covers/Cover.svelte
new file mode 100644
index 0000000000..e3291d33ab
--- /dev/null
+++ b/builder/web/src/lib/covers/Cover.svelte
@@ -0,0 +1,169 @@
+
+
+ { if (!(event.target as Element).closest('.route-pin')) opened = undefined; }} />
+
+
+ {#if shown}
+
onpoint?.(null)}>
+ {#each shownPins as pin (pin.index)}
+
+ opened = pin.index} onfocus={() => opened = pin.index} onblur={() => opened = undefined}
+ onkeydown={event => { if (event.key === 'Escape') opened = undefined; }}>
+ {#if pin.number}{pin.number}{:else} {/if}
+
+ {#if opened === pin.index}{pinName(pin)} {/if}
+
+ {/each}
+ {:else if fallback && line}
+
+
+
+ {/if}
+
+
+
diff --git a/builder/web/src/lib/covers/CoverPage.svelte b/builder/web/src/lib/covers/CoverPage.svelte
new file mode 100644
index 0000000000..762f08e5d0
--- /dev/null
+++ b/builder/web/src/lib/covers/CoverPage.svelte
@@ -0,0 +1,36 @@
+
+
+
+
+ {#each [['card', 'card'], ['large', 'page']] as const as [size, place] (size)}
+ mark = metres ?? undefined} />
+ {/each}
+
+
+
diff --git a/builder/web/src/lib/covers/draw.test.ts b/builder/web/src/lib/covers/draw.test.ts
new file mode 100644
index 0000000000..b81c43c04c
--- /dev/null
+++ b/builder/web/src/lib/covers/draw.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from 'vitest';
+import type { Summary } from '../library/records';
+import { drawCover, REST } from './draw';
+import { pack } from './line';
+
+// Five visible points 100 m and 100 px apart along y = 50.
+const x = [0, 100, 200, 300, 400];
+const points = pack({
+ x: Float32Array.from(x), y: Float32Array.from(x, () => 50),
+ distance: Float32Array.from(x, (_, i) => 1000 * (i + 1)), visible: Uint8Array.from(x, () => 1),
+});
+const summary = {
+ line: x.flatMap((_, i) => [i * 0.0009, 0]), heights: x.map(() => null), bounds: [0, 0, 0.0036, 0],
+ lengthM: 400, climbM: 0, highestM: null, seconds: 0, bike: 'road',
+} satisfies Summary;
+
+/** A context that keeps the colour and the strength of each stroke, and the x where its path starts. */
+function recorder() {
+ const strokes: { colour: string; alpha: number; from: number }[] = [];
+ let from = 0;
+ const context = {
+ globalAlpha: 1, strokeStyle: '', fillStyle: '', lineWidth: 1, lineCap: '', lineJoin: '',
+ drawImage() {}, beginPath() {}, moveTo(x: number) { from = x; }, lineTo() {}, arc() {}, fill() {},
+ stroke() { strokes.push({ colour: context.strokeStyle, alpha: context.globalAlpha, from }); },
+ };
+ return { context: context as unknown as CanvasRenderingContext2D, strokes };
+}
+const LINE = '#cc2a93', GLOW = '#ee8fcf', CORE = '#f8b8e2';
+const cover = { image: {} as CanvasImageSource, width: 400, height: 100, points, summary };
+function strokesOf(part?: [number, number]) {
+ const { context, strokes } = recorder();
+ drawCover(context, cover, { box: [400, 100], line: true, part });
+ return strokes;
+}
+
+describe('the line of a cover', () => {
+ it('draws no pale colour with no part', () => {
+ expect(strokesOf().map(stroke => stroke.colour)).not.toContain(REST.route);
+ });
+
+ it('draws the part in the colours of the line, and the rest pale with no glow and no core, under the part', () => {
+ // The part is the segment from x = 100 to x = 200.
+ const strokes = strokesOf([100, 200]), inPart = strokes.filter(stroke => stroke.from === 100), rest = strokes.filter(stroke => stroke.from !== 100);
+ expect(rest.length).toBeGreaterThan(0);
+ expect(rest.every(stroke => stroke.colour === REST.route && stroke.alpha === 1)).toBe(true);
+ expect(new Set(inPart.map(stroke => stroke.colour))).toEqual(new Set([GLOW, LINE, CORE]));
+ expect(inPart.find(stroke => stroke.colour === LINE)?.alpha).toBe(1);
+ expect(strokes.indexOf(inPart[0])).toBeGreaterThan(strokes.lastIndexOf(rest.at(-1)!));
+ });
+
+ it('draws a part shorter than one segment in the colour of the line', () => {
+ const strong = strokesOf([120, 130]).filter(stroke => stroke.colour === LINE);
+ expect(strong.map(stroke => stroke.from)).toEqual([100]);
+ });
+});
diff --git a/builder/web/src/lib/covers/draw.ts b/builder/web/src/lib/covers/draw.ts
new file mode 100644
index 0000000000..9bc0c7681a
--- /dev/null
+++ b/builder/web/src/lib/covers/draw.ts
@@ -0,0 +1,111 @@
+/** Draws a cover into a box: the image cut as CSS `cover` cuts it, the line of the route, a selected part and the mark. */
+import type { CoverPoints, Summary } from '../library/records';
+import { along, distanceAt, metresAlong, placed, runs } from './line';
+
+/** The image is the same in both themes, so the line of a route keeps the colour of the light theme: `--route`. As the
+ * ribbon of TrailView, a glow in a lighter tint of the line fades out beyond it, and a weak light core runs in its
+ * middle. The line of a ride is a teal, lighter than `--ride` so that it shows on a dark slope; `ring` is the edge of the mark. */
+const LOOKS = {
+ route: { line: '#cc2a93', glow: '#ee8fcf', core: '#f8b8e2', ring: '#cc2a93' },
+ ride: { line: '#12b3a8', glow: '#84e2d9', core: '#cdf6f1', ring: '#0b8f8b' },
+};
+export type Look = 'route' | 'ride';
+/** With a part, the part keeps the colours of its look. The rest of the line is a paler solid tint with no glow and no
+ * core, so that it stays behind the part on a dark slope as the pale line does on the map. */
+export const REST: Record = { route: '#e7a6d0', ride: '#a5d8d3' };
+/** The glow reaches GLOW_REACH of the widest line beyond it, in GLOW_STEPS strokes of GLOW_ALPHA each; the core is CORE_WIDTH of the line. */
+const GLOW_REACH = 0.6, GLOW_STEPS = 5, GLOW_ALPHA = 0.14, CORE_WIDTH = 0.25, CORE_ALPHA = 0.3;
+/** The width of the line at the point nearest to the eye, as a share of the shorter side of the box, and the least width as a share of it. */
+const WIDEST = 0.012, LEAST = 1 / 3;
+
+/** The cut of the image: canvas pixel = (image pixel − `left`, `top`) · `scale`. */
+export interface Crop { scale: number; left: number; top: number }
+
+export interface CoverImage {
+ image: CanvasImageSource;
+ width: number;
+ height: number;
+ points: CoverPoints;
+ /** The summary that the points belong to. Without it, the line shows with no part and no mark. */
+ summary?: Summary;
+}
+
+/** The cut for a box of `width` × `height`: it fills the box as CSS `cover` does, and moves toward the middle of the route as far as the image permits. */
+export function crop(cover: Pick, [width, height]: [number, number]): Crop {
+ const scale = Math.max(width / cover.width, height / cover.height), { points } = cover;
+ const middle = (axis: Float32Array, size: number) => {
+ let low = Infinity, high = -Infinity;
+ for (let i = 0; i < axis.length; i++) if (placed(points, i)) [low, high] = [Math.min(low, axis[i]), Math.max(high, axis[i])];
+ return low <= high ? (Math.max(low, 0) + Math.min(high, size)) / 2 : size / 2;
+ };
+ const place = (centre: number, size: number, shown: number) => Math.max(0, Math.min(size - shown, centre - shown / 2));
+ return { scale, left: place(middle(points.x, cover.width), cover.width, width / scale), top: place(middle(points.y, cover.height), cover.height, height / scale) };
+}
+
+/** Draws the cover over the whole canvas of `context`, which is `box` pixels in size, and returns the cut. `mark` and `part` are metres along the route. */
+export function drawCover(context: CanvasRenderingContext2D, cover: CoverImage,
+ { box, mark, part, line, look = 'route' }: { box: [number, number]; mark?: number; part?: [number, number]; line: boolean; look?: Look }): Crop {
+ const cut = crop(cover, box), { points, summary } = cover, colours = LOOKS[look];
+ context.drawImage(cover.image, cut.left, cut.top, box[0] / cut.scale, box[1] / cut.scale, 0, 0, box[0], box[1]);
+ if (!line) return cut;
+ const x = (i: number) => (points.x[i] - cut.left) * cut.scale, y = (i: number) => (points.y[i] - cut.top) * cut.scale;
+ // The width falls with the distance from the eye.
+ let nearest = Infinity;
+ for (let i = 0; i < points.x.length; i++) if (placed(points, i)) nearest = Math.min(nearest, distanceAt(points, i));
+ const widest = Math.max(2, WIDEST * Math.min(...box));
+ const width = (i: number) => widest * Math.max(LEAST, Math.min(1, nearest / distanceAt(points, i)));
+ const metres = summary && part && metresAlong(summary);
+ // A segment that overlaps the part is in it, so a part shorter than one segment still shows.
+ const inPart = (i: number) => !!metres && !!part && metres[i] > part[0] && metres[i - 1] < part[1];
+
+ // Consecutive segments of one width step and one colour make one path, so that a weak stroke shows no dots at its
+ // joints. A stretch that the terrain hides draws nothing.
+ const pieces: { part: boolean; w: number; from: number; to: number }[] = [];
+ for (const run of runs(points)) for (let i = run.from + 1; run.visible && i <= run.to; i++) {
+ const w = Math.round(width(i - 1) + width(i)) / 2, last = pieces.at(-1), inside = inPart(i);
+ if (last?.to === i - 1 && last.w === w && last.part === inside) last.to = i;
+ else pieces.push({ part: inside, w, from: i - 1, to: i });
+ }
+ const reach = Math.max(2, GLOW_REACH * widest), glow = Array.from({ length: GLOW_STEPS }, (_, k) => 2 * reach * (GLOW_STEPS - k) / GLOW_STEPS);
+ // The rest draws first, so the part with its glow is on top where the line crosses itself or goes back on itself.
+ const passes: { width: (w: number) => number; colour: string; alpha: number; part: boolean }[] = [
+ ...metres ? [{ width: (w: number) => w, colour: REST[look], alpha: 1, part: false }] : [],
+ ...glow.map(extra => ({ width: (w: number) => w + extra, colour: colours.glow, alpha: GLOW_ALPHA, part: true })),
+ { width: w => w, colour: colours.line, alpha: 1, part: true },
+ { width: w => CORE_WIDTH * w, colour: colours.core, alpha: CORE_ALPHA, part: true },
+ ];
+ context.lineCap = context.lineJoin = 'round';
+ for (const pass of passes) {
+ context.globalAlpha = pass.alpha;
+ for (const piece of pieces) {
+ if (metres && piece.part !== pass.part) continue;
+ context.beginPath();
+ context.moveTo(x(piece.from), y(piece.from));
+ for (let i = piece.from + 1; i <= piece.to; i++) context.lineTo(x(i), y(i));
+ context.lineWidth = pass.width(piece.w);
+ context.strokeStyle = pass.colour;
+ context.stroke();
+ }
+ }
+ context.globalAlpha = 1;
+ const at = summary && mark !== undefined ? along(points, summary, mark) : undefined;
+ if (at) {
+ const cx = (at.x - cut.left) * cut.scale, cy = (at.y - cut.top) * cut.scale, r = 1.2 * widest;
+ context.fillStyle = colours.glow;
+ context.globalAlpha = GLOW_ALPHA;
+ for (const extra of glow) {
+ context.beginPath();
+ context.arc(cx, cy, r + extra / 2, 0, 2 * Math.PI);
+ context.fill();
+ }
+ context.globalAlpha = 1;
+ context.beginPath();
+ context.arc(cx, cy, r, 0, 2 * Math.PI);
+ context.fillStyle = '#fff';
+ context.fill();
+ context.lineWidth = widest * 0.5;
+ context.strokeStyle = colours.ring;
+ context.stroke();
+ }
+ return cut;
+}
diff --git a/builder/web/src/lib/covers/job.test.ts b/builder/web/src/lib/covers/job.test.ts
new file mode 100644
index 0000000000..ed8f3c79bf
--- /dev/null
+++ b/builder/web/src/lib/covers/job.test.ts
@@ -0,0 +1,411 @@
+import { IDBFactory } from 'fake-indexeddb';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { CoverRecord, RouteRecord } from '../library/records';
+import { Library } from '../library/store';
+import type { Still, StillJob } from '../trailview/still';
+import { lineKey } from '../library/summary';
+import { coverKey, settled, startCoverJob, wantCover, type Renderer } from './job';
+import type { MapPictureMaker, MapPictureResult } from './map-picture';
+
+const route = (id: string, name = id, line = [8.38, 46.82, 8.42, 46.81]): RouteRecord => ({
+ id, revision: 0, name, updatedAt: Date.UTC(2026, 7, 15), trip: {},
+ summary: { line, heights: [null, null], bounds: [8.38, 46.81, 8.42, 46.82], lengthM: 3000, climbM: 0, highestM: null, seconds: 600, bike: 'road', days: 1 },
+});
+const result: Still = {
+ image: new Blob(['cover']),
+ points: { x: Float32Array.of(10, 20), y: Float32Array.of(10, 20), distance: Float32Array.of(900, 1200), visible: Uint8Array.of(1, 1) },
+ credits: ['Terrain test data'],
+};
+const picture: MapPictureResult = { image: new Blob(['map']), points: { x: Float32Array.of(1, 2), y: Float32Array.of(1, 2), eye: Uint8Array.of(129, 129) }, credits: ['Map test data'] };
+const failure = (name: string) => Object.assign(new Error(name), { name });
+
+/** A fake TrailView: each still waits until the test settles it, or rejects as `still` does when its signal aborts. */
+function fake() {
+ const stills: { job: StillJob; resolve: (still: Still) => void; reject: (error: Error) => void }[] = [];
+ const listeners = new Set<() => void>();
+ let open = false;
+ const renderer: Renderer = {
+ canRender: async () => true,
+ view: async (_, when) => ({ lat: 46.8, lon: 8.4, heading: 0, pitch: -30, mode: 'fly', height: 3000, debug: 'off', plan: 'off', ...when }),
+ still: (job, signal) => new Promise((resolve, reject) => {
+ stills.push({ job, resolve, reject });
+ signal.addEventListener('abort', () => reject(failure('aborted')));
+ }),
+ trailViewOpen: () => open,
+ onTrailViewOpen: listener => { listeners.add(listener); return () => listeners.delete(listener); },
+ };
+ const setOpen = (value: boolean) => { open = value; listeners.forEach(listener => listener()); };
+ return { renderer, stills, setOpen };
+}
+
+/** A fake map picture: each one waits until the test settles it. */
+function fakePicture() {
+ const calls: { resolve: (made: MapPictureResult | 'none') => void; reject: (error: Error) => void }[] = [];
+ const maker: MapPictureMaker = (_, __, signal) => new Promise((resolve, reject) => {
+ calls.push({ resolve, reject });
+ signal.addEventListener('abort', () => reject(failure('aborted')));
+ });
+ return { maker, calls };
+}
+
+/** Lets the fake database and the job run, with no move of the fake clock. */
+const settle = async () => { for (let i = 0; i < 30; i++) await new Promise(resolve => setImmediate(resolve)); };
+
+let held = false;
+const document = Object.assign(new EventTarget(), { hidden: false });
+let library: Library, factory: IDBFactory, stops: (() => void)[], coarse = false;
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ vi.spyOn(console, 'info').mockImplementation(() => {});
+ held = false;
+ document.hidden = false;
+ vi.stubGlobal('document', document);
+ vi.stubGlobal('window', new EventTarget());
+ coarse = false;
+ vi.stubGlobal('matchMedia', (query: string) => ({ matches: coarse && query === '(pointer: coarse)' }));
+ // One lock for all the jobs, as the browser has for all its tabs.
+ vi.stubGlobal('navigator', {
+ onLine: true,
+ gpu: {},
+ locks: {
+ async request(_: string, __: unknown, work: (lock: object | null) => Promise) {
+ if (held) return work(null);
+ held = true;
+ try { return await work({}); } finally { held = false; }
+ },
+ },
+ });
+ factory = new IDBFactory();
+ library = new Library(factory);
+ stops = [];
+});
+
+afterEach(() => {
+ stops.forEach(stop => stop());
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+async function start(renderer: Renderer, on = library, picture = fakePicture().maker) {
+ stops.push(startCoverJob(on, async () => renderer, async () => picture));
+ await settle();
+}
+
+async function saved(...ids: string[]) {
+ for (const id of ids) await library.saveRoute(route(id));
+}
+
+describe('settled', () => {
+ it('is false for the image of an earlier line and for a waiting cover, so a page asks for them', () => {
+ const item = route('a'), key = coverKey(item), image = new Blob(['cover']);
+ expect(settled(item, undefined)).toBe(false);
+ expect(settled(item, { id: 'a', lineKey: coverKey(route('a', 'a', [8, 46, 8.1, 46])), state: 'done', image, tries: 0 })).toBe(false);
+ expect(settled(item, { id: 'a', lineKey: key, state: 'waiting', image, tries: 1 })).toBe(false);
+ for (const state of ['done', 'none', 'failed'] as const) expect(settled(item, { id: 'a', lineKey: key, state, tries: 0 })).toBe(true);
+ });
+});
+
+describe('the cover job', () => {
+ it('renders one cover at a time in the whole browser, and skips a cover that another tab made', async () => {
+ await saved('a');
+ const first = fake(), second = fake();
+ await start(first.renderer);
+ wantCover('a', 'page');
+ await settle();
+ // The second tab asks for the same cover while the first renders it.
+ await start(second.renderer, new Library(factory));
+ wantCover('a', 'page');
+ await settle();
+ expect([first.stills.length, second.stills.length]).toEqual([1, 0]);
+ first.stills[0].resolve(result);
+ await settle();
+ await vi.advanceTimersByTimeAsync(10_000);
+ await settle();
+ expect(second.stills).toHaveLength(0);
+ const cover = await library.cover('a');
+ expect(cover).toMatchObject({ state: 'done', lineKey: coverKey(route('a')), tries: 0, credits: ['Terrain test data'] });
+ expect(cover?.points?.x).toEqual(Float32Array.of(10, 20));
+ expect(first.stills[0].job).toMatchObject({ width: 1920, height: 1280, view: { date: '2026-08-15', time: '10:00', weather: 'sunny' } });
+ });
+
+ it('waits while the page is hidden', async () => {
+ await saved('a');
+ const { renderer, stills } = fake();
+ document.hidden = true;
+ await start(renderer);
+ wantCover('a', 'page');
+ await settle();
+ expect(stills).toHaveLength(0);
+ document.hidden = false;
+ document.dispatchEvent(new Event('visibilitychange'));
+ await settle();
+ expect(stills).toHaveLength(1);
+ });
+
+ it('stops a render when the planner opens TrailView, and renders it again when TrailView closes', async () => {
+ await saved('a');
+ const { renderer, stills, setOpen } = fake();
+ await start(renderer);
+ wantCover('a', 'page');
+ await settle();
+ setOpen(true);
+ await settle();
+ expect(await library.cover('a')).toBeUndefined();
+ setOpen(false);
+ await settle();
+ expect(stills).toHaveLength(2);
+ });
+
+ it.each([
+ ['hidden', undefined, 2],
+ ['tiles-failed', { state: 'waiting', tries: 1 }, 1],
+ ['device-lost', { state: 'waiting', tries: 1 }, 2],
+ ['timeout', { state: 'waiting', tries: 1 }, 1],
+ ])('after %s, it counts %o and renders %i stills of the record', async (name, cover, renders) => {
+ await saved('a');
+ const { renderer, stills } = fake();
+ await start(renderer);
+ wantCover('a', 'page');
+ await settle();
+ // A hidden page waits; here it is visible again at once.
+ stills[0].reject(failure(name));
+ await settle();
+ document.dispatchEvent(new Event('visibilitychange'));
+ await settle();
+ expect(await library.cover('a')).toEqual(cover && expect.objectContaining(cover));
+ expect(stills).toHaveLength(renders);
+ });
+
+ it('goes on to the next record after tiles fail, and renders no cover after a time limit', async () => {
+ await saved('a', 'b', 'c');
+ const { renderer, stills } = fake();
+ await start(renderer);
+ wantCover('b', 'page');
+ wantCover('a', 'page');
+ await settle();
+ stills[0].reject(failure('tiles-failed'));
+ await settle();
+ expect(stills.map(still => still.job.line)).toHaveLength(2);
+ stills[1].reject(failure('timeout'));
+ await settle();
+ wantCover('c', 'page');
+ await settle();
+ expect(stills).toHaveLength(2);
+ });
+
+ it('makes a map picture and no still for a card ask after a time limit', async () => {
+ await saved('a', 'b');
+ const { renderer, stills } = fake(), { maker, calls } = fakePicture();
+ await start(renderer, library, maker);
+ wantCover('a', 'page');
+ await settle();
+ stills[0].reject(failure('timeout'));
+ await settle();
+ wantCover('b', 'card');
+ await settle();
+ expect([stills.length, calls.length]).toEqual([1, 1]);
+ });
+
+ it('marks a cover as failed after three tries, also of earlier sessions', async () => {
+ await saved('a');
+ await library.saveCover({ id: 'a', lineKey: coverKey(route('a')), state: 'waiting', tries: 2 });
+ const { renderer, stills } = fake();
+ await start(renderer);
+ wantCover('a', 'page');
+ await settle();
+ stills[0].reject(failure('tiles-failed'));
+ await settle();
+ expect(await library.cover('a')).toMatchObject({ state: 'failed', tries: 3 });
+ wantCover('a', 'page');
+ await settle();
+ expect(stills).toHaveLength(1);
+ });
+
+ it('renders the planner route 30 s after its line changes, and not after a new name', async () => {
+ const { renderer, stills } = fake();
+ await start(renderer);
+ await library.saveRoute(route('a'));
+ await library.setState('active', 'a');
+ await settle();
+ await vi.advanceTimersByTimeAsync(29_000);
+ expect(stills).toHaveLength(0);
+ await vi.advanceTimersByTimeAsync(1_000);
+ await settle();
+ expect(stills).toHaveLength(1);
+ stills[0].resolve(result);
+ await settle();
+ await library.saveRoute(route('a', 'New name'));
+ await settle();
+ await vi.advanceTimersByTimeAsync(30_000);
+ await settle();
+ expect(stills).toHaveLength(1);
+ await library.saveRoute(route('a', 'New name', [8.38, 46.82, 8.45, 46.8]));
+ await settle();
+ await vi.advanceTimersByTimeAsync(30_000);
+ await settle();
+ expect(stills).toHaveLength(2);
+ });
+
+ it('renders no cover for a saved route that is not the open plan, such as an imported one', async () => {
+ const { renderer, stills } = fake();
+ await start(renderer);
+ await library.setState('active', 'a');
+ await saved('a', 'b');
+ await settle();
+ await vi.advanceTimersByTimeAsync(30_000);
+ await settle();
+ expect(stills.map(still => still.job.line)).toHaveLength(1);
+ stills[0].resolve(result);
+ await settle();
+ expect(await library.cover('b')).toBeUndefined();
+ });
+
+ it('renders a record again when it is asked for during its render, for the new line', async () => {
+ await saved('a');
+ const { renderer, stills } = fake();
+ await start(renderer);
+ wantCover('a', 'page');
+ await settle();
+ const line = [8.38, 46.82, 8.45, 46.8];
+ await library.saveRoute(route('a', 'a', line));
+ wantCover('a', 'page');
+ stills[0].resolve(result);
+ await settle();
+ expect(stills).toHaveLength(2);
+ expect(stills[1].job.line?.flat()).toEqual(line);
+ });
+
+ it('stores no cover for a route that is deleted during its render', async () => {
+ await saved('a');
+ const { renderer, stills } = fake();
+ await start(renderer);
+ wantCover('a', 'page');
+ await settle();
+ await library.removeRoute('a');
+ stills[0].resolve(result);
+ await settle();
+ expect(await library.cover('a')).toBeUndefined();
+ });
+
+ it('keeps an ask that comes before the job starts', async () => {
+ await saved('a');
+ const { renderer, stills } = fake();
+ wantCover('a', 'page');
+ await start(renderer);
+ expect(stills).toHaveLength(1);
+ });
+});
+
+describe('the map picture', () => {
+ /** A job with no WebGPU. */
+ async function noGpu() {
+ delete (navigator as { gpu?: object }).gpu;
+ const renderer = vi.fn<() => Promise>(), { maker, calls } = fakePicture();
+ stops.push(startCoverJob(library, renderer, async () => maker));
+ await settle();
+ return { renderer, calls };
+ }
+
+ it('comes with no WebGPU for a card and not for a page, and TrailView does not load', async () => {
+ await saved('a', 'b');
+ const { renderer, calls } = await noGpu();
+ wantCover('b', 'page');
+ wantCover('a', 'card');
+ await settle();
+ expect(calls).toHaveLength(1);
+ calls[0].resolve(picture);
+ await settle();
+ expect(calls).toHaveLength(1);
+ expect(renderer).not.toHaveBeenCalled();
+ expect(await library.cover('a')).toMatchObject({
+ state: 'waiting', tries: 0, map: { lineKey: lineKey(route('a')), tries: 0, light: expect.any(Blob), credits: ['Map test data'] },
+ });
+ expect(await library.cover('b')).toBeUndefined();
+ });
+
+ it('comes in place of a cover with a coarse pointer, as on a phone', async () => {
+ await saved('a');
+ coarse = true;
+ const renderer = vi.fn<() => Promise>(), { maker, calls } = fakePicture();
+ stops.push(startCoverJob(library, renderer, async () => maker));
+ wantCover('a', 'card');
+ await settle();
+ expect(calls).toHaveLength(1);
+ expect(renderer).not.toHaveBeenCalled();
+ });
+
+ it('waits while a cover renders, and comes after a cover that is not possible', async () => {
+ const { renderer, stills } = fake(), { maker, calls } = fakePicture(), view = renderer.view;
+ renderer.view = async (line, when) => line[0][0] === 9 ? undefined : view(line, when);
+ await library.saveRoute(route('a'));
+ await library.saveRoute(route('b', 'b', [9, 47, 9.1, 47]));
+ await start(renderer, library, maker);
+ wantCover('a', 'card');
+ await settle();
+ expect([stills.length, calls.length]).toEqual([1, 0]);
+ wantCover('b', 'card');
+ stills[0].resolve(result);
+ await settle();
+ expect(calls).toHaveLength(1);
+ calls[0].resolve(picture);
+ await settle();
+ expect(await library.cover('b')).toMatchObject({ state: 'none', map: { light: expect.any(Blob) } });
+ expect((await library.cover('a'))?.map).toBeUndefined();
+ });
+
+ it.each([
+ ['none', 1, { none: true }],
+ ['tiles-failed', 3, { tries: 3 }],
+ ])('stops for its line after %s, at %i pictures', async (end, count, map) => {
+ await saved('a');
+ const { calls } = await noGpu();
+ for (let i = 0; i < 4; i++) {
+ wantCover('a', 'card');
+ await settle();
+ if (end === 'none') calls[i]?.resolve('none');
+ else calls[i]?.reject(failure(end));
+ await settle();
+ }
+ expect(calls).toHaveLength(count);
+ expect((await library.cover('a'))?.map).toMatchObject(map);
+ });
+
+ it('goes when the cover is done', async () => {
+ await saved('a');
+ const waiting: CoverRecord = { id: 'a', lineKey: coverKey(route('a')), state: 'waiting', tries: 1, map: { lineKey: lineKey(route('a')), tries: 0, light: new Blob(['map']) } };
+ await library.saveCover(waiting);
+ const { renderer, stills } = fake();
+ await start(renderer);
+ wantCover('a', 'card');
+ await settle();
+ stills[0].resolve(result);
+ await settle();
+ expect(await library.cover('a')).toMatchObject({ state: 'done' });
+ expect((await library.cover('a'))?.map).toBeUndefined();
+ });
+
+ it('comes with a software renderer, which loads one time', async () => {
+ await saved('a', 'b');
+ const { renderer, stills } = fake(), { maker, calls } = fakePicture(), load = vi.fn(async () => renderer);
+ renderer.canRender = async () => false;
+ stops.push(startCoverJob(library, load, async () => maker));
+ wantCover('a', 'card');
+ await settle();
+ calls[0].resolve(picture);
+ await settle();
+ wantCover('b', 'card');
+ await settle();
+ expect([load.mock.calls.length, stills.length, calls.length]).toEqual([1, 0, 2]);
+ });
+
+ it('counts no try when its code fails to load', async () => {
+ await saved('a');
+ delete (navigator as { gpu?: object }).gpu;
+ stops.push(startCoverJob(library, vi.fn(), () => Promise.reject(new Error('Failed to fetch dynamically imported module'))));
+ wantCover('a', 'card');
+ await settle();
+ expect(await library.cover('a')).toBeUndefined();
+ });
+});
diff --git a/builder/web/src/lib/covers/job.ts b/builder/web/src/lib/covers/job.ts
new file mode 100644
index 0000000000..699df3a778
--- /dev/null
+++ b/builder/web/src/lib/covers/job.ts
@@ -0,0 +1,256 @@
+/** Renders the covers of routes and rides in the background, one at a time in the whole browser, and stores them in the
+ * library, with a map picture for a card whose record gets no cover. */
+import type { CoverRecord, MapPicture, RideRecord, RouteRecord } from '../library/records';
+import type { Library } from '../library/store';
+import { lineKey } from '../library/summary';
+import { loadTrailView } from '../planner/trailview';
+import { appearance } from '../theme.svelte';
+import type { Still, StillJob } from '../trailview/still';
+import { TIME_ZONE, type View } from '../trailview/view';
+import { pack } from './line';
+import type { MapPictureMaker } from './map-picture';
+
+export const WIDTH = 1920, HEIGHT = 1280;
+/** A changed route waits this long after its last change, so a rider who edits a route gets one cover at the end. */
+const SETTLE_MS = 30_000;
+/** A tab that finds the lock of another tab tries again after this. */
+const RETRY_MS = 10_000;
+const MAX_TRIES = 3;
+const LOCK = 'obc-cover';
+
+/** What the job uses of TrailView. A test gives fakes. */
+export interface Renderer {
+ /** False with no WebGPU or with a software renderer (`canRenderStills`). */
+ canRender(): Promise;
+ /** The cover view of a line (`coverView`), or undefined when no view holds it or TrailView has no data there. */
+ view(line: [number, number][], when: Pick): Promise;
+ /** A still on the page's GPU device; it rejects with the named errors of `still`. */
+ still(job: StillJob, signal: AbortSignal): Promise;
+ /** Whether the planner shows TrailView, and a listener for each change. */
+ trailViewOpen(): boolean;
+ onTrailViewOpen(listener: () => void): () => void;
+}
+
+/** Changes when the covers of a line change, so that the job makes them again; map pictures keep theirs. */
+const COVER_VERSION = 2;
+
+/** The key that a cover keeps in its field `lineKey`: the line of the record and COVER_VERSION. */
+export const coverKey = (item: RouteRecord | RideRecord) => `${lineKey(item)}/${COVER_VERSION}`;
+
+/** Whether the job has nothing left to do for the record: its cover is made, impossible or failed for its line. A page
+ * asks for the cover of a record that is not settled, also when it shows the cover of an earlier line. */
+export const settled = (item: RouteRecord | RideRecord, cover: CoverRecord | undefined) => cover?.lineKey === coverKey(item) && cover.state !== 'waiting';
+
+/** Where a cover part shows: a row of a list asks for nothing, a card for the cover and else for the map picture, a page
+ * for the cover only. */
+export type Place = 'row' | 'card' | 'page';
+type Asker = Exclude;
+
+/** Whether the job can still make the map picture of the theme for the line of the record: it has no cover image, and
+ * the picture of its line has no image of the theme, no `none` and fewer than MAX_TRIES tries. */
+export function wantsPicture(item: RouteRecord | RideRecord, cover: CoverRecord | undefined, dark: boolean): boolean {
+ const map = cover?.map?.lineKey === lineKey(item) ? cover.map : undefined;
+ return !cover?.image && !map?.none && (map?.tries ?? 0) < MAX_TRIES && !map?.[dark ? 'dark' : 'light'];
+}
+
+let asked: ((id: string, place: Asker) => void) | undefined;
+/** The asks that come before a job starts. */
+const early: [string, Asker][] = [];
+
+/** Asks for the cover of a route or a ride, if it has none for its line, and for a card also for the map picture. The
+ * newest ask comes first. */
+export function wantCover(id: string, place: Asker): void {
+ if (asked) asked(id, place);
+ else early.push([id, place]);
+}
+
+/**
+ * Starts the cover job of the page. It renders the covers that `wantCover` asks for, and the cover of the planner's
+ * route SETTLE_MS after its last change. For a card whose record gets no cover, it then makes the map picture of the
+ * theme. It works only while the page is visible and online. A cover also waits while the planner shows TrailView; a
+ * picture does not. Covers are off with no WebGPU or a coarse pointer and, once the job learns it, with a software renderer or after a still
+ * that reached its time limit. Returns the function that stops the job.
+ */
+export function startCoverJob(library: Library, renderer: () => Promise = trailView, picture: () => Promise = mapPicture): () => void {
+ if ((navigator as Navigator & { connection?: { saveData?: boolean } }).connection?.saveData) return () => {};
+ const queue: string[] = [], cards = new Set(), parked = new Set(), settling = new Map>(), stops: (() => void)[] = [];
+ // A phone gets no covers, as a browser with no WebGPU: its cards show the map picture.
+ let engine: Promise | undefined, off = !('gpu' in navigator) || matchMedia('(pointer: coarse)').matches, busy = false, stopped = false;
+ let rendering: AbortController | undefined, drawing: AbortController | undefined, retry: ReturnType | undefined;
+
+ const stop = () => {
+ stopped = true;
+ rendering?.abort();
+ drawing?.abort();
+ clearTimeout(retry);
+ for (const timer of settling.values()) clearTimeout(timer);
+ for (const end of stops) end();
+ if (asked === want) asked = undefined;
+ };
+ const want = (id: string, place: Asker) => {
+ if (place === 'card') cards.add(id);
+ if (queue.includes(id)) queue.splice(queue.indexOf(id), 1);
+ queue.unshift(id);
+ void pump();
+ };
+ asked = want;
+
+ // The renderer loads at the first cover, so a page that asks for none does not load the engine.
+ const load = () => engine ??= renderer().then(async loaded => {
+ if (!await loaded.canRender()) return undefined;
+ stops.push(loaded.onTrailViewOpen(() => {
+ if (loaded.trailViewOpen()) return rendering?.abort();
+ for (const id of parked) if (!queue.includes(id)) queue.push(id);
+ parked.clear();
+ void pump();
+ }));
+ return loaded;
+ });
+ const waits = () => stopped || document.hidden || !navigator.onLine;
+
+ async function pump(): Promise {
+ if (busy || waits() || !queue.length) return;
+ busy = true;
+ try {
+ while (queue.length && !waits()) {
+ // An ask during the work puts the id in the queue again, for the line that it has then.
+ const id = queue.shift()!;
+ const outcome = await navigator.locks.request(LOCK, { ifAvailable: true }, lock => lock && work(id));
+ if (outcome === 'park') parked.add(id);
+ else if (outcome === 'next') { if (!queue.includes(id)) cards.delete(id); }
+ else if (!queue.includes(id)) queue.unshift(id);
+ if (!outcome) {
+ retry = setTimeout(() => void pump(), RETRY_MS);
+ return;
+ }
+ }
+ } catch (error) {
+ console.error('Cover job:', error);
+ stop();
+ } finally {
+ busy = false;
+ }
+ }
+
+ /** The work for one record, inside the lock. `stay` puts the record first in the queue again; `park` keeps it until
+ * the planner closes TrailView. */
+ async function work(id: string): Promise<'next' | 'stay' | 'park'> {
+ const item = await library.item(id);
+ let cover = await library.cover(id);
+ // A record that is gone.
+ if (!item?.summary) return 'next';
+ if (!off && !settled(item, cover)) {
+ const loaded = await load();
+ if (!loaded) off = true;
+ else if (loaded.trailViewOpen()) return 'park';
+ else {
+ const outcome = await render(loaded, id, item, cover);
+ if (outcome !== 'next') return outcome;
+ cover = await library.cover(id);
+ }
+ }
+ const coverless = off || (settled(item, cover) && cover!.state !== 'done');
+ return cards.has(id) && coverless && wantsPicture(item, cover, appearance.dark) ? draw(id, item, cover) : 'next';
+ }
+
+ /** One cover. */
+ async function render(loaded: Renderer, id: string, item: RouteRecord | RideRecord, old: CoverRecord | undefined): Promise<'next' | 'stay'> {
+ const key = coverKey(item), tries = old?.lineKey === key ? old.tries : 0, controller = rendering = new AbortController();
+ const line = Array.from({ length: item.summary!.line.length / 2 }, (_, i) => [item.summary!.line[2 * i], item.summary!.line[2 * i + 1]] as [number, number]);
+ try {
+ const view = await loaded.view(line, when(item));
+ if (!view) {
+ await library.saveCover({ id, lineKey: key, state: 'none', tries: 0, ...old?.map && { map: old.map } });
+ return 'next';
+ }
+ if (controller.signal.aborted) return 'stay';
+ const { image, points, credits } = await loaded.still({ view, width: WIDTH, height: HEIGHT, line }, controller.signal);
+ await library.saveCover({ id, lineKey: key, state: 'done', image, points: pack(points!), credits, tries: 0 });
+ return 'next';
+ } catch (error) {
+ const name = error instanceof Error ? error.name : '';
+ if (name === 'aborted' || name === 'hidden') return 'stay';
+ console.info(`Cover of ${id}:`, error);
+ // The cover of an earlier line and the map picture stay.
+ await library.saveCover({ ...old, id, lineKey: key, state: tries + 1 >= MAX_TRIES ? 'failed' : 'waiting', tries: tries + 1 });
+ if (name === 'timeout') off = true;
+ // After a lost device, the next still asks for a new one.
+ return name === 'device-lost' ? 'stay' : 'next';
+ } finally {
+ rendering = undefined;
+ }
+ }
+
+ /** The map picture of the theme. */
+ async function draw(id: string, item: RouteRecord | RideRecord, old: CoverRecord | undefined): Promise<'next' | 'stay'> {
+ const key = lineKey(item), dark = appearance.dark, controller = drawing = new AbortController();
+ const map: MapPicture = old?.map?.lineKey === key ? old.map : { lineKey: key, tries: 0 };
+ // A record with a picture and no cover waits for a cover.
+ const cover: CoverRecord = old ?? { id, lineKey: coverKey(item), state: 'waiting', tries: 0 };
+ // The browser keeps a failed import until the page loads again, so it counts no try; the next ask tries again.
+ const make = await picture().catch((error: unknown) => void console.info('Map picture code:', error));
+ if (!make) return 'next';
+ try {
+ const made = await make(item.summary!, dark, controller.signal);
+ const next: MapPicture = made === 'none' ? { lineKey: key, tries: 0, none: true }
+ : { ...map, tries: 0, points: made.points, credits: made.credits, [dark ? 'dark' : 'light']: made.image };
+ await library.saveCover({ ...cover, map: next });
+ return 'next';
+ } catch (error) {
+ const name = error instanceof Error ? error.name : '';
+ if (name === 'aborted' || name === 'hidden') return 'stay';
+ console.info(`Map picture of ${id}:`, error);
+ await library.saveCover({ ...cover, map: { ...map, tries: map.tries + 1 } });
+ return 'next';
+ } finally {
+ drawing = undefined;
+ }
+ }
+
+ stops.push(library.onChange((store, id) => {
+ if (store !== 'routes') return;
+ clearTimeout(settling.get(id));
+ settling.set(id, setTimeout(async () => {
+ settling.delete(id);
+ // Only the planner's route: a restored backup changes many routes, and a row of a list asks for no cover.
+ if (await library.state('active') !== id) return;
+ const [item, cover] = await Promise.all([library.item(id), library.cover(id)]);
+ if (item?.summary && !settled(item, cover)) want(id, 'page');
+ }, SETTLE_MS));
+ }));
+ for (const [target, event] of [[document, 'visibilitychange'], [window, 'online']] as const) {
+ const listener = () => void pump();
+ target.addEventListener(event, listener);
+ stops.push(() => target.removeEventListener(event, listener));
+ }
+ for (const [id, place] of early.splice(0)) want(id, place);
+ return stop;
+}
+
+/** The time of a cover: the middle of a ride, or the day of the last change of a route at 10:00, sunny. */
+function when(item: RouteRecord | RideRecord): Pick {
+ const ride = 'key' in item, at = ride ? new Date((item.summary.start + item.summary.seconds / 2) * 1000) : new Date(item.updatedAt);
+ // Swedish writes a date and a time as YYYY-MM-DD HH:MM.
+ const [date, time] = new Intl.DateTimeFormat('sv-SE', { timeZone: TIME_ZONE, dateStyle: 'short', timeStyle: 'short' }).format(at).split(' ');
+ return { date, time: ride ? time : '10:00', weather: 'sunny' };
+}
+
+async function trailView(): Promise {
+ const [start, { canRenderStills, still }, { coverView }, { config }] = await Promise.all([
+ loadTrailView(), import('../trailview/still'), import('../trailview/still-view'), import('../planner/map-data'),
+ ]);
+ return {
+ canRender: () => canRenderStills(),
+ view: (line, conditions) => coverView(line, config, { width: WIDTH, height: HEIGHT, ...conditions }),
+ async still(job, signal) {
+ const gpu = await start.requestGpu();
+ if (!gpu) throw new Error('No WebGPU device.');
+ return still(gpu, config, job, { signal });
+ },
+ trailViewOpen: start.trailViewOpen,
+ onTrailViewOpen: start.onTrailViewOpen,
+ };
+}
+
+/** The map code loads at the first picture, so the shell does not load MapLibre at its start. */
+const mapPicture = () => import('./map-picture').then(module => module.mapPicture);
diff --git a/builder/web/src/lib/covers/line.test.ts b/builder/web/src/lib/covers/line.test.ts
new file mode 100644
index 0000000000..e35979df35
--- /dev/null
+++ b/builder/web/src/lib/covers/line.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from 'vitest';
+import type { Summary } from '../library/records';
+import { along, distanceAt, nearest, pack, runs } from './line';
+
+// Nine points 100 m apart on the equator. In the image they run along y = 0; point 6 has no place.
+const x = [0, 100, 110, 210, 220, 320, NaN, 400, 500];
+const visible = [1, 1, 0, 1, 0, 0, 0, 1, 1];
+const points = pack({
+ x: Float32Array.from(x), y: Float32Array.from(x, value => Number.isNaN(value) ? NaN : 0),
+ distance: Float32Array.from(x, (value, i) => Number.isNaN(value) ? NaN : 1000 * (i + 1)), visible: Uint8Array.from(visible),
+});
+const summary = {
+ line: x.flatMap((_, i) => [i * 0.001, 0]), heights: x.map(() => null), bounds: [0, 0, 0.008, 0],
+ lengthM: 800, climbM: 0, highestM: null, seconds: 0, bike: 'road',
+} satisfies Summary;
+
+describe('the line of a cover', () => {
+ it('keeps the distance from the eye to 5 %', () => {
+ for (const i of [0, 4, 8]) expect(Math.abs(distanceAt(points, i) / (1000 * (i + 1)) - 1)).toBeLessThan(0.05);
+ expect(distanceAt(points, 6)).toBeNaN();
+ });
+
+ it('joins a stretch of less than 16 pixels to the stretch before it, and has a gap at a point with no place', () => {
+ // The hidden 10 px at point 2 joins the visible stretch; the hidden 10 px at point 4 and the hidden 100 px after it make 110 px.
+ expect(runs(points)).toEqual([
+ { from: 0, to: 3, visible: true },
+ { from: 3, to: 5, visible: false },
+ { from: 7, to: 8, visible: true },
+ ]);
+ });
+
+ it('places the mark between two points, and none in the gap', () => {
+ expect(along(points, summary, 50)?.x).toBeCloseTo(50);
+ expect(along(points, summary, 150)?.x).toBeCloseTo(105);
+ expect(along(points, summary, 650)).toBeUndefined();
+ });
+
+ it('gives the metres along the route of the point nearest to the pointer', () => {
+ expect(nearest(points, summary, 105, 3)).toBeCloseTo(150);
+ expect(nearest(points, summary, 450, -20)).toBeCloseTo(750);
+ });
+
+ it('gives a place only for a pointer within the limit of the line, also of a hidden stretch', () => {
+ expect(nearest(points, summary, 270, 20, 24)).toBeCloseTo(450);
+ expect(nearest(points, summary, 270, 30, 24)).toBeUndefined();
+ });
+
+ it('keeps a segment to a point far beside the eye on its line', () => {
+ // From the middle of the image toward a point 10 million pixels away, down and to the right at 1 : 5.
+ const far = pack({ x: Float32Array.of(960, 960 + 1e7), y: Float32Array.of(640, 640 + 2e6), distance: Float32Array.of(5000, 10), visible: Uint8Array.of(1, 0) });
+ const at = along(far, { ...summary, line: [0, 0, 0.001, 0], heights: [null, null], lengthM: 1e7 }, 1000);
+ expect(at!.x).toBeCloseTo(1960, 0);
+ expect(at!.y).toBeCloseTo(840, 0);
+ });
+});
+
diff --git a/builder/web/src/lib/covers/line.ts b/builder/web/src/lib/covers/line.ts
new file mode 100644
index 0000000000..e957a3f298
--- /dev/null
+++ b/builder/web/src/lib/covers/line.ts
@@ -0,0 +1,81 @@
+/** Reads the point list of a cover: the stretches of the line that show, the place of the mark and the point under the pointer. */
+import type { CoverPoints, Summary } from '../library/records';
+import { kilometres } from '../planner/geo';
+import type { StillPoints } from '../trailview/still';
+
+/** A visible or a hidden stretch shorter than this, in pixels of the image, joins the stretch before it, so the edge of a ridge does not cut the line into dashes. */
+const JOIN_PX = 16;
+/** Distance code c of 1 to 127 is NEAREST_M · 2^((c − 1) / STEPS) metres: 9 % for each step, from 10 m to 550 km. */
+const NEAREST_M = 10, STEPS = 8, VISIBLE = 128;
+
+export function pack({ x, y, distance, visible }: StillPoints): CoverPoints {
+ // Floats keep a point far outside the image on its line: a clamp of each axis would turn the segment to it.
+ const points = { x: Float32Array.from(x), y: Float32Array.from(y), eye: new Uint8Array(x.length) };
+ for (let i = 0; i < x.length; i++) {
+ if (![x[i], y[i], distance[i]].every(Number.isFinite)) continue;
+ const code = 1 + Math.round(STEPS * Math.log2(Math.max(distance[i], NEAREST_M) / NEAREST_M));
+ points.eye[i] = Math.min(code, 127) | (visible[i] ? VISIBLE : 0);
+ }
+ return points;
+}
+
+export const placed = (points: CoverPoints, i: number) => (points.eye[i] & 127) !== 0;
+export const visibleAt = (points: CoverPoints, i: number) => points.eye[i] >= VISIBLE;
+/** Metres from the eye, NaN for a point with no place. */
+export const distanceAt = (points: CoverPoints, i: number) => placed(points, i) ? NEAREST_M * 2 ** (((points.eye[i] & 127) - 1) / STEPS) : NaN;
+
+/** The points `from` to `to` of the line. A segment is visible when its end point is. Two runs that follow each other share a point. */
+export interface Run { from: number; to: number; visible: boolean }
+
+/** The visible and the hidden stretches, after the rule of JOIN_PX. A point with no place ends a stretch, and the line has a gap there. */
+export function runs(points: CoverPoints): Run[] {
+ const segments: (Run & { px: number })[] = [];
+ for (let i = 1; i < points.x.length; i++) {
+ if (!placed(points, i - 1) || !placed(points, i)) continue;
+ const visible = visibleAt(points, i), px = Math.hypot(points.x[i] - points.x[i - 1], points.y[i] - points.y[i - 1]), last = segments.at(-1);
+ if (last?.to === i - 1 && last.visible === visible) { last.to = i; last.px += px; }
+ else segments.push({ from: i - 1, to: i, visible, px });
+ }
+ const joined: typeof segments = [];
+ for (const run of segments) {
+ const last = joined.at(-1);
+ if (last?.to === run.from && (run.px < JOIN_PX || run.visible === last.visible)) { last.to = run.to; last.px += run.px; }
+ else joined.push(run);
+ }
+ return joined.map(({ from, to, visible }) => ({ from, to, visible }));
+}
+
+/** The metres along the route at each point of the summary line, from 0 to `lengthM`: the simplified line is shorter than the route. */
+export function metresAlong({ line, lengthM }: Summary): Float64Array {
+ const metres = new Float64Array(line.length / 2);
+ for (let i = 1; i < metres.length; i++) metres[i] = metres[i - 1] + kilometres(line.slice(2 * i - 2, 2 * i), line.slice(2 * i, 2 * i + 2));
+ const scale = metres.at(-1)! > 0 ? lengthM / metres.at(-1)! : 0;
+ return metres.map(m => m * scale);
+}
+
+/** The place in the image of the point `metres` along the route, or undefined where the line has a gap. It is visible
+ * when its segment is. */
+export function along(points: CoverPoints, summary: Summary, metres: number): { x: number; y: number; distance: number; visible: boolean } | undefined {
+ const at = metresAlong(summary);
+ let i = 1;
+ while (i < at.length - 1 && at[i] < metres) i++;
+ if (!placed(points, i - 1) || !placed(points, i)) return undefined;
+ const t = at[i] > at[i - 1] ? Math.max(0, Math.min(1, (metres - at[i - 1]) / (at[i] - at[i - 1]))) : 0;
+ const mix = (a: number, b: number) => a + t * (b - a);
+ return { x: mix(points.x[i - 1], points.x[i]), y: mix(points.y[i - 1], points.y[i]), distance: mix(distanceAt(points, i - 1), distanceAt(points, i)), visible: visibleAt(points, i) };
+}
+
+/** The metres along the route of the point of the line that is nearest to pixel (x, y) of the image; undefined when no
+ * segment has a place within `within` pixels of the image. A hidden stretch counts as line. */
+export function nearest(points: CoverPoints, summary: Summary, x: number, y: number, within = Infinity): number | undefined {
+ const at = metresAlong(summary);
+ let best: number | undefined, closest = Infinity;
+ for (let i = 1; i < at.length; i++) {
+ if (!placed(points, i - 1) || !placed(points, i)) continue;
+ const ax = points.x[i - 1], ay = points.y[i - 1], dx = points.x[i] - ax, dy = points.y[i] - ay, length = dx * dx + dy * dy;
+ const t = length ? Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / length)) : 0;
+ const away = (ax + t * dx - x) ** 2 + (ay + t * dy - y) ** 2;
+ if (away < closest) [closest, best] = [away, at[i - 1] + t * (at[i] - at[i - 1])];
+ }
+ return closest <= within * within ? best : undefined;
+}
diff --git a/builder/web/src/lib/covers/map-picture.ts b/builder/web/src/lib/covers/map-picture.ts
new file mode 100644
index 0000000000..4c9b95fb7b
--- /dev/null
+++ b/builder/web/src/lib/covers/map-picture.ts
@@ -0,0 +1,82 @@
+/** Draws a still picture of the planner map around the line of a route, with no labels, for a card with no cover. */
+import * as maplibregl from 'maplibre-gl';
+import type { CoverPoints, Summary } from '../library/records';
+import { creditsWith, styleConfig, useMapProtocols } from '../planner/map-setup';
+import { mapStyle } from '../planner/map-style';
+import type { StillFailure } from '../trailview/still';
+import { pack } from './line';
+
+const PICTURE_WIDTH = 768, PICTURE_HEIGHT = 512;
+/** The line fits inside the middle 720 × 300 pixels, the band that `crop` shows in each box from 3:2 to 2.2:1. */
+const PADDING = { top: 106, bottom: 106, left: 24, right: 24 };
+/** A short loop keeps the tiles of the basemap. */
+const MAX_ZOOM = 13;
+/** Chosen, not measured: well above the time of a picture of a long route on a slow link. */
+const TIMEOUT_MS = 20_000;
+const QUALITY = 0.85;
+/** The layers of the planner map that are no part of a picture, besides each layer of text and icons. */
+const LEFT_OUT = new Set(['contour-lines', 'planner-pois']);
+
+export interface MapPictureResult { image: Blob; points: CoverPoints; credits: string[] }
+export type MapPictureMaker = (summary: Summary, dark: boolean, signal: AbortSignal) => Promise;
+
+const failure = (name: StillFailure, message: string) => Object.assign(new Error(message), { name });
+
+/** The picture of the map at its zoom, or `none` when the line is outside the map data. It fails with the names of `still`. */
+export const mapPicture: MapPictureMaker = async (summary, dark, signal) => {
+ const [west, south, east, north] = summary.bounds, data = styleConfig.bounds;
+ if (west > data[2] || east < data[0] || south > data[3] || north < data[1]) return 'none';
+ useMapProtocols();
+ const container = document.createElement('div');
+ container.style.cssText = `position: fixed; top: 0; left: 0; width: ${PICTURE_WIDTH}px; height: ${PICTURE_HEIGHT}px; visibility: hidden; pointer-events: none`;
+ document.body.append(container);
+ const done = new AbortController();
+ let map: maplibregl.Map | undefined;
+ try {
+ return await new Promise((resolve, reject) => {
+ const fail = (name: StillFailure, message: string) => reject(failure(name, message));
+ const timer = setTimeout(() => fail('timeout', `The map picture took more than ${TIMEOUT_MS} ms.`), TIMEOUT_MS);
+ done.signal.addEventListener('abort', () => clearTimeout(timer));
+ // A hidden page draws no frame.
+ const hidden = () => document.hidden && fail('hidden', 'The page became hidden.');
+ const aborted = () => signal.aborted && fail('aborted', 'The map picture was aborted.');
+ hidden();
+ aborted();
+ if (document.hidden || signal.aborted) return;
+ document.addEventListener('visibilitychange', hidden, { signal: done.signal });
+ signal.addEventListener('abort', aborted, { signal: done.signal });
+ map = new maplibregl.Map({
+ container, style: style(dark), bounds: [west, south, east, north], fitBoundsOptions: { padding: PADDING },
+ pixelRatio: 1, canvasContextAttributes: { preserveDrawingBuffer: true }, interactive: false, fadeDuration: 0,
+ maxZoom: MAX_ZOOM, attributionControl: false, renderWorldCopies: false,
+ });
+ map.on('error', event => !('name' in event.error && event.error.name === 'AbortError') && fail('tiles-failed', `A tile of the map picture failed: ${event.error?.message}`));
+ map.once('idle', () => {
+ const n = summary.line.length / 2, x = new Float32Array(n), y = new Float32Array(n);
+ for (let i = 0; i < n; i++) ({ x: x[i], y: y[i] } = map!.project([summary.line[2 * i], summary.line[2 * i + 1]]));
+ // One distance gives the line one width, as on a cover seen from above.
+ const points = pack({ x, y, distance: new Float32Array(n).fill(1000), visible: new Uint8Array(n).fill(1) });
+ encode(map!.getCanvas()).then(image => resolve({ image, points, credits: creditsWith([]) }), reject);
+ });
+ });
+ } finally {
+ done.abort();
+ // Releases the WebGL context.
+ map?.remove();
+ container.remove();
+ }
+};
+
+/** The planner map in the theme, with no text, icons, contour lines or places. */
+function style(dark: boolean): maplibregl.StyleSpecification {
+ const full = mapStyle(dark ? 'dark' : 'light', styleConfig, styleConfig.terrain, '');
+ const { basemap, terrain } = full.sources;
+ return { version: 8, sources: { basemap, terrain }, layers: full.layers.filter(layer => layer.type !== 'symbol' && !LEFT_OUT.has(layer.id)) };
+}
+
+async function encode(canvas: HTMLCanvasElement): Promise {
+ const blob = (type: string) => new Promise((resolve, reject) => canvas.toBlob(made => made ? resolve(made) : reject(new Error('The map picture has no image.')), type, QUALITY));
+ // A browser that cannot encode a type gives PNG.
+ const webp = await blob('image/webp');
+ return webp.type === 'image/webp' ? webp : blob('image/jpeg');
+}
diff --git a/builder/web/src/lib/covers/testdata/cover.json b/builder/web/src/lib/covers/testdata/cover.json
new file mode 100644
index 0000000000..f0a8bcc314
--- /dev/null
+++ b/builder/web/src/lib/covers/testdata/cover.json
@@ -0,0 +1 @@
+{"summary":{"lengthM":30117,"climbM":83,"seconds":5733,"bike":"touring","days":1,"line":[8.40438,46.82221,8.40484,46.822,8.40464,46.8213,8.40269,46.8203,8.40131,46.81999,8.39673,46.81987,8.39271,46.82011,8.39254,46.81954,8.38791,46.81982,8.38752,46.81947,8.38647,46.81968,8.3852,46.81912,8.38439,46.8193,8.38363,46.82026,8.38249,46.82101,8.37966,46.82204,8.37908,46.82211,8.37876,46.82198,8.37795,46.82113,8.37651,46.82154,8.37609,46.82179,8.37647,46.82175,8.37614,46.82232,8.37648,46.8232,8.37614,46.82605,8.3764,46.82673,8.37521,46.82772,8.37421,46.82954,8.37415,46.83002,8.3747,46.83003,8.37485,46.83049,8.37393,46.83185,8.37311,46.83212,8.37222,46.83288,8.3716,46.83295,8.37026,46.83473,8.37,46.83574,8.37075,46.83688,8.37108,46.8379,8.3702,46.83977,8.37083,46.84005,8.37132,46.84185,8.37295,46.84305,8.37237,46.84334,8.37189,46.84392,8.3719,46.84491,8.37108,46.84554,8.37023,46.84581,8.36991,46.84635,8.36934,46.84669,8.36962,46.84844,8.36905,46.8489,8.36904,46.84929,8.36874,46.84969,8.36909,46.85016,8.37042,46.85092,8.37133,46.85169,8.37113,46.85184,8.37127,46.85245,8.37185,46.85333,8.37112,46.85428,8.37111,46.85594,8.37134,46.85639,8.37113,46.85859,8.37106,46.85875,8.37038,46.8589,8.36986,46.85955,8.37034,46.85957,8.371,46.86211,8.37025,46.86509,8.36962,46.86563,8.36936,46.86609,8.36947,46.86637,8.37016,46.86663,8.36962,46.86776,8.36988,46.86907,8.3698,46.86989,8.36932,46.86999,8.37,46.87173,8.3717,46.87355,8.37309,46.87453,8.37264,46.87478,8.37278,46.87498,8.37344,46.87489,8.37394,46.87547,8.37423,46.87606,8.37412,46.87716,8.37451,46.87851,8.37518,46.87912,8.37652,46.88368,8.37726,46.88546,8.3786,46.88534,8.37954,46.88506,8.37977,46.88514,8.38036,46.88597,8.38164,46.88897,8.38278,46.89019,8.38625,46.89492,8.38907,46.89756,8.39093,46.89961,8.39134,46.90182,8.39295,46.90469,8.39412,46.90761,8.39409,46.9095,8.39379,46.91071,8.39416,46.91155,8.39416,46.91318,8.39294,46.9153,8.39288,46.917,8.39324,46.91828,8.39497,46.92089,8.39578,46.92166,8.39637,46.92257,8.39655,46.92372,8.39626,46.92538,8.39575,46.92566,8.39446,46.92817,8.39275,46.92978,8.39113,46.93091,8.39062,46.93339,8.39074,46.93684,8.38997,46.94247,8.38901,46.94379,8.38597,46.94578,8.3835,46.94805,8.38263,46.94834,8.38037,46.95001,8.37928,46.95041,8.37824,46.95107,8.37758,46.95297,8.37654,46.95384,8.37647,46.9541,8.37178,46.95403,8.37101,46.95492,8.36922,46.9558,8.36621,46.95616,8.36565,46.9558,8.36535,46.95578,8.3651,46.95631,8.36516,46.95653,8.36545,46.95662,8.36499,46.95711,8.36405,46.95777,8.36223,46.95854,8.36199,46.95878,8.36197,46.95963,8.36214,46.95972,8.36138,46.96073,8.36086,46.96053,8.35907,46.96083,8.35963,46.96246,8.35824,46.96308,8.35803,46.963,8.35725,46.96332,8.35734,46.96343,8.3555,46.96318,8.3551,46.96335,8.35503,46.96368,8.35394,46.96505,8.35366,46.9661,8.35331,46.96649,8.35256,46.96686,8.34862,46.96793,8.3458,46.96898,8.34505,46.96911,8.34349,46.96908,8.34252,46.97019,8.33885,46.96994,8.33822,46.9733,8.33777,46.97335,8.33739,46.97452,8.33638,46.97543,8.33518,46.97623,8.33322,46.97715,8.33297,46.97796,8.3333,46.97863,8.3336,46.97875,8.33419,46.97868,8.33433,46.97836,8.33458,46.9783,8.33492,46.97861,8.33721,46.97959,8.33755,46.97956,8.33744,46.97974,8.33755,46.97956,8.33721,46.97959,8.33492,46.97861,8.33343,46.9787,8.33298,46.97786,8.33322,46.97715,8.33585,46.97584,8.33739,46.97452,8.33777,46.97335,8.33822,46.9733,8.33885,46.96994,8.34252,46.97019,8.34349,46.96908,8.34505,46.96911,8.3458,46.96898,8.34862,46.96793,8.35281,46.96674,8.35363,46.96616,8.35394,46.96505,8.35503,46.96368,8.3551,46.96335,8.3555,46.96318,8.35728,46.96344,8.35725,46.96332,8.35803,46.963,8.35824,46.96308,8.35891,46.9628,8.35885,46.9627,8.35955,46.96237,8.35907,46.96083,8.36086,46.96053,8.36138,46.96073,8.36201,46.95986,8.36199,46.95878,8.36223,46.95854,8.36313,46.95808,8.36378,46.95873,8.36414,46.95858,8.36447,46.95889,8.36522,46.95841,8.36586,46.95729,8.36613,46.95712],"heights":[1011,1010,1004,1000,999,997,995,994,993,992,994,1001,1005,1001,994,977,972,969,956,946,943,939,929,911,860,847,823,789,782,777,772,754,746,742,740,713,703,693,688,672,672,678,674,673,669,657,651,650,649,643,628,626,625,622,618,614,612,611,608,606,602,599,597,592,592,592,594,592,583,578,576,575,575,574,571,568,567,567,564,560,561,565,565,564,563,563,563,552,550,544,542,541,540,540,539,535,533,527,523,522,518,515,512,510,509,510,506,504,502,502,501,500,501,500,499,500,498,493,488,484,479,473,470,467,463,463,460,460,460,458,457,457,463,464,462,460,464,465,463,461,460,457,456,455,454,449,449,448,447,446,446,445,445,445,445,444,444,444,443,442,442,441,439,438,438,437,437,435,435,435,435,435,435,435,435,435,435,436,437,436,435,435,435,435,435,435,436,435,435,435,435,435,435,435,435,437,437,438,438,439,441,442,443,444,444,444,445,445,445,445,446,446,446,446,447,448,448,454,455,455,450,450,450,450,451,451],"bounds":[8.332968,46.819118,8.404866,46.979741],"highestM":1011},"points":{"x":[29,28,28,32,35,43,50,50,58,58,60,62,63,65,67,72,73,73,74,77,78,77,78,77,79,78,81,83,83,82,82,84,86,87,88,91,92,91,91,93,92,92,89,90,91,92,93,95,96,97,97,98,98,99,98,96,95,95,95,95,96,97,97,98,98,99,100,100,99,102,103,104,104,103,104,104,105,106,105,103,100,101,101,99,99,98,99,99,97,96,95,92,90,89,88,86,84,76,69,65,64,60,56,57,58,57,57,62,62,61,55,52,50,49,51,53,58,66,73,76,77,84,89,106,120,124,137,143,149,156,162,163,184,190,200,214,215,216,219,219,218,222,228,238,240,243,242,249,250,259,263,271,272,276,276,282,285,286,297,303,306,311,331,347,351,356,366,377,400,402,412,421,431,444,452,456,457,454,451,450,451,453,451,453,451,453,451,457,451,444,426,412,402,400,377,366,356,351,347,331,309,303,297,286,285,282,277,276,272,271,267,267,263,259,250,249,243,240,238,233,232,230,230,225,219,217],"y":[38,38,38,37,37,36,36,36,35,35,35,34,34,34,35,35,35,35,34,35,35,35,35,36,38,39,39,41,41,41,41,42,43,43,43,44,44,45,46,47,47,48,49,49,50,50,51,51,51,51,52,53,53,53,53,54,55,55,55,56,56,58,58,59,59,59,60,60,62,64,64,64,64,65,65,66,67,67,68,70,72,72,72,72,73,73,74,75,76,81,83,83,83,84,85,88,90,97,102,105,109,114,119,122,124,126,129,132,135,138,145,148,150,153,157,157,162,165,166,173,184,203,207,210,216,215,219,219,220,227,229,231,221,224,225,221,219,218,220,221,222,224,225,225,226,230,231,234,232,230,239,240,239,239,240,235,235,237,241,246,248,248,246,245,244,241,245,236,253,252,258,261,263,263,268,273,274,275,274,274,277,289,290,291,290,289,277,274,267,263,262,258,252,253,236,245,241,244,245,246,248,247,241,237,235,235,240,239,239,240,240,239,239,230,232,234,231,226,225,225,229,229,231,230,226,226],"eye":[88,88,88,88,88,88,88,88,88,88,88,88,216,216,216,216,216,216,216,216,216,216,216,216,215,215,215,87,87,87,87,87,87,215,215,215,215,215,214,214,214,214,214,214,214,214,214,214,214,214,214,214,214,214,214,213,213,213,213,213,213,213,213,213,213,213,213,213,212,212,212,212,212,212,212,212,212,84,84,83,211,211,211,211,211,211,211,211,211,82,82,210,210,210,210,82,210,209,209,209,208,208,208,207,207,207,207,207,206,206,206,206,206,205,205,205,205,204,204,204,203,202,202,202,201,201,201,201,201,200,200,200,200,200,200,200,200,200,200,200,72,200,200,200,200,200,200,200,200,200,199,199,199,199,199,200,200,200,200,199,199,199,200,200,200,200,200,73,201,201,201,201,201,201,201,201,201,201,201,201,201,200,200,200,200,200,201,201,201,201,201,201,201,201,73,200,200,200,200,200,199,199,200,200,200,200,199,199,199,199,199,199,199,200,200,200,200,200,200,200,72,200,200,200,200,200]}}
\ No newline at end of file
diff --git a/builder/web/src/lib/covers/testdata/cover.webp b/builder/web/src/lib/covers/testdata/cover.webp
new file mode 100644
index 0000000000..1675c046ff
Binary files /dev/null and b/builder/web/src/lib/covers/testdata/cover.webp differ
diff --git a/builder/web/src/lib/desktop/invoke.ts b/builder/web/src/lib/desktop/invoke.ts
deleted file mode 100644
index f9eda97fd9..0000000000
--- a/builder/web/src/lib/desktop/invoke.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-// The desktop host's transport: Tauri commands. Only the desktop platform and
-// native device/library adapters import it, so it never reaches the other two
-// bundles.
-//
-// Every function here is one `invoke()`. The names are the Rust command names in
-// builder/desktop/src/main.rs, and the argument shapes are what serde deserializes
-// there; that is the whole contract, and it is worth keeping in one file so a rename
-// is one place on each side.
-
-import { invoke, type Channel } from "@tauri-apps/api/core";
-
-/** The catalog manifest, plus the URL relative references resolve against. */
-export interface FetchedCatalog {
- url: string;
- body: string;
-}
-
-export interface OpenedMapOutput {
- id: number;
- path: string;
-}
-
-// The Rust side moves bytes and nothing else; the protocol is the TS client, the same
-// one the hosted site runs. See builder/desktop/src/usb/ for the plane split and why
-// the two binary calls below do not go through JSON.
-
-/** Which endpoint pair a call means — `DeviceLink`'s two members, by name. */
-export type UsbPlane = "control" | "bulk";
-/** Which half of a pair to cancel. Omitted means both. */
-export type UsbDir = "in" | "out";
-
-/** A device the backend is willing to open. `id` is opaque: never parse it. */
-export interface UsbDeviceSummary {
- id: string;
- vendorId: number;
- productId: number;
- product: string | null;
- serialNumber: string | null;
-}
-
-/** Hot-plug, as the backend reports it. `watchFailed` is not a device problem — it
- * means the OS notification stream itself is gone, and a watch that died quietly is
- * indistinguishable from "nothing is ever plugged in". */
-export type UsbEvent =
- | { type: "connected"; device: UsbDeviceSummary }
- | { type: "disconnected"; id: string }
- | { type: "watchFailed"; message: string };
-
-/** What `usb_open` hands back: the handle every later call carries, plus the two
- * planes' packet sizes. */
-export interface UsbLinkInfo {
- handle: number;
- deviceId: string;
- interfaceNumber: number;
- controlPacketSize: number;
- bulkPacketSize: number;
- product: string | null;
- serialNumber: string | null;
-}
-
-/** A transport failure in `PipeError`'s own vocabulary. Tauri rejects with the
- * serialized `Err` value, so this arrives as a plain object rather than an `Error`. */
-export interface UsbFault {
- code: string;
- message: string;
-}
-
-export const desktop = {
- catalog: () => invoke("catalog"),
- /** Raw response path: catalog cells can be hundreds of MB, so a JSON byte array is
- * not an acceptable transport. Rust restricts this to the configured catalog
- * origin. */
- catalogGet: (url: string) => invoke("catalog_get", { url }),
- mapOutputBegin: (name: string) => invoke("map_output_begin", { name }),
- mapOutputWrite: (id: number, name: string, bytes: Uint8Array) =>
- invoke("map_output_write", bytes, {
- headers: { "output-id": String(id), filename: name },
- }),
- mapOutputFinish: (id: number) => invoke("map_output_finish", { id }),
- mapOutputDiscard: (id: number) => invoke("map_output_discard", { id }),
-
- revealFile: (path: string) => invoke("reveal_file", { path }),
-
- usbWatch: (onEvent: Channel) => invoke("usb_watch", { onEvent }),
- usbList: () => invoke("usb_list"),
- usbOpen: (deviceId: string) => invoke("usb_open", { deviceId }),
- usbClose: (handle: number) => invoke("usb_close", { handle }),
-
- /** One transfer off a plane's IN endpoint. Resolves to an `ArrayBuffer`: the
- * command returns `tauri::ipc::Response`, which is Tauri's raw path. */
- usbRead: (handle: number, plane: UsbPlane) => invoke("usb_read", { handle, plane }),
-
- /**
- * One transfer onto a plane's OUT endpoint.
- *
- * The bytes are the *whole* invoke body — that is what makes them raw rather than a
- * JSON array of numbers, roughly 4 bytes of text per byte — so the handle and the
- * plane have nowhere to go but headers.
- */
- usbWrite: (handle: number, plane: UsbPlane, bytes: Uint8Array) =>
- invoke("usb_write", bytes, { headers: { handle: String(handle), plane } }),
-
- usbCancel: (handle: number, plane: UsbPlane, dir?: UsbDir) =>
- invoke("usb_cancel", { handle, plane, dir: dir ?? null }),
- usbReset: (handle: number, plane: UsbPlane) => invoke("usb_reset", { handle, plane }),
-
- // `ridesImport` is the one command in this file whose *timing* is part of a
- // contract: it resolves after the ride object, the GPX and the index have each been
- // fsynced, which is what makes `PullReport` true. See builder/desktop/src/rides.rs.
-
- ridesIndex: () => invoke("rides_index"),
- ridesImport: (request: RideImportRequest) => invoke("rides_import", { request }),
- /** The stored ride object. Raw, like `usbRead` — a JSON number array would be 4× the bytes. */
- ridesRead: (key: string) => invoke("rides_read", { key }),
- ridesWriteGpx: (key: string, gpx: string) => invoke("rides_write_gpx", { key, gpx }),
- /** Opens the OS folder chooser and moves the library. `null` when it was dismissed. */
- ridesChooseFolder: () => invoke("rides_choose_folder"),
-};
-
-// Field for field what `serde` reads and writes in builder/desktop/src/rides.rs.
-// `lib/device/library.ts` owns the app-facing shapes; these are the wire ones.
-// StoreId is full lowercase hex; ObjectId is a decimal u64 string, to keep JSON
-// precision.
-
-export interface RideIndexEntry {
- key: string;
- serial: string;
- storeId: string;
- objectId: string;
- name: string;
- startTime: number;
- distanceM: number;
- movingTimeS: number;
- climbM: number;
- points: number;
- bytes: number;
- crc32: number;
- importedAt: number;
- /** Basenames — what the index stores, because the folder can move. */
- rideFile: string;
- gpxFile: string;
- track: Array<[number, number]>;
- /** The basenames joined to the current folder, by the side that owns a path separator. */
- ridePath: string;
- gpxPath: string;
- /** Recomputed against the filesystem on every read, never trusted from the index. */
- present: boolean;
- gpxPresent: boolean;
-}
-
-export interface RideIndexView {
- folder: string;
- isDefault: boolean;
- rides: RideIndexEntry[];
-}
-
-export interface RideImportRequest {
- serial: string;
- storeId: string;
- objectId: string;
- name: string;
- startTime: number;
- distanceM: number;
- movingTimeS: number;
- climbM: number;
- points: number;
- crc32: number;
- track: Array<[number, number]>;
- object: number[];
- gpx: string;
-}
-
-export interface RideImported {
- ride: RideIndexEntry;
- imported: boolean;
-}
diff --git a/builder/web/src/lib/desktop/library.test.ts b/builder/web/src/lib/desktop/library.test.ts
deleted file mode 100644
index b1dc655edb..0000000000
--- a/builder/web/src/lib/desktop/library.test.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-import { openRideLibrary } from "./library";
-import { desktop, type RideIndexEntry } from "./invoke";
-
-vi.mock("./invoke", () => ({
- desktop: { ridesIndex: vi.fn(), ridesImport: vi.fn() },
-}));
-
-describe("desktop ride identity at the JSON boundary", () => {
- it("uses decimal strings in both directions and bigint in the library", async () => {
- const library = openRideLibrary();
- for (const storeId of ["a1b2c3d4000000000000000000000000", "a1b2c3d4000000000000000000000001"]) {
- for (const objectId of [65536n, 9007199254740993n, 18446744073709551615n]) {
- const key = `OBC-24-000317:${storeId}:${objectId}`;
- const entry: RideIndexEntry = {
- key, serial: "OBC-24-000317", storeId, objectId: objectId.toString(),
- name: "Ride", startTime: 0, distanceM: 0, movingTimeS: 0, climbM: 0,
- points: 1, bytes: 3, crc32: 0, importedAt: 1,
- rideFile: "ride.obcride", gpxFile: "ride.gpx",
- ridePath: "/archive/ride.obcride", gpxPath: "/rides/ride.gpx",
- track: [], present: true, gpxPresent: true,
- };
- vi.mocked(desktop.ridesImport).mockImplementation(async (request) => {
- const json = JSON.parse(JSON.stringify(request));
- expect(json.storeId).toBe(storeId);
- expect(json.objectId).toBe(objectId.toString());
- return JSON.parse(JSON.stringify({ ride: entry, imported: true }));
- });
- const imported = await library.import({
- ...entry, objectId, object: new Uint8Array([1, 2, 3]), gpx: " ",
- });
- expect(imported.ride.key).toBe(key);
- expect(imported.ride.storeId).toBe(storeId);
- expect(imported.ride.objectId).toBe(objectId);
-
- vi.mocked(desktop.ridesIndex).mockResolvedValue(
- JSON.parse(JSON.stringify({ folder: "/rides", isDefault: true, rides: [entry] })),
- );
- expect((await library.view()).rides[0]).toEqual(imported.ride);
- }
- }
- });
-});
diff --git a/builder/web/src/lib/desktop/library.ts b/builder/web/src/lib/desktop/library.ts
deleted file mode 100644
index 82657202e3..0000000000
--- a/builder/web/src/lib/desktop/library.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-/**
- * The desktop host's ride library: `lib/device/library.ts`'s {@link RideLibrary} over six Tauri
- * commands.
- *
- * Deliberately thin. Everything that decides whether this feature is correct is in
- * `lib/device/library.ts`, over this interface, where it is tested against a fake that is not a mock
- * of these calls. What lives here is the translation between the app's shapes and `serde`'s, and one
- * decision worth stating:
- *
- * **`import()` is awaited for its timing, not just its value.** The Rust side writes the ride
- * object, the GPX and the index, fsyncing each and the directory entry, and only then resolves.
- * Nothing here may be made "fire and forget" for responsiveness — that would turn a durability
- * predicate into an optimistic one, which is the single way this feature can lose a rider's ride.
- */
-
-import { desktop, type RideIndexEntry } from "./invoke";
-import type { LibraryRide, LibraryView, RideImport, RideLibrary } from "../device/library";
-
-/**
- * `RideIndexEntry` → `LibraryRide`.
- *
- * Convert the JSON decimal ObjectId to bigint. The wire carries `rideFile`/`gpxFile` as *basenames*
- * plus the joined absolute paths, because a basename is what the index stores — the GPX folder can
- * move — and a path is what `reveal()` needs, and joining them in JavaScript would have to guess a
- * path separator. The two paths point at different roots: `ridePath` into the internal archive under
- * app data, `gpxPath` into the visible folder.
- */
-function toRide(entry: RideIndexEntry): LibraryRide {
- return {
- key: entry.key,
- serial: entry.serial,
- storeId: entry.storeId,
- objectId: BigInt(entry.objectId),
- name: entry.name,
- startTime: entry.startTime,
- distanceM: entry.distanceM,
- movingTimeS: entry.movingTimeS,
- climbM: entry.climbM,
- points: entry.points,
- bytes: entry.bytes,
- crc32: entry.crc32,
- importedAt: entry.importedAt,
- ridePath: entry.ridePath,
- gpxPath: entry.gpxPath,
- track: entry.track,
- present: entry.present,
- gpxPresent: entry.gpxPresent,
- };
-}
-
-export function openRideLibrary(): RideLibrary {
- return {
- async view(): Promise {
- const view = await desktop.ridesIndex();
- return {
- folder: view.folder,
- isDefault: view.isDefault,
- rides: view.rides.map(toRide),
- };
- },
-
- async import(ride: RideImport) {
- const landed = await desktop.ridesImport({
- serial: ride.serial,
- storeId: ride.storeId,
- objectId: ride.objectId.toString(),
- name: ride.name,
- startTime: ride.startTime,
- distanceM: ride.distanceM,
- movingTimeS: ride.movingTimeS,
- climbM: ride.climbM,
- points: ride.points,
- crc32: ride.crc32,
- track: ride.track.map((p) => [p[0], p[1]] as [number, number]),
- // The one place this host pays the JSON tax on binary. A ride object is hundreds of
- // kilobytes, written exactly once per ride, behind a transfer that already took
- // longer than the encode will.
- object: Array.from(ride.object),
- gpx: ride.gpx,
- });
- return { ride: toRide(landed.ride), imported: landed.imported };
- },
-
- // USB carries no possession acknowledgement: it changes no object, so it keeps the BLE
- // surface it had.
-
- async readObject(key: string): Promise {
- return new Uint8Array(await desktop.ridesRead(key));
- },
-
- writeGpx: (key: string, gpx: string) => desktop.ridesWriteGpx(key, gpx),
- reveal: (path: string) => desktop.revealFile(path),
- chooseFolder: () => desktop.ridesChooseFolder(),
- };
-}
diff --git a/builder/web/src/lib/desktop/release.test.ts b/builder/web/src/lib/desktop/release.test.ts
deleted file mode 100644
index b679ed8f0f..0000000000
--- a/builder/web/src/lib/desktop/release.test.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-// A ratchet, not a test of today: `RELEASE` is null until the first installers are
-// published, so the body below runs zero assertions right now — on
-// purpose. The moment there is a build, these are the things that have to be
-// true of it, and a missing checksum or a placeholder URL fails here instead of
-// on someone's machine. The one assertion that always runs pins that the page
-// has an honest empty state to fall back on.
-
-import { describe, expect, it } from "vitest";
-import { RELEASE } from "./release";
-
-describe("the desktop release", () => {
- it("either exists or is null — never a half-filled record", () => {
- expect(RELEASE === null || typeof RELEASE === "object").toBe(true);
- });
-
- it("offers a real, checksummed file per platform", () => {
- if (!RELEASE) return;
- expect(RELEASE.version).toMatch(/\S/);
- expect(RELEASE.date).toMatch(/^\d{4}-\d{2}-\d{2}$/);
- expect(RELEASE.downloads.length).toBeGreaterThan(0);
-
- const seen = new Set();
- for (const file of RELEASE.downloads) {
- expect(file.url).toMatch(/^https:\/\//);
- expect(file.filename).toMatch(/\S/);
- expect(file.size).toBeGreaterThan(0);
- expect(file.sha256).toMatch(/^[0-9a-f]{64}$/);
- const key = `${file.os} ${file.arch ?? ""}`;
- expect(seen.has(key)).toBe(false);
- seen.add(key);
- }
- });
-
- it("writes the install note as instructions, not an apology", () => {
- if (!RELEASE?.installNote) return;
- expect(RELEASE.installNote).not.toMatch(/!|sorry|unfortunately|afraid|apolog/i);
- });
-});
diff --git a/builder/web/src/lib/desktop/release.ts b/builder/web/src/lib/desktop/release.ts
deleted file mode 100644
index fafef277f2..0000000000
--- a/builder/web/src/lib/desktop/release.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-// What the desktop page offers to download. Until the installers are built,
-// signed and published, `RELEASE` is null and the page says there are no builds
-// yet rather than linking at files that do not exist. Inventing a URL now would
-// cost a visitor a 404 and cost us the one thing the page is for.
-
-export interface DesktopDownload {
- readonly os: "macOS" | "Windows" | "Linux";
- /** Only where one OS ships more than one build (`Apple silicon`, `x86-64`). */
- readonly arch?: string;
- readonly filename: string;
- readonly url: string;
- /** Bytes, for the size shown next to the button. */
- readonly size: number;
- /** Lowercase hex, 64 chars. Shown in full: a checksum you have to expand to
- * read is a checksum nobody checks. */
- readonly sha256: string;
-}
-
-export interface DesktopRelease {
- readonly version: string;
- /** ISO date, `YYYY-MM-DD`. */
- readonly date: string;
- readonly downloads: readonly DesktopDownload[];
- /**
- * Set only if D3 ships unsigned builds, and written as **instructions**:
- * what to click, in what order, in the imperative. "Right-click the app and
- * choose Open, then confirm" — not "unfortunately macOS will warn you that
- * …". The page renders it under a *First run* heading, so it needs no
- * preamble explaining that something is about to be awkward.
- */
- readonly installNote?: string;
-}
-
-/** Filled in once the installers are published. `src/lib/desktop/release.test.ts` holds it to
- * its shape from then on. */
-export const RELEASE: DesktopRelease | null = null;
diff --git a/builder/web/src/lib/desktop/usb.svelte.ts b/builder/web/src/lib/desktop/usb.svelte.ts
deleted file mode 100644
index b08b46acd8..0000000000
--- a/builder/web/src/lib/desktop/usb.svelte.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * The desktop host's device session — the reactive shell C3 already wrote, over a native watcher.
- *
- * This file is three lines of substance on purpose. `WatchedDeviceSession` mirrors any
- * `DeviceWatcher`'s snapshots into runes, and `NativeWatcher` has the same three methods
- * `WebUsbWatcher` does, so the entire desktop USB session is "the same session, different
- * transport". If this file ever needs to grow a branch, the seam has stopped holding.
- */
-
-import { WatchedDeviceSession } from "../usb/session.svelte";
-import type { DeviceSession } from "../usb/session";
-import { NativeWatcher, type NativeWatcherOptions } from "./usb";
-
-/**
- * Open a native USB session and adopt an attached device if there is one.
- *
- * Returns as soon as the adopt attempt has settled — with a live client when a device was found and
- * `idle` when none was. Neither is a failure: the session's job is to be something the UI can
- * render in every state, including "nothing is plugged in yet".
- *
- * There is no `unsupported` state to reach here. That one means "this browser has no WebUSB", and
- * not having to say it is the reason this tier exists.
- */
-export async function openNativeSession(options: NativeWatcherOptions = {}): Promise {
- const watcher = new NativeWatcher(options);
- const session = new WatchedDeviceSession(watcher, "native");
- await watcher.start();
- return session;
-}
diff --git a/builder/web/src/lib/desktop/usb.test.ts b/builder/web/src/lib/desktop/usb.test.ts
deleted file mode 100644
index d676d4a23a..0000000000
--- a/builder/web/src/lib/desktop/usb.test.ts
+++ /dev/null
@@ -1,683 +0,0 @@
-/**
- * The native transport, driven end to end.
- *
- * There is no device in CI, so the substitution is made at exactly one place: the **Tauri command
- * boundary**. Everything above it — `NativePipe`, `NativeWatcher`, `FlatStoreClient`, the record
- * framing, the codecs, the CRC — is the shipping code, and the fake backend below stands in for
- * `builder/desktop/src/usb/`, forwarding to the simulated device.
- *
- * That leaves two things a fake can prove: that a real fixture object round-trips through the real
- * client over the native pipes byte for byte, with the device verifying the whole-object CRC, and
- * that the transport properties hold — a read is not a record, a zero-length packet is a marker and
- * not data, concurrent writes keep submission order, cancellation reaches the transport, and an
- * unplug settles pending calls.
- *
- * A third is an absence: this host has no EP0 vendor request, which is asserted rather than worked
- * around, because a connection that invented a firmware revision would feed "an update is
- * available" a lie.
- *
- * Nothing here proves anything about `nusb`, the OS or the descriptors.
- */
-
-import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
-import { existsSync, readFileSync } from "node:fs";
-import { dirname, join } from "node:path";
-import { fileURLToPath } from "node:url";
-
-import { FlatStoreClient } from "../usb/client";
-import { Crc32 } from "../usb/crc32";
-import { loadFlatDevice } from "../../../test-support/flat-device/load";
-import { FlatDevice, type FlatDeviceOptions } from "../usb/flat-device";
-import { loopbackLink, type LoopbackLink, type LoopbackOptions } from "../usb/loopback";
-import { PipeError, type BytePipe } from "../usb/pipe";
-import { MAX_HOST_STREAM_RECORD } from "../usb/records";
-import { HEAD_REVISION, ObjectKind } from "../usb/protocol";
-
-/** One `invoke()` the fake backend saw, for the wire assertions. */
-interface Call {
- cmd: string;
- args: unknown;
- options?: { headers?: Record };
-}
-
-class FakeChannel {
- onmessage: ((message: T) => void) | null = null;
-}
-
-const calls: Call[] = [];
-/** Set per test: what `usb_watch` / `usb_list` report is attached. */
-let attached: Array<{
- id: string;
- vendorId: number;
- productId: number;
- product: string | null;
- serialNumber: string | null;
-}> = [];
-/** The hot-plug channel the watcher handed `usb_watch` — a test pushes plug events through it. */
-let watchChannel: FakeChannel | null = null;
-let wire: LoopbackLink | null = null;
-let device: FlatDevice | null = null;
-/** Whether `usb_open` should refuse, and with what. `onlyId` scopes the fault to one device. */
-let openFault: { code: string; message: string; onlyId?: string } | null = null;
-/** Gates shifted per `usb_open` call — an entry parks that open until its promise resolves,
- * which is how a test freezes one connect flow mid-open while another overtakes it. */
-let openGates: Array<(() => Promise) | undefined> = [];
-/** Per-call gates for `usb_write` on the stream plane, modelling the backend's free ordering of
- * concurrent invokes. */
-let writeGates: Array<(() => Promise) | undefined> = [];
-/** In-flight reads/writes, so `usb_cancel` can settle them the way a cancelled URB does. */
-const inFlight = new Map();
-
-/**
- * The backend's plane name → the channel the protocol gives it. `"bulk"` is `DeviceLink.stream`
- * under the Rust side's older name for the endpoint pair; renaming it is a Rust change.
- */
-function planeOf(name: string): BytePipe {
- const link = wire?.host;
- if (!link) throw { code: "closed", message: "no link" };
- return name === "control" ? link.control : link.stream;
-}
-
-async function backend(cmd: string, args: unknown, options?: { headers?: Record }): Promise {
- const a = (args ?? {}) as Record;
- switch (cmd) {
- case "usb_watch":
- watchChannel = a.onEvent as FakeChannel;
- return attached;
- case "usb_list":
- return attached;
- case "usb_open": {
- const gate = openGates.shift();
- if (gate) await gate();
- if (openFault && (!openFault.onlyId || openFault.onlyId === a.deviceId)) throw openFault;
- const found = attached.find((d) => d.id === a.deviceId);
- if (!found) throw { code: "closed", message: "That device is no longer attached." };
- return {
- handle: 1,
- deviceId: found.id,
- interfaceNumber: 0,
- controlPacketSize: 512,
- bulkPacketSize: 512,
- product: found.product,
- serialNumber: found.serialNumber,
- };
- }
- case "usb_close":
- await wire?.host.close();
- return null;
- case "usb_read": {
- const key = `${a.plane}:in`;
- const controller = new AbortController();
- inFlight.set(key, controller);
- try {
- const bytes = await planeOf(a.plane as string).read(controller.signal);
- return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
- } catch (cause) {
- throw asFault(cause);
- } finally {
- inFlight.delete(key);
- }
- }
- case "usb_write": {
- // The real command takes the bytes as the whole invoke body, with the handle and plane
- // in headers — which is exactly what is asserted here rather than assumed.
- const plane = options?.headers?.plane ?? "";
- if (plane === "bulk") {
- const gate = writeGates.shift();
- if (gate) await gate();
- }
- const key = `${plane}:out`;
- const controller = new AbortController();
- inFlight.set(key, controller);
- try {
- await planeOf(plane).write(new Uint8Array(args as ArrayBufferLike), controller.signal);
- return null;
- } catch (cause) {
- throw asFault(cause);
- } finally {
- inFlight.delete(key);
- }
- }
- case "usb_cancel": {
- const dirs = a.dir ? [a.dir as string] : ["in", "out"];
- for (const dir of dirs) inFlight.get(`${a.plane}:${dir}`)?.abort();
- return null;
- }
- case "usb_reset":
- await planeOf(a.plane as string).reset();
- return null;
- default:
- throw new Error(`the fake backend has no command ${cmd}`);
- }
-}
-
-/** Translate the loopback's `PipeError` into the `{code, message}` the Rust side rejects with. */
-function asFault(cause: unknown): { code: string; message: string } {
- if (cause instanceof PipeError) return { code: cause.code, message: cause.message };
- return { code: "device-error", message: String(cause) };
-}
-
-vi.mock("@tauri-apps/api/core", () => ({
- invoke: (cmd: string, args?: unknown, options?: { headers?: Record }) => {
- calls.push({ cmd, args, options });
- return backend(cmd, args, options);
- },
- Channel: FakeChannel,
-}));
-
-const { NativeWatcher, openNativeLink } = await import("./usb");
-
-function repoRoot(): string {
- let dir = dirname(fileURLToPath(import.meta.url));
- for (let up = 0; up < 12; up++) {
- if (existsSync(join(dir, "specs", "vectors", "manifest.json"))) return dir;
- dir = dirname(dir);
- }
- throw new Error("could not locate the repo root");
-}
-const ROOT = repoRoot();
-const vector = (name: string): Uint8Array => new Uint8Array(readFileSync(join(ROOT, "specs/vectors", name)));
-
-const DEVICE = {
- id: "usb#1",
- vendorId: 0x1209,
- productId: 0x0001,
- product: "OpenBikeComputer",
- serialNumber: "0011223344556677",
-};
-const DEVICE_B = {
- id: "usb#2",
- vendorId: 0x1209,
- productId: 0x0001,
- product: "OpenBikeComputer",
- serialNumber: "8877665544332211",
-};
-
-/** A live simulated device behind the fake backend, and a watcher already connected to it. */
-async function connected(options: LoopbackOptions & FlatDeviceOptions = {}) {
- wire = loopbackLink(options);
- device = new FlatDevice(wire.device, options);
- void device.run();
- attached = [DEVICE];
- const watcher = new NativeWatcher();
- const ok = await watcher.start();
- return { watcher, ok };
-}
-
-beforeAll(loadFlatDevice);
-
-beforeEach(() => {
- calls.length = 0;
- attached = [];
- watchChannel = null;
- openFault = null;
- openGates = [];
- writeGates = [];
- inFlight.clear();
- wire = null;
- device = null;
-});
-
-// Each test moves an object through the wasm flat device, which a machine that runs other suites slows past 5 s.
-describe("the native pipes under the flat-store client", { timeout: 30_000 }, () => {
- it("round-trips a specs/vectors object, byte for byte", async () => {
- // 64-byte packets, so every record of any size spans several transfers in both directions. A
- // client that treated one `usb_read` as one record would pass against a device that wrote
- // whole records and fail here, which is the whole reason the loopback re-slices.
- const { watcher, ok } = await connected({ packetSize: 64 });
- expect(ok).toBe(true);
- const client = watcher.current.client!;
- expect(watcher.current.status).toBe("ready");
- // The `LIST` every connection issues first is where the card's identity comes from.
- expect(watcher.current.store).toEqual({ storeId: device!.storeId, commitSequence: device!.sequence });
-
- // A `PUT` of a real OBCR fixture: the request over the control channel, the payload as
- // stream records, and the device verifying the whole-object CRC at commit. The device is the
- // one checking, so a mis-framed record fails here rather than being "uploaded".
- const obcr = vector("route-waypoints.obcr");
- const put = await client.put({ kind: ObjectKind.Route, displayName: "waypoints" }, obcr);
- expect(put.payloadLength).toBe(BigInt(obcr.length));
- expect(put.payloadCrc32).toBe(Crc32.of(obcr));
- expect(device!.payloadOf(put.objectId)).toEqual(obcr);
-
- // …and a `GET` in the other direction, whose length and CRC this side verifies.
- const got = await client.get({ objectId: put.objectId, revision: HEAD_REVISION });
- expect(got.bytes).toEqual(obcr);
- expect(got.revisionServed).toBe(put.revision);
-
- // The catalog, paged over the same channel, now names it.
- const catalog = await client.list();
- expect(catalog.entries.map((e) => e.objectId)).toContain(put.objectId);
- expect(catalog.entries.find((e) => e.objectId === put.objectId)?.displayName).toBe("waypoints");
-
- await watcher.close();
- });
-
- it("keeps concurrent stream writes in submission order across the bridge", async () => {
- // The backend gives concurrent invokes no ordering guarantee — each lands in its own task
- // racing for the endpoint lock. Delaying the first stream invoke a few ticks models the race:
- // without the pipe's submission chain the second batch reaches the wire first and the object
- // arrives with its middle swapped — right total length, wrong whole-object CRC.
- const { watcher, ok } = await connected();
- expect(ok).toBe(true);
- const client = watcher.current.client!;
- // Big enough that the upload keeps several batches in its window, plus an odd tail.
- const bytes = new Uint8Array(200_003);
- for (let i = 0; i < bytes.length; i++) bytes[i] = (i * 31 + (i >> 9)) & 0xff;
- writeGates.push(() => new Promise((resolve) => setTimeout(resolve, 10)));
- const put = await client.put({ kind: ObjectKind.MapShard, displayName: "black forest" }, bytes);
- expect(put.payloadCrc32).toBe(Crc32.of(bytes));
- expect(device!.payloadOf(put.objectId)).toEqual(bytes);
- await watcher.close();
- });
-});
-
-describe("the native pipe's transport contract", () => {
- it("puts the bytes in a raw body and the routing in headers", async () => {
- const { watcher } = await connected();
- const write = calls.find((c) => c.cmd === "usb_write");
- // A `Vec` argument would have been JSON — about four bytes of text per byte of payload,
- // which is fine for a 32-byte `LIST` and absurd for a 300 MB map.
- expect(write?.args).toBeInstanceOf(Uint8Array);
- expect(write?.options?.headers).toEqual({ handle: "1", plane: "control" });
- const read = calls.find((c) => c.cmd === "usb_read");
- expect(read?.args).toEqual({ handle: 1, plane: "control" });
- await watcher.close();
- });
-
- it("sends a record that spans packets instead of refusing it", async () => {
- // A record is self-delimiting — a `record_length u32`, frame bytes and alignment padding,
- // across as many packets as it takes — so the ordinary 8,208-byte stream frame has to go out,
- // and so does a control record that lands on the 512-byte boundary.
- wire = loopbackLink();
- attached = [DEVICE];
- const link = await openNativeLink(DEVICE.id);
- const stream = Uint8Array.from({ length: MAX_HOST_STREAM_RECORD }, (_, i) => (i * 13) & 0xff);
- await link.stream.write(stream);
- expect(await drain(wire.device.stream, stream.length)).toEqual(stream);
-
- const control = new Uint8Array(512).fill(0xa5);
- await link.control.write(control);
- expect(await drain(wire.device.control, control.length)).toEqual(control);
- await link.close();
- });
-
- it("cancels at the transport rather than merely releasing the caller", async () => {
- const { watcher } = await connected();
- const link = await openNativeLink(DEVICE.id);
- const abort = new AbortController();
- const read = link.stream.read(abort.signal);
- // Nothing is queued on the stream plane, so this read is genuinely parked — the case that
- // wedges if a cancel only settles the promise: the backend would still hold the endpoint and
- // the next read would queue behind an orphan that never completes.
- await Promise.resolve();
- abort.abort();
- await expect(read).rejects.toMatchObject({ name: "PipeError", code: "aborted" });
- expect(calls.some((c) => c.cmd === "usb_cancel")).toBe(true);
- await watcher.close();
- });
-
- it("settles everything parked on it the moment the device is unplugged", async () => {
- const { watcher } = await connected();
- const link = await openNativeLink(DEVICE.id);
- const read = link.stream.read();
- link.disconnected();
- await expect(read).rejects.toMatchObject({ code: "closed" });
- // …and stays closed: a later call fails immediately instead of making another doomed round
- // trip, which is the difference between one error message and a stuck spinner.
- await expect(link.stream.read()).rejects.toMatchObject({ code: "closed" });
-
- // The abandoned command settles *after* the caller was failed by the unplug, so its
- // rejection lands on nobody. It must stay harmless: no second error, no resurrected pipe, and
- // a `close()` afterwards that still works on a link whose device is already gone.
- await wire!.host.close();
- await new Promise((resolve) => setTimeout(resolve, 10));
- expect(link.stream.open).toBe(false);
- await watcher.close();
- });
-});
-
-/** Read `total` bytes off a loopback end, which delivers them one packet at a time. */
-async function drain(pipe: BytePipe, total: number): Promise {
- const out = new Uint8Array(total);
- let at = 0;
- while (at < total) {
- const slice = await pipe.read();
- out.set(slice, at);
- at += slice.length;
- }
- return out;
-}
-
-// --- the device info this host cannot ask for ----------------------------------
-
-describe("the device info this host cannot read", () => {
- it("says so rather than answering with a version nobody read off the device", async () => {
- // `GET_DEVICE_INFO` is an EP0 vendor request and the Rust bridge exposes no
- // control-transfer command, so the link omits `vendorIn` entirely. The client turns that
- // absence into one specific code, which is what the connect flow catches.
- wire = loopbackLink();
- attached = [DEVICE];
- const link = await openNativeLink(DEVICE.id);
- expect(link.vendorIn, "a link that cannot issue EP0 must not pretend to").toBeUndefined();
- const client = new FlatStoreClient(link);
- await expect(client.deviceInfo()).rejects.toMatchObject({ name: "DeviceError", code: "unavailable" });
- await client.close();
- });
-
- it("connects anyway, publishing no firmware version at all", async () => {
- // The alternative — failing the connection, or filling the field with a plausible number —
- // would either strand the desktop tier or hand "an update is available" a lie. `null` is the
- // honest third answer, and the UI renders the absence.
- const { watcher, ok } = await connected();
- expect(ok).toBe(true);
- expect(watcher.current.status).toBe("ready");
- expect(watcher.current.info).toBeNull();
- expect(watcher.current.store).not.toBeNull();
- await watcher.close();
- });
-});
-
-// --- discovery -----------------------------------------------------------------
-
-describe("native discovery", () => {
- it("adopts an attached device with no prompt and no gesture", async () => {
- const { ok, watcher } = await connected();
- expect(ok).toBe(true);
- // The watch is started before the listing, which is the ordering that cannot miss a device
- // plugged in during the call.
- expect(calls[0].cmd).toBe("usb_watch");
- await watcher.close();
- });
-
- it("reports nothing attached as idle, which is not an error", async () => {
- attached = [];
- const watcher = new NativeWatcher();
- expect(await watcher.start()).toBe(false);
- expect(watcher.current).toMatchObject({ status: "idle", error: null, client: null, store: null });
- await watcher.close();
- });
-
- it("releases the interface when a connection fails partway", async () => {
- // A device claimed but never listed still holds its interface, and an interface can be
- // claimed once — so a failed connect that kept it would lock out every retry.
- wire = loopbackLink();
- attached = [DEVICE];
- const watcher = new NativeWatcher({ timeoutMs: 20, hotplugRetryDelayMs: 1 });
- // No device running, so the `LIST` times out.
- expect(await watcher.start()).toBe(false);
- expect(watcher.current.status).toBe("error");
- expect(calls.some((c) => c.cmd === "usb_close")).toBe(true);
- await watcher.close();
- });
-
- it("surfaces a refused open as the sentence the backend wrote", async () => {
- attached = [DEVICE];
- openFault = {
- code: "device-error",
- message: "Interface 0 could not be claimed: busy — something else has it open.",
- };
- const watcher = new NativeWatcher({ hotplugRetryDelayMs: 1 });
- expect(await watcher.start()).toBe(false);
- expect(watcher.current.error).toContain("something else has it open");
- await watcher.close();
- });
-
- it("connects by itself when the device is plugged in after start", async () => {
- // The hot-plug contract on hardware: app open, nothing attached, cable in — the window
- // lights up with no click. The event rides the channel `usb_watch` was given.
- attached = [];
- const watcher = new NativeWatcher();
- await watcher.start();
- expect(watcher.current.status).toBe("idle");
-
- wire = loopbackLink();
- device = new FlatDevice(wire.device);
- void device.run();
- attached = [DEVICE];
- watchChannel!.onmessage!({ type: "connected", device: DEVICE });
-
- await vi.waitFor(() => expect(watcher.current.status).toBe("ready"));
- await watcher.close();
- });
-
- it("retries when the OS announces the device before it is claimable", async () => {
- // nusb's own hot-plug docs: a `Connected` event can precede the device being openable, so
- // retry after a short delay. The failure that motivated this: one transient claim failure
- // parked the session in `error` — which the chip renders as "No device" — forever.
- attached = [];
- const watcher = new NativeWatcher({ hotplugRetryDelayMs: 1 });
- await watcher.start();
-
- wire = loopbackLink();
- device = new FlatDevice(wire.device);
- void device.run();
- attached = [DEVICE];
- openFault = { code: "device-error", message: "Interface 0 could not be claimed: busy." };
- watchChannel!.onmessage!({ type: "connected", device: DEVICE });
-
- // The first attempt has failed; between attempts the state stays `connecting`, not `error`.
- await vi.waitFor(() => expect(calls.filter((c) => c.cmd === "usb_open").length).toBeGreaterThanOrEqual(1));
- expect(watcher.current.status).toBe("connecting");
-
- openFault = null; // the OS finished setting the device up
- await vi.waitFor(() => expect(watcher.current.status).toBe("ready"));
- await watcher.close();
- });
-
- it("settles back to idle when the device vanishes during the retries", async () => {
- attached = [];
- const watcher = new NativeWatcher({ hotplugRetryDelayMs: 1 });
- await watcher.start();
-
- attached = [DEVICE];
- openFault = { code: "device-error", message: "busy" };
- watchChannel!.onmessage!({ type: "connected", device: DEVICE });
- await vi.waitFor(() => expect(calls.some((c) => c.cmd === "usb_open")).toBe(true));
-
- // Unplugged again before any attempt succeeded: the truthful end state is idle, not an
- // error about a device that is no longer there.
- attached = [];
- await vi.waitFor(() => expect(watcher.current.status).toBe("idle"));
- expect(watcher.current.error).toBeNull();
- await watcher.close();
- });
-
- it("gives up with the device's own error once the retries run out", async () => {
- attached = [];
- const watcher = new NativeWatcher({ hotplugRetryDelayMs: 1 });
- await watcher.start();
-
- attached = [DEVICE];
- openFault = {
- code: "device-error",
- message: "Interface 0 could not be claimed: busy — something else has it open.",
- };
- watchChannel!.onmessage!({ type: "connected", device: DEVICE });
-
- await vi.waitFor(() => expect(watcher.current.status).toBe("error"));
- expect(watcher.current.error).toContain("something else has it open");
- // Bounded: it tried its attempts and stopped, rather than polling forever.
- expect(calls.filter((c) => c.cmd === "usb_open")).toHaveLength(5);
- await watcher.close();
- });
-
- it("retries start()'s own initial adopt through the same window", async () => {
- // App launched moments after the cable went in: the initial probe hits the exact same
- // not-yet-claimable window a hot-plug event does, where a single failed attempt would
- // park in `error` with no event ever coming to rescue it.
- wire = loopbackLink();
- device = new FlatDevice(wire.device);
- void device.run();
- attached = [DEVICE];
- openFault = { code: "device-error", message: "not ready yet" };
- const watcher = new NativeWatcher({ hotplugRetryDelayMs: 1 });
-
- let release1!: () => void;
- let release2!: () => void;
- openGates.push(() => new Promise((resolve) => (release1 = resolve)));
- const started = watcher.start();
- await vi.waitFor(() => expect(calls.filter((c) => c.cmd === "usb_open")).toHaveLength(1));
- openGates.push(() => new Promise((resolve) => (release2 = resolve)));
- release1(); // attempt 1 fails against the not-yet-claimable device
- await vi.waitFor(() => expect(calls.filter((c) => c.cmd === "usb_open")).toHaveLength(2));
- openFault = null; // the OS finished setting the device up
- release2();
-
- expect(await started).toBe(true);
- expect(watcher.current.status).toBe("ready");
- await watcher.close();
- });
-
- it("lets a Connect click win over an adopt loop parked between attempts", async () => {
- // The wedge this guards against: the click and the loop both open the same device, the
- // loop's late failure publishes `error` over the click's `ready`, and whichever link
- // loses is dropped still holding the interface claim. The click claims the flow, so the
- // loop must notice and stand down without another attempt.
- attached = [];
- const watcher = new NativeWatcher({ hotplugRetryDelayMs: 120 });
- await watcher.start();
-
- wire = loopbackLink();
- device = new FlatDevice(wire.device);
- void device.run();
- attached = [DEVICE];
- openFault = { code: "device-error", message: "busy" };
- watchChannel!.onmessage!({ type: "connected", device: DEVICE });
- await vi.waitFor(() => expect(calls.filter((c) => c.cmd === "usb_open")).toHaveLength(1));
-
- // The rider clicks Connect while the loop sleeps out its retry delay.
- openFault = null;
- expect(await watcher.requestDevice()).toBe(true);
- expect(watcher.current.status).toBe("ready");
-
- // The loop wakes, sees it lost the flow, and goes quietly: no third open, no late error,
- // and the winner's client still works.
- await new Promise((resolve) => setTimeout(resolve, 200));
- expect(watcher.current.status).toBe("ready");
- expect(calls.filter((c) => c.cmd === "usb_open")).toHaveLength(2);
- const page = await watcher.current.client!.listPage({});
- expect(page.storeId).toBe(device!.storeId);
- await watcher.close();
- });
-
- it("closes, not orphans, a link whose flow lost while the handshake ran", async () => {
- // The expensive half of the same race: a flow that already *opened* the device loses
- // while its handshake runs. The Rust side holds the interface claim until the link is
- // closed, so dropping the client on the floor would make every later open fail "busy"
- // until a physical replug. The loser must close what it opened and publish nothing.
- attached = [];
- const watcher = new NativeWatcher({ hotplugRetryDelayMs: 1 });
- await watcher.start();
-
- wire = loopbackLink();
- device = new FlatDevice(wire.device);
- void device.run();
- attached = [DEVICE];
- let release!: () => void;
- openGates.push(() => new Promise((resolve) => (release = resolve)));
- watchChannel!.onmessage!({ type: "connected", device: DEVICE });
- await vi.waitFor(() => expect(calls.some((c) => c.cmd === "usb_open")).toBe(true));
-
- // Overtaken while parked inside the open: a deliberate disconnect claims the flow.
- await watcher.disconnect();
- const seen: string[] = [];
- const unsubscribe = watcher.subscribe((s) => seen.push(s.status));
- release();
-
- // The open and the handshake complete against the live device — and then the loser
- // notices it lost: the link is closed at the backend, nothing is published.
- await vi.waitFor(() => expect(calls.some((c) => c.cmd === "usb_close")).toBe(true));
- await new Promise((resolve) => setTimeout(resolve, 50));
- expect(watcher.current.status).toBe("idle");
- expect(seen).not.toContain("ready");
- expect(seen).not.toContain("error");
- expect(calls.filter((c) => c.cmd === "usb_open")).toHaveLength(1);
- unsubscribe();
- await watcher.close();
- });
-
- it("keeps a successor alive when a superseded loop's final attempt fails late", async () => {
- // A replugged device gets a new id and a new `Connected` event while the old id's loop is
- // still failing its last attempt. That final failure must not publish `error` over the
- // fresh loop's `connecting` — before the flow token, it did, and the fresh loop then saw
- // the wrong status and stood down: the freshly plugged device never connected.
- attached = [];
- const watcher = new NativeWatcher({ hotplugRetryDelayMs: 1 });
- await watcher.start();
-
- wire = loopbackLink();
- device = new FlatDevice(wire.device);
- void device.run();
- attached = [DEVICE, DEVICE_B];
- openFault = { code: "device-error", message: "gone", onlyId: DEVICE.id };
- // Attempts 1–4 fail fast; the 5th parks in its open so the successor can overtake it.
- let release!: () => void;
- openGates = [
- undefined,
- undefined,
- undefined,
- undefined,
- () => new Promise((resolve) => (release = resolve)),
- ];
- watchChannel!.onmessage!({ type: "connected", device: DEVICE });
- await vi.waitFor(() => expect(calls.filter((c) => c.cmd === "usb_open")).toHaveLength(5));
-
- watchChannel!.onmessage!({ type: "connected", device: DEVICE_B });
- await vi.waitFor(() => expect(watcher.current.status).toBe("ready"));
- release(); // the old loop's final attempt now fails, late and superseded
-
- await new Promise((resolve) => setTimeout(resolve, 50));
- expect(watcher.current.status).toBe("ready");
- expect(watcher.current.error).toBeNull();
- // …and the connection that stands is the successor's, not a resurrected old one.
- const opens = calls.filter((c) => c.cmd === "usb_open");
- expect((opens.at(-1)?.args as { deviceId: string }).deviceId).toBe(DEVICE_B.id);
- await watcher.close();
- });
-
- it("ends in idle when the unplug event lands mid-flow", async () => {
- // The Disconnected event arrives while the flow has no link yet (so the link-based
- // handler ignores it) and the device is even still *listed* by a stale probe. The flow
- // chasing exactly this id is ended in the honest state, and its in-flight attempt's
- // failure stays silent.
- attached = [];
- const watcher = new NativeWatcher({ hotplugRetryDelayMs: 1 });
- await watcher.start();
-
- attached = [DEVICE];
- openFault = { code: "device-error", message: "busy" };
- // Park the attempt inside its open, so the unplug event demonstrably lands mid-flight.
- let release!: () => void;
- openGates.push(() => new Promise((resolve) => (release = resolve)));
- watchChannel!.onmessage!({ type: "connected", device: DEVICE });
- await vi.waitFor(() => expect(calls.some((c) => c.cmd === "usb_open")).toBe(true));
-
- watchChannel!.onmessage!({ type: "disconnected", id: DEVICE.id });
- await vi.waitFor(() => expect(watcher.current.status).toBe("idle"));
- release(); // the parked attempt now fails, sees a stale token, and says nothing
- await new Promise((resolve) => setTimeout(resolve, 60));
- expect(watcher.current.status).toBe("idle");
- expect(watcher.current.error).toBeNull();
- await watcher.close();
- });
-
- it("re-scans instead of opening a chooser", async () => {
- // The native host has no permission prompt, so `requestDevice()` is "look again now" — the
- // Connect button keeps working and no UI branches on which transport it got.
- attached = [];
- const watcher = new NativeWatcher();
- await watcher.start();
- wire = loopbackLink();
- device = new FlatDevice(wire.device);
- void device.run();
- attached = [DEVICE];
- expect(await watcher.requestDevice()).toBe(true);
- expect(watcher.current.status).toBe("ready");
- await watcher.close();
- });
-});
-
-// A map sent disk to endpoint inside Rust cannot exist until the Rust side frames records: every
-// stream record carries a `RequestId`, an absolute offset and a length. The heap claim that path made belongs to the shared upload loop and is
-// tested where that loop lives; the CRC constant it pinned is `usb/crc32.test.ts`'s.
diff --git a/builder/web/src/lib/desktop/usb.ts b/builder/web/src/lib/desktop/usb.ts
deleted file mode 100644
index 9c502a31b4..0000000000
--- a/builder/web/src/lib/desktop/usb.ts
+++ /dev/null
@@ -1,551 +0,0 @@
-/**
- * The native USB transport: `nusb` behind the {@link BytePipe} seam.
- *
- * Tauri's webview has no WebUSB — WKWebView, WebView2 and WebKitGTK all lack it — so this tier
- * drives USB from Rust. It is also the only universal USB path, and the answer for every Safari and
- * Firefox user the hosted site cannot reach.
- *
- * Nothing about the protocol lives here. `lib/usb/` is the codec, the record framing and the client;
- * this file supplies the two byte pipes underneath them and a watcher with the same three methods
- * `WebUsbWatcher` has. It lives in `lib/desktop/` because it imports `@tauri-apps/api`, and
- * `platform/bundle.test.ts` asserts nothing in that folder reaches the hosted bundle.
- *
- * What differs from the browser:
- *
- * - Cancellation reaches the transport. WebUSB cannot cancel a submitted `transferIn`; nusb can, and
- * here it must, because after an abort the device stops sending and an orphaned read would hold
- * the endpoint forever.
- * - There is no chooser and no permission prompt. `requestDevice()` is "look again now".
- * - There is no EP0 read: the Rust side exposes no control-transfer command, so the link omits
- * `DeviceLink.vendorIn` and the connect flow publishes `info: null` rather than a fabricated
- * firmware revision.
- *
- * A map is not sent from disk. Every stream record must be framed by the protocol client, which is
- * TypeScript, so the desktop app sends a map exactly the way the browser does: a picked `File`
- * through the webview.
- */
-
-import { PipeError, withAbort, type BytePipe, type DeviceLink } from "../usb/pipe";
-import { DeviceError, FlatStoreClient, isFormatRecoveryState, type ClientOptions } from "../usb/client";
-import type { DeviceInfo } from "../usb/records";
-import type { DeviceState, DeviceWatcher } from "../usb/session";
-import { Channel } from "@tauri-apps/api/core";
-import { desktop, type UsbDeviceSummary, type UsbEvent, type UsbLinkInfo, type UsbPlane } from "./invoke";
-
-/** One endpoint pair, as a byte pipe over the Tauri commands in `builder/desktop/src/usb/`. */
-class NativePipe implements BytePipe {
- readonly transport = "native";
-
- private failure: PipeError | null = null;
- private closedByUs = false;
- /** Rejectors for {@link dead}, released when the pipe closes or fails. */
- private readonly mourners: Array<(error: PipeError) => void> = [];
- /**
- * The previous {@link write}'s settlement — each write chains on it, so submission order is wire
- * order. Without the chain, concurrent writes each travel as an independent IPC invoke and the
- * backend gives them no ordering: two in-flight chunks can swap on the wire, giving the right
- * total length and the wrong whole-object CRC. The chain costs one IPC round trip of idle bridge
- * per chunk, not wire idle. WebUSB needs none of this: the browser queues per-endpoint transfers
- * in call order.
- */
- private writeTail: Promise = Promise.resolve();
-
- constructor(
- /**
- * The backend's name for this endpoint pair. `"bulk"` is what `DeviceLink.stream` is called
- * on the Rust side; renaming it is a Rust change, so the wire word stays and the seam is here.
- */
- readonly plane: UsbPlane,
- private readonly handle: number,
- /**
- * The endpoint's max packet size, as `usb_open` reported it. Diagnostics only, never a
- * branch target: packet boundaries carry no protocol meaning.
- */
- readonly packetSize: number,
- ) {}
-
- get open(): boolean {
- return !this.failure && !this.closedByUs;
- }
-
- async read(signal?: AbortSignal): Promise {
- this.check();
- // The backend cancels the URB, so the abort is not merely the caller walking away: the
- // transfer is really gone, and the endpoint is free for the reset that always follows.
- const release = this.cancelOnAbort(signal, "in");
- try {
- const body = await Promise.race([
- withAbort(desktop.usbRead(this.handle, this.plane), signal, "the read"),
- this.dead(),
- ]);
- // Never empty: the backend absorbs zero-length packets, which are USB-level markers
- // rather than data, and an empty read is indistinguishable from a spurious wakeup.
- return new Uint8Array(body);
- } catch (cause) {
- throw this.asPipeError(cause, "read");
- } finally {
- release();
- }
- }
-
- /**
- * One OUT transfer of whatever the caller handed over. There is deliberately no "a control frame
- * must fit one packet" rule: records span packets by design, and the only thing that says where a
- * record ends is its own four-byte prefix.
- */
- async write(bytes: Uint8Array, signal?: AbortSignal): Promise {
- this.check();
- const run = async () => {
- const release = this.cancelOnAbort(signal, "out");
- try {
- await Promise.race([
- withAbort(desktop.usbWrite(this.handle, this.plane, bytes), signal, "the write"),
- this.dead(),
- ]);
- } catch (cause) {
- throw this.asPipeError(cause, "write");
- } finally {
- release();
- }
- };
- // Chain on the predecessor whether it settled well or badly — its caller owns its error;
- // this write only needs it to be off the bridge. See `writeTail` for why order is load-bearing.
- const chained = this.writeTail.then(run, run);
- this.writeTail = chained.then(
- () => {},
- () => {},
- );
- return chained;
- }
-
- /**
- * Cancel everything in flight and clear both halves of the pair.
- *
- * An exchange that does not reach its correlated close leaves the channel at an unknown offset.
- * Here that is a real cancel plus `CLEAR_FEATURE(ENDPOINT_HALT)`, not the best-effort `clearHalt`
- * the browser can manage, so a cancelled download's tail is genuinely discarded.
- */
- async reset(): Promise {
- this.check();
- try {
- await desktop.usbReset(this.handle, this.plane);
- } catch (cause) {
- // A pipe whose device has already gone has nothing left to reset, and the caller's
- // original error is the interesting one.
- if (this.failure) return;
- throw this.asPipeError(cause, "reset");
- }
- }
-
- async close(): Promise {
- this.closedByUs = true;
- this.bury(new PipeError("closed", "The device link is closed."));
- }
-
- /** Mark the pipe dead and fail everything waiting on it — what an unplug calls. */
- fail(error: PipeError): void {
- this.failure ??= error;
- this.bury(error);
- }
-
- /** Tell the backend to cancel this direction when `signal` fires. Returns the unsubscriber. */
- private cancelOnAbort(signal: AbortSignal | undefined, dir: "in" | "out"): () => void {
- if (!signal) return () => undefined;
- const onAbort = () => void desktop.usbCancel(this.handle, this.plane, dir).catch(() => undefined);
- signal.addEventListener("abort", onAbort, { once: true });
- return () => signal.removeEventListener("abort", onAbort);
- }
-
- /**
- * A promise that rejects when this pipe closes or fails. Raced against every call so an unplug
- * settles the caller from the *event*, deterministically, rather than from whichever of the OS
- * transfer error and the hot-plug notification wins.
- */
- private dead(): Promise {
- return new Promise((_, reject) => {
- if (this.failure) reject(this.failure);
- else if (this.closedByUs) reject(new PipeError("closed", "The device link is closed."));
- else this.mourners.push(reject);
- });
- }
-
- private bury(error: PipeError): void {
- while (this.mourners.length) this.mourners.shift()?.(error);
- }
-
- private check(): void {
- if (this.failure) throw this.failure;
- if (this.closedByUs) throw new PipeError("closed", "The device link is closed.");
- }
-
- private asPipeError(cause: unknown, what: string): PipeError {
- if (this.failure) return this.failure;
- const error = asPipeError(cause, what);
- // A transport-level `closed` is terminal for this pipe, exactly as an unplug is: recording
- // it means the next call fails immediately instead of making another doomed round trip.
- if (error.code === "closed") this.fail(error);
- return error;
- }
-}
-
-/**
- * Translate a rejected Tauri command into a {@link PipeError}.
- *
- * The backend rejects with its own `{ code, message }`, deliberately in `PipeError`'s vocabulary, so
- * the mapping is a lookup rather than string-matching an OS error. Anything else is a `device-error`.
- */
-function asPipeError(cause: unknown, what: string): PipeError {
- if (cause instanceof PipeError) return cause;
- const fault = cause as { code?: unknown; message?: unknown } | null;
- const code = fault?.code;
- const message = typeof fault?.message === "string" ? fault.message : String(cause);
- if (code === "closed" || code === "aborted" || code === "device-error") {
- return new PipeError(code, message, { cause });
- }
- return new PipeError("device-error", `The ${what} failed: ${message}`, { cause });
-}
-
-/** A claimed device, as a {@link DeviceLink}. */
-export interface NativeLink extends DeviceLink {
- readonly info: UsbLinkInfo;
- /** Fail both pipes at once — what a `disconnected` event calls. */
- disconnected(): void;
-}
-
-/**
- * Open and claim a device by the backend's opaque id, returning its two channels.
- *
- * `DeviceLink.vendorIn` is deliberately absent: the Rust side has no control-transfer command, and
- * omitting the method is what lets {@link FlatStoreClient.deviceInfo} say "this host cannot ask".
- */
-export async function openNativeLink(deviceId: string): Promise {
- let info: UsbLinkInfo;
- try {
- info = await desktop.usbOpen(deviceId);
- } catch (cause) {
- throw asPipeError(cause, "connection");
- }
- const control = new NativePipe("control", info.handle, info.controlPacketSize);
- // The stream channel, under the backend's own name for the pair — see {@link NativePipe.plane}.
- const stream = new NativePipe("bulk", info.handle, info.bulkPacketSize);
- return {
- info,
- control,
- stream,
- disconnected() {
- const error = new PipeError("closed", "The device was unplugged.");
- control.fail(error);
- stream.fail(error);
- },
- async close() {
- await control.close();
- await stream.close();
- try {
- await desktop.usbClose(info.handle);
- } catch {
- // Closing a link whose device is already gone is the normal unplug path.
- }
- },
- };
-}
-
-export interface NativeWatcherOptions extends ClientOptions {
- /** Injected by tests; defaults to the real Tauri bridge. */
- bridge?: Bridge;
- /** Pause between hot-plug connect attempts; tests shrink it. */
- hotplugRetryDelayMs?: number;
-}
-
-/**
- * How a hot-plug connect is allowed to fail before it is a real error.
- *
- * The OS announces a device the moment it enumerates, which can be *before* it is claimable: nusb's
- * own hot-plug docs say to retry after a short delay, and macOS has the same window while IOKit is
- * still matching drivers. One failed attempt at that instant must not park the session in a dead
- * `error` state, because the error chip reads as "No device".
- */
-const HOTPLUG_CONNECT_ATTEMPTS = 5;
-const HOTPLUG_RETRY_DELAY_MS = 400;
-
-const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
-
-/** The slice of the Tauri bridge discovery uses, named so a test can drive the real code paths. */
-export interface Bridge {
- usbWatch(onEvent: Channel): Promise;
- usbList(): Promise;
-}
-
-/**
- * Finds the device, keeps up with plugging and unplugging, and owns the {@link FlatStoreClient}.
- *
- * The same three-method shape as `WebUsbWatcher`, so `WatchedDeviceSession` wraps either one and the
- * UI above never learns which.
- */
-export class NativeWatcher implements DeviceWatcher {
- private readonly options: NativeWatcherOptions;
- private readonly bridge: Bridge;
- private readonly listeners = new Set<(state: DeviceState) => void>();
-
- private link: NativeLink | null = null;
- private state: DeviceState = { status: "idle", client: null, store: null, info: null, error: null };
-
- constructor(options: NativeWatcherOptions = {}) {
- this.options = options;
- this.bridge = options.bridge ?? desktop;
- }
-
- get current(): DeviceState {
- return this.state;
- }
-
- subscribe(listener: (state: DeviceState) => void): () => void {
- this.listeners.add(listener);
- listener(this.state);
- return () => this.listeners.delete(listener);
- }
-
- /**
- * Start watching for hot-plug and adopt a device that is already attached.
- *
- * No gesture and no prompt, ever — that restriction is WebUSB's. Returns whether a device
- * connected. The initial adopt runs through the same retrying flow the hot-plug path uses: an app
- * launched moments after the cable went in hits the same not-yet-claimable window.
- */
- async start(): Promise {
- const channel = new Channel();
- channel.onmessage = (event) => this.onEvent(event);
- let devices: UsbDeviceSummary[];
- try {
- devices = await this.bridge.usbWatch(channel);
- } catch (cause) {
- this.publish({ ...this.state, status: "error", error: describe(cause) });
- return false;
- }
- return devices.length > 0 ? this.adopt(devices[0]) : false;
- }
-
- /**
- * Look for a device now. The native counterpart of the browser's chooser, and deliberately not a
- * dialog: this host can see the device without asking anyone. It stays because the UI's Connect
- * button calls it, and a button that re-scans is reasonable.
- */
- async requestDevice(): Promise {
- if (this.state.status === "ready") return true;
- // Claim the flow before anything async: from here the click owns the published state, and a
- // sleeping adopt loop stands down instead of racing it for the one interface claim.
- const token = this.claimFlow();
- this.publish({ ...this.state, status: "connecting", error: null });
- let devices: UsbDeviceSummary[];
- try {
- devices = await this.bridge.usbList();
- } catch (cause) {
- if (this.owns(token)) {
- this.publish({ status: "error", client: null, store: null, info: null, error: describe(cause) });
- }
- return false;
- }
- if (!this.owns(token)) return false;
- if (devices.length === 0) {
- this.publish({
- status: "idle",
- client: null,
- store: null,
- info: null,
- error: null,
- });
- return false;
- }
- return this.adopt(devices[0], token);
- }
-
- /** Drop the link but keep watching, so re-plugging reconnects. */
- async disconnect(): Promise {
- // A deliberate disconnect outranks any connect flow still in flight: claim the flow so a
- // sleeping adopt loop stands down and an in-flight attempt finishes into silence.
- this.claimFlow();
- this.chasing = null;
- const client = this.state.client;
- this.publish({ status: "idle", client: null, store: null, info: null, error: null });
- this.link = null;
- await client?.close();
- }
-
- /** Stop following this session. The backend's watch outlives it and is re-pointed on the next
- * `start()`, which is what makes a window reload cheap. */
- async close(): Promise {
- await this.disconnect();
- this.listeners.clear();
- }
-
- // At most one connect flow may drive the published state and `this.link` at a time, but three
- // things can start one — the hot-plug adopt loop, the Connect click, `start()`'s initial probe —
- // and a running flow parks on awaits where any of the others can overtake it. So every flow
- // claims a monotonically increasing token, claiming invalidates every older flow, and each older
- // flow notices at its next step and stands down *silently*: it must not publish over the winner,
- // must not null a link it no longer owns, and must close any link it did open, because the Rust
- // side holds the interface claim until it is closed and an orphaned claim makes every later open
- // fail "busy" until a physical replug.
-
- /** The current flow's token. Bump-to-claim. */
- private flow = 0;
- /** The device id the current flow is chasing while it has no link yet — how a `disconnected`
- * event can end a flow whose device vanished mid-attempt. */
- private chasing: string | null = null;
-
- private claimFlow(): number {
- return ++this.flow;
- }
-
- private owns(token: number): boolean {
- return this.flow === token;
- }
-
- /**
- * One connect attempt: publish `connecting`, open, handshake, publish `ready` — with every
- * publish and every `this.link` write gated on still owning `token`. A failure publishes nothing
- * terminal and returns the failure's sentence; the *caller* owns the verdict.
- */
- private async connectOnce(device: UsbDeviceSummary, token: number): Promise<{ ok: boolean; error?: string }> {
- if (!this.owns(token)) return { ok: false };
- this.publish({ ...this.state, status: "connecting", error: null });
- let link: NativeLink | null = null;
- try {
- link = await openNativeLink(device.id);
- const client = new FlatStoreClient(link, { timeoutMs: this.options.timeoutMs });
- // The EP0 read first, mirroring `WebUsbWatcher.connect`, except that this host cannot
- // issue one. Only `unavailable` is caught: a device that answered a request badly is a
- // real failure and must not be rounded down to "no info".
- let info: DeviceInfo | null;
- try {
- info = await client.deviceInfo();
- } catch (cause) {
- if (!(cause instanceof DeviceError) || cause.code !== "unavailable") throw cause;
- info = null;
- }
- // Then `LIST`, which every client issues before anything else and which carries the
- // store's identity. The wire major is settled by descriptor matching, not read here.
- let store: DeviceState["store"];
- try {
- const page = await client.listPage({});
- store = { storeId: page.storeId, commitSequence: page.commitSequence };
- } catch (cause) {
- if (!isFormatRecoveryState(cause)) throw cause;
- store = null;
- }
- if (!this.owns(token)) {
- // A newer flow (or a disconnect) took the state while this handshake ran. The
- // connection itself is real, so it must be closed, not dropped.
- await client.close().catch(() => undefined);
- return { ok: false };
- }
- this.link = link;
- this.publish({
- status: "ready",
- client,
- store,
- info,
- error: null,
- });
- return { ok: true };
- } catch (cause) {
- // A device claimed but never handshaken still holds its interface, and an interface can
- // be claimed once, so releasing it lets a retry get at the device instead of finding it
- // busy. `this.link` is deliberately not touched: a newer flow's may already be in there.
- await link?.close().catch(() => undefined);
- return { ok: false, error: describe(cause) };
- }
- }
-
- /**
- * Connect to a device, retrying over the window in which the OS has announced it but not
- * finished setting it up — the shared flow behind the hot-plug event, `start()`'s initial probe
- * and the Connect click. Between attempts the loop re-checks that the device is still attached,
- * so a re-unplug ends in `idle` rather than an error about a device that is not there.
- */
- private async adopt(device: UsbDeviceSummary, token: number = this.claimFlow()): Promise {
- if (this.owns(token)) this.chasing = device.id;
- try {
- let lastError = "The device could not be opened.";
- for (let attempt = 1; attempt <= HOTPLUG_CONNECT_ATTEMPTS; attempt++) {
- const result = await this.connectOnce(device, token);
- if (result.ok) return true;
- // Superseded by a newer event, a Connect click or a disconnect — stand down silently
- // rather than fight over the published state. This covers the final attempt too.
- if (!this.owns(token)) return false;
- if (result.error !== undefined) lastError = result.error;
- if (attempt < HOTPLUG_CONNECT_ATTEMPTS) {
- await delay(this.options.hotplugRetryDelayMs ?? HOTPLUG_RETRY_DELAY_MS);
- if (!this.owns(token)) return false;
- }
- // Still attached? Between attempts this decides whether to keep trying; after the
- // final one it decides between the honest `idle` and the device's own error.
- const present = await this.stillAttached(device.id);
- if (!this.owns(token)) return false;
- if (present === false) {
- this.publish({ status: "idle", client: null, store: null, info: null, error: null });
- return false;
- }
- }
- this.publish({ status: "error", client: null, store: null, info: null, error: lastError });
- return false;
- } finally {
- if (this.owns(token)) this.chasing = null;
- }
- }
-
- /** Whether `deviceId` is still listed; null when the probe itself failed (unknown). */
- private async stillAttached(deviceId: string): Promise {
- try {
- return (await this.bridge.usbList()).some((d) => d.id === deviceId);
- } catch {
- return null;
- }
- }
-
- private onEvent(event: UsbEvent): void {
- switch (event.type) {
- case "connected":
- if (this.state.status === "ready") return;
- void this.adopt(event.device);
- return;
- case "disconnected": {
- if (this.link && this.link.info.deviceId === event.id) {
- // Fail the pipes *before* awaiting anything: every pending read and write
- // settles now, so an in-flight transfer's UI reports "unplugged".
- this.link.disconnected();
- const client = this.state.client;
- this.link = null;
- this.publish({ status: "idle", client: null, store: null, info: null, error: null });
- void client?.close();
- return;
- }
- // No link yet, but a connect flow is chasing exactly this device: end it in the
- // honest state now. The in-flight attempt sees a stale token and says nothing.
- if (this.chasing === event.id) {
- this.claimFlow();
- this.chasing = null;
- this.publish({ status: "idle", client: null, store: null, info: null, error: null });
- }
- return;
- }
- case "watchFailed":
- // Only meaningful when there is nothing connected: a live link keeps working without
- // hot-plug, and replacing it with an error would be a lie about what is wrong.
- if (this.state.status === "idle") {
- this.publish({ ...this.state, status: "error", error: event.message });
- }
- return;
- }
- }
-
- private publish(state: DeviceState): void {
- this.state = state;
- for (const listener of this.listeners) listener(state);
- }
-}
-
-function describe(cause: unknown): string {
- if (cause instanceof Error) return cause.message;
- const message = (cause as { message?: unknown } | null)?.message;
- return typeof message === "string" ? message : String(cause);
-}
diff --git a/builder/web/src/lib/device-sync/area.test.ts b/builder/web/src/lib/device-sync/area.test.ts
new file mode 100644
index 0000000000..02c0c44402
--- /dev/null
+++ b/builder/web/src/lib/device-sync/area.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from 'vitest';
+import { exampleCatalog } from '../catalog/testdata';
+import { deviceArea, sameArea, sameMap, type MapArea } from './area';
+
+const regions = exampleCatalog.regions;
+const box = { minLat: 46_000_000, minLon: 8_000_000, maxLat: 46_500_000, maxLon: 9_000_000 };
+const sent: MapArea = { regions: ['europe/switzerland/basel-stadt'], boxes: [box], light: 'default', dark: 'custom-night' };
+
+describe('deviceArea', () => {
+ it('is the area of the map that this browser sent, while that map is on the card', () => {
+ expect(deviceArea({ map: 'Alps', mapObject: '7:2', built: { object: '7:2', ...sent } }, regions)).toEqual(sent);
+ expect(deviceArea({ map: 'Alps', mapObject: '7:3', built: { object: '7:2', ...sent } }, regions)).toBeNull();
+ });
+
+ it('is the catalog region with the name of the map, in the first colours of the catalog', () => {
+ expect(deviceArea({ map: 'Switzerland', mapObject: '7:1', built: null }, regions))
+ .toEqual({ regions: ['europe/switzerland'], boxes: [], light: 'default', dark: 'dusk' });
+ });
+
+ it('is not known for another map, for no map and for no device', () => {
+ expect(deviceArea({ map: 'Alps', mapObject: '7:1', built: null }, regions)).toBeNull();
+ expect(deviceArea({ map: null, mapObject: null, built: null }, regions)).toBeNull();
+ expect(deviceArea(null, regions)).toBeNull();
+ });
+});
+
+describe('sameMap', () => {
+ const map: MapArea = { regions: ['a', 'b'], boxes: [box, { ...box, maxLon: 9_500_000 }], light: 'default', dark: 'dusk' };
+
+ it('takes the regions and the boxes in any order', () => {
+ expect(sameMap(map, { ...map, regions: ['b', 'a'], boxes: [...map.boxes].reverse() })).toBe(true);
+ expect(sameMap(map, { ...map, regions: ['a'] })).toBe(false);
+ expect(sameMap(map, { ...map, boxes: [box, box] })).toBe(false);
+ });
+
+ it('sees other colours as the same area and another map', () => {
+ expect(sameArea(map, { ...map, dark: 'custom-night' })).toBe(true);
+ expect(sameMap(map, { ...map, dark: 'custom-night' })).toBe(false);
+ });
+});
diff --git a/builder/web/src/lib/device-sync/area.ts b/builder/web/src/lib/device-sync/area.ts
new file mode 100644
index 0000000000..49114711b9
--- /dev/null
+++ b/builder/web/src/lib/device-sync/area.ts
@@ -0,0 +1,29 @@
+/** Compares the area and the colours of two device maps, and gives those of the map on the device. */
+import type { MapBox, NextMap } from '../library/records';
+import type { RememberedDevice } from './remembered.svelte';
+
+/** The regions, the boxes and the colours of a device map. */
+export type MapArea = Omit;
+
+/**
+ * The area and the colours of the map on the device, or null where this browser does not know them. It knows a map
+ * that it sent. A map with the name of one catalog region is that region, in the first colours of the catalog.
+ */
+export function deviceArea(device: Pick | null, regions: { id: string; name: string }[]): MapArea | null {
+ if (!device) return null;
+ if (device.built && device.built.object === device.mapObject) {
+ const { regions, boxes, light, dark } = device.built;
+ return { regions, boxes, light, dark };
+ }
+ const named = regions.filter(region => region.name === device.map);
+ return named.length === 1 ? { regions: [named[0].id], boxes: [], light: 'default', dark: 'dusk' } : null;
+}
+
+const boxKey = (box: MapBox) => `${box.minLat},${box.minLon},${box.maxLat},${box.maxLon}`;
+const sameSet = (a: string[], b: string[]) => new Set(a).size === new Set(b).size && a.every(value => b.includes(value));
+
+/** The two maps have the same regions and the same boxes, in any order. */
+export const sameArea = (a: MapArea, b: MapArea) => sameSet(a.regions, b.regions) && sameSet(a.boxes.map(boxKey), b.boxes.map(boxKey));
+
+/** The two maps have the same area and the same colours. */
+export const sameMap = (a: MapArea, b: MapArea) => sameArea(a, b) && a.light === b.light && a.dark === b.dark;
diff --git a/builder/web/src/lib/device-sync/map.svelte.ts b/builder/web/src/lib/device-sync/map.svelte.ts
new file mode 100644
index 0000000000..df8559b73e
--- /dev/null
+++ b/builder/web/src/lib/device-sync/map.svelte.ts
@@ -0,0 +1,66 @@
+/** Builds the device map that waits, in this tab, and sends it to the device. It needs the wasm core of the map builder. */
+import { CatalogClient } from '../catalog/client';
+import { mapWorkBusy } from '../cells/workBarrier';
+import { MapRun } from '../coverage/run.svelte';
+import { CoverageStore } from '../coverage/store.svelte';
+import type { JobContext } from '../device/progress';
+import type { NextMap } from '../library/records';
+import { platform } from '../platform';
+import type { FlatStoreClient } from '../usb/client';
+import type { PutResponse } from '../usb/protocol';
+import { sameMap } from './area';
+import { until } from './until';
+
+/**
+ * Downloads the cells of `next`, assembles them and puts the map on the device as one run that `ctx.signal` stops.
+ * It builds exactly `next` or nothing: the caller records `next` as the map on the device. `waits` is called when another
+ * map build holds the working files. While the run goes, the browser asks before it closes the tab.
+ */
+export async function buildMap(next: NextMap, client: FlatStoreClient, ctx: JobContext, waits: () => void): Promise {
+ const leave = (event: BeforeUnloadEvent) => event.preventDefault();
+ window.addEventListener('beforeunload', leave);
+ let run: MapRun | undefined;
+ try {
+ const { url, body } = await until(platform.catalog(), ctx.signal);
+ const store = new CoverageStore(CatalogClient.fromBody(body, url, { fetchImpl: platform.catalogFetch }), body);
+ store.setArea(next);
+ // The selection leaves out a region that the catalog does not hold and a box that the grid refuses, and it takes
+ // the first map style for one that is not there.
+ if (!sameMap(store.area(), next)) throw new Error('This area cannot be built: a part or a map style of it is not there any more. Choose the area again.');
+ if (await until(mapWorkBusy(), ctx.signal)) waits();
+ run = new MapRun(store);
+ run.start();
+ await ready(store, run, ctx.signal);
+ return await run.sendToDevice(client, ctx);
+ } finally {
+ window.removeEventListener('beforeunload', leave);
+ run?.destroy();
+ }
+}
+
+/** Resolves when the run can start, and rejects with the reason why it never can. */
+function ready(store: CoverageStore, run: MapRun, signal: AbortSignal): Promise {
+ return new Promise((resolve, reject) => {
+ let stop = () => {};
+ const end = (error?: unknown) => {
+ signal.removeEventListener('abort', aborted);
+ // The effect that calls this is inside the root that `stop` ends.
+ queueMicrotask(() => stop());
+ if (error === undefined) resolve();
+ else reject(error);
+ };
+ const aborted = () => end(signal.reason);
+ if (signal.aborted) return reject(signal.reason);
+ signal.addEventListener('abort', aborted, { once: true });
+ stop = $effect.root(() => {
+ $effect(() => {
+ const area = store.indexError ?? store.resolutionError ?? [...store.regionErrors.values()][0];
+ if (area) end(new Error(`This area cannot be built: ${area}`));
+ else if (store.ledger?.isFinal && store.ledger.cellCount === 0) end(new Error('This area cannot be built: the map catalog has no map data for it.'));
+ else if (run.refusal) end(new Error(run.refusal));
+ else if (run.estimateError) end(new Error(`The memory check failed: ${run.estimateError}`));
+ else if (run.ready) end();
+ });
+ });
+ });
+}
diff --git a/builder/web/src/lib/device-sync/metadata.ts b/builder/web/src/lib/device-sync/metadata.ts
new file mode 100644
index 0000000000..513f98a513
--- /dev/null
+++ b/builder/web/src/lib/device-sync/metadata.ts
@@ -0,0 +1,31 @@
+/** Reads the rides that the card marks as taken from its Metadata object (`specs/ride-archive-metadata.md`). */
+
+/** The exact source of a ride that a row of the Metadata object marks. */
+export interface ArchivedRow {
+ objectId: bigint;
+ revision: bigint;
+ payloadLength: bigint;
+ payloadCrc32: number;
+}
+
+const HEADER = 32, ROW = 40, MAX_ROWS = 128;
+
+/** The rows of an `OBRM` version 2 payload. It throws for another magic, version or layout. */
+export function archivedRows(bytes: Uint8Array): ArchivedRow[] {
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ if (bytes.length < HEADER || String.fromCharCode(...bytes.subarray(0, 4)) !== 'OBRM' || view.getUint16(4, true) !== 2
+ || view.getUint16(6, true) !== HEADER || view.getUint16(8, true) !== ROW) {
+ throw new Error('The ride metadata of the device cannot be read.');
+ }
+ const count = view.getUint16(10, true);
+ if (count > MAX_ROWS || bytes.length < HEADER + count * ROW) throw new Error('The ride metadata of the device cannot be read.');
+ return Array.from({ length: count }, (_, i) => {
+ const at = HEADER + i * ROW;
+ return {
+ objectId: view.getBigUint64(at, true),
+ revision: view.getBigUint64(at + 8, true),
+ payloadLength: view.getBigUint64(at + 16, true),
+ payloadCrc32: view.getUint32(at + 24, true),
+ };
+ });
+}
diff --git a/builder/web/src/lib/device-sync/remembered.svelte.ts b/builder/web/src/lib/device-sync/remembered.svelte.ts
new file mode 100644
index 0000000000..a293df8332
--- /dev/null
+++ b/builder/web/src/lib/device-sync/remembered.svelte.ts
@@ -0,0 +1,92 @@
+/** Remembers the one device that the sync works with, and what the last sync found on it, in `localStorage`. */
+import { deviceHolder } from '../device/session.svelte';
+import type { MapBox } from '../library/records';
+
+/** Bytes on the card by the kind of object. */
+export interface DeviceBytes { map: number; routes: number; rides: number; other: number }
+
+export interface RememberedDevice {
+ serial: string;
+ /** The card of the device. Another card makes `skipped` void. */
+ storeId: string;
+ /** Unix milliseconds of the end of the last sync, or null before the first. */
+ at: number | null;
+ /** The name of the map on the card, or null without one. */
+ map: string | null;
+ /** `objectId:revision` of the map on the card, or null without one. */
+ mapObject: string | null;
+ /** The area and the colours of the map `object` that this browser sent to the card. */
+ built: { object: string; regions: string[]; boxes: MapBox[]; light: string; dark: string } | null;
+ routes: number;
+ bytes: DeviceBytes;
+ /** The rides that came in on `day`, a local `YYYY-MM-DD`. */
+ came: { day: string; count: number } | null;
+ /** The `ObjectId`s of the rides that the library does not take: demo rides and rides with no points or no clock. */
+ skipped: string[];
+}
+
+const KEY = 'obc-device';
+
+function isDevice(value: unknown): value is RememberedDevice {
+ const v = value as Partial | null;
+ return !!v && typeof v.serial === 'string' && typeof v.storeId === 'string' && Array.isArray(v.skipped) && typeof v.bytes === 'object';
+}
+
+function stored(): RememberedDevice | null {
+ try {
+ const value = JSON.parse(localStorage.getItem(KEY) ?? 'null');
+ return isDevice(value) ? value : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The remembered device. Before a Connect button remembers one, it is null and no sync runs. */
+export const remembered = $state<{ device: RememberedDevice | null }>({ device: stored() });
+
+// Another tab remembered a device or synced.
+if (typeof window !== 'undefined') {
+ window.addEventListener('storage', event => { if (event.key === KEY || event.key === null) remembered.device = stored(); });
+}
+
+function save(device: RememberedDevice | null): void {
+ remembered.device = device;
+ try { localStorage.setItem(KEY, JSON.stringify(device)); } catch { /* The device stays remembered for this page. */ }
+}
+
+/** Merges `change` onto the remembered device; nothing without one. */
+export function remember(change: Partial): void {
+ const device = stored() ?? $state.snapshot(remembered.device);
+ if (device) save({ ...device, ...change });
+}
+
+const listeners = new Set<() => void>();
+
+/** Calls `listener` after each `rememberDevice`. Returns the function that stops it. */
+export function onRemember(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+/** Remembers the card `storeId` of the device `serial`, with a new record for a new serial or card. */
+export function rememberCard(serial: string, storeId: string): void {
+ const device = remembered.device;
+ if (device?.serial === serial && device.storeId === storeId) return;
+ save({ serial, storeId, at: null, map: null, mapObject: null, built: null, routes: 0, bytes: { map: 0, routes: 0, rides: 0, other: 0 }, came: null, skipped: [] });
+}
+
+/** Remembers the connected device. Only the Connect button of the Device page calls it; a sync follows. */
+export function rememberDevice(info: { serialNumber: string }, store: { storeId: string }): void {
+ rememberCard(info.serialNumber, store.storeId);
+ for (const listener of listeners) listener();
+}
+
+/** The factory name of a device: `OBC-` and the last four hex digits of its serial, as the device names itself. */
+export const deviceName = (serial: string) => `OBC-${serial.slice(-4).toUpperCase()}`;
+
+/** Whether the remembered device is the `ready` device of the session, with a card that has a format. Reactive where a
+ * component reads it. */
+export function rememberedReady(): boolean {
+ const session = deviceHolder.session;
+ return session?.status === 'ready' && !!session.store && !!remembered.device && session.info?.serialNumber === remembered.device.serial;
+}
diff --git a/builder/web/src/lib/device-sync/ride.ts b/builder/web/src/lib/device-sync/ride.ts
new file mode 100644
index 0000000000..0796d7d3dd
--- /dev/null
+++ b/builder/web/src/lib/device-sync/ride.ts
@@ -0,0 +1,32 @@
+/** Turns a ride object of the device into its samples and its library record. */
+import type { FitSample } from '../core/fit';
+import { dateName, rideKeyAt } from '../library/import';
+import type { Bike, RideRecord } from '../library/records';
+import { rideSummary } from '../library/summary';
+import type { RideObject } from '../usb/objects';
+
+/** The bike types of the device, by their number in the ride footer. */
+const deviceBikes: Bike[] = ['road', 'gravel', 'mtb', 'touring'];
+
+/** The samples of a ride object, with no key for a value that the sensor did not give. The device and `FitSample` both
+ * store positions in microdegrees (`specs/ble-interface.md` §7.2), so the positions copy through. The time of a sample is
+ * the start time plus its milliseconds after the first sample, modulo 2³² because the clock of the device wraps there. */
+export function deviceSamples(ride: RideObject): FitSample[] {
+ const first = ride.points[0]?.tMs ?? 0;
+ return ride.points.map(({ tMs, latMicrodegrees, lonMicrodegrees, elevationM, segmentStart, hrBpm, cadenceRpm, powerW }) => ({
+ timeS: ride.startTime + ((tMs - first) >>> 0) / 1000, lat: latMicrodegrees, lon: lonMicrodegrees, elevationM, segmentStart,
+ ...hrBpm !== null && { hrBpm }, ...cadenceRpm !== null && { cadenceRpm }, ...powerW !== null && { powerW },
+ }));
+}
+
+/** The library record of a ride object, with `device` set to `ref` (`storeId:objectId`). Null for a demo ride, a ride with no
+ * points, and a ride that started before the device had a clock. */
+export function rideRecord(ride: RideObject, ref: string): RideRecord | null {
+ if (ride.isDemo || !ride.points.length || !ride.startTime) return null;
+ const bike = deviceBikes[ride.bikeType], summary = rideSummary(deviceSamples(ride), bike);
+ return {
+ key: rideKeyAt(summary.start), name: ride.name || dateName(summary.start, bike), source: 'device', format: 'obcride', summary,
+ maxHr: ride.effortLimits.maxHrBpm, ftp: ride.effortLimits.ftpW, device: ref,
+ ...ride.trip && { trip: { key: ride.trip.key.toString(), day: ride.trip.dayIndex + 1, name: ride.trip.name } },
+ };
+}
diff --git a/builder/web/src/lib/device-sync/route.ts b/builder/web/src/lib/device-sync/route.ts
new file mode 100644
index 0000000000..7c6c7b38bc
--- /dev/null
+++ b/builder/web/src/lib/device-sync/route.ts
@@ -0,0 +1,41 @@
+/** Encodes a plan with its calculated line as one OBCR route for the device, also a plan of several days. */
+import { lineToObcr, type LineWaypoint } from '../convert/bridge';
+import { dayStops, planTitle, planView, type RoutePoint } from '../planner/editor';
+import { coordinateAt } from '../planner/geo';
+import type { Plan } from '../planner/library';
+import { poiKinds, type PlaceCategory } from '../planner/poi-kinds';
+import { SURFACES, type RoutingLine } from '../planner/routing';
+
+/** The device reads this many waypoints of a route (`MAX_WAYPOINTS` of `obc-route`). */
+export const MAX_WAYPOINTS = 32;
+
+/** The device numbers of `PoiCategory` (`firmware/obc-formats/src/obcm.rs`); another place is generic, 0. */
+const categories: Partial> = { water: 1, camp: 2, hotel: 3, shop: 4, food: 4, pharmacy: 5, bike: 6 };
+/** The device bike types: on foot is Touring. */
+const bikes = { road: 0, gravel: 1, mtb: 2, touring: 3, hiking: 3 };
+
+const micro = (degrees: number) => Math.round(degrees * 1e6);
+function categoryOf(point?: RoutePoint): number {
+ const kind = point?.placeKind && poiKinds[point.placeKind];
+ return kind ? categories[kind.category] ?? 0 : 0;
+}
+
+/** The route file of `plan` along `line`, the line that `calculateLine` gave for it. The waypoints are the nights, then the
+ * stops in route order, at most `MAX_WAYPOINTS`; `left` counts the others. */
+export async function routeObcr(plan: Plan, line: RoutingLine): Promise<{ bytes: Uint8Array; left: number }> {
+ const trip = plan.trip, view = planView(trip, line);
+ const nights = view.days.slice(0, -1).map((day): LineWaypoint => {
+ const [lon, lat] = day.pinned?.coordinate ?? coordinateAt(view.coordinates, day.to);
+ return { lon: micro(lon), lat: micro(lat), distanceM: day.to * view.total * 1000, category: categoryOf(day.pinned), name: day.pinned?.label || `Night ${day.number}` };
+ });
+ const stops = dayStops(trip, line, { from: 0, to: 1 }).map(({ point, km }): LineWaypoint =>
+ ({ lon: micro(point.coordinate[0]), lat: micro(point.coordinate[1]), distanceM: km * 1000, category: categoryOf(point), name: point.label }));
+ const waypoints = [...nights, ...stops];
+ const surfaces = line.edges.surfaces;
+ const bytes = await lineToObcr({
+ coordinates: Int32Array.from(line.coordinates.flatMap(([lon, lat]) => [micro(lon), micro(lat)])),
+ heights: line.elevation,
+ surfaces: Uint8Array.from(line.coordinates, (_, i) => Math.max(0, SURFACES.indexOf(surfaces?.[i - 1] ?? 'Unknown'))),
+ }, waypoints.slice(0, MAX_WAYPOINTS), plan.name || planTitle(trip), bikes[trip.bike ?? 'touring']);
+ return { bytes, left: Math.max(0, waypoints.length - MAX_WAYPOINTS) };
+}
diff --git a/builder/web/src/lib/device-sync/state.svelte.test.ts b/builder/web/src/lib/device-sync/state.svelte.test.ts
new file mode 100644
index 0000000000..d58bbeb572
--- /dev/null
+++ b/builder/web/src/lib/device-sync/state.svelte.test.ts
@@ -0,0 +1,60 @@
+// @vitest-environment happy-dom
+
+import { IDBFactory } from 'fake-indexeddb';
+import { flushSync } from 'svelte';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { deviceHolder } from '../device/session.svelte';
+import { Library } from '../library/store';
+import type { DeviceSession } from '../usb/session';
+import { rememberCard, remembered } from './remembered.svelte';
+import { deviceSync, startDeviceSync } from './state.svelte';
+import { syncDevice, type SyncReport } from './sync';
+
+vi.mock('./sync', () => ({ syncDevice: vi.fn() }));
+
+const SERIAL = '9F3A00C1E2B47D10';
+const session = (status: DeviceSession['status']) =>
+ ({ status, client: status === 'ready' ? {} : null, info: { serialNumber: SERIAL }, store: null }) as unknown as DeviceSession;
+const report = (tried: string[]): SyncReport => ({ rides: 0, marked: 0, sent: 0, removed: 0, waypointsLeft: 0, tried, problem: null });
+const settle = () => new Promise(resolve => setTimeout(resolve, 20));
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('startDeviceSync', () => {
+ it('syncs again after a reconnection during a sync, and not for its own writes', async () => {
+ vi.spyOn(deviceHolder, 'open').mockResolvedValue(null);
+ const library = new Library(new IDBFactory());
+ rememberCard(SERIAL, '8f2c41d96b074ea3b1559c207de83466');
+ let release!: () => void;
+ const signals: AbortSignal[] = [];
+ vi.mocked(syncDevice).mockImplementation(async (_client, _serial, lib, signal) => {
+ signals.push(signal);
+ if (signals.length === 1) await new Promise(resolve => release = resolve);
+ // A route that the routing cannot calculate stays in `waiting`; the write must start no sync.
+ await lib.changeState('waiting', () => ['offline']);
+ return report(['offline']);
+ });
+ deviceHolder.session = session('ready');
+ const stop = startDeviceSync(library);
+ flushSync();
+ await vi.waitFor(() => expect(signals).toHaveLength(1));
+
+ // The cable goes out and in while the first sync waits.
+ deviceHolder.session = session('idle');
+ flushSync();
+ expect(signals[0].aborted).toBe(true);
+ deviceHolder.session = session('ready');
+ flushSync();
+ release();
+ await vi.waitFor(() => expect(signals).toHaveLength(2));
+ await settle();
+ expect([signals.length, deviceSync.running]).toEqual([2, false]);
+
+ // Only an id that no sync tried starts one.
+ await library.changeState('waiting', ids => [...ids ?? [], 'new']);
+ await vi.waitFor(() => expect(signals).toHaveLength(3));
+ stop();
+ deviceHolder.session = null;
+ remembered.device = null;
+ });
+});
diff --git a/builder/web/src/lib/device-sync/state.svelte.ts b/builder/web/src/lib/device-sync/state.svelte.ts
new file mode 100644
index 0000000000..58f9943fc6
--- /dev/null
+++ b/builder/web/src/lib/device-sync/state.svelte.ts
@@ -0,0 +1,187 @@
+/** Starts the device sync of the shell, and shows the pages if it runs and what it did. It also runs the send of the map
+ * that waits, which only the rider starts. */
+import { untrack } from 'svelte';
+import { initCore } from '../core/bridge';
+import type { JobContext } from '../device/progress';
+import { deviceHolder } from '../device/session.svelte';
+import type { Library } from '../library/store';
+import { onRemember, remembered } from './remembered.svelte';
+import type { SyncReport } from './sync';
+import { until } from './until';
+
+/** One sync at a time in the whole browser: two tabs on one cable would send each route twice. */
+const LOCK = 'obc-device-sync';
+
+/** A step of the map send. `wait`: another map build holds the working files. `percent` is of the step. `storing`: the
+ * device has each byte and stores the map, so the send cannot stop any more. */
+export interface MapStep { phase: 'wait' | 'download' | 'build' | 'send'; percent: number; storing: boolean }
+
+class DeviceSync {
+ running = $state(false);
+ problem = $state(null);
+ report = $state.raw(null);
+ /** The map send that runs, or null. */
+ map = $state.raw(null);
+ /** Why the last map send did not put the map on the device; `stopped` when the rider stopped it. */
+ mapProblem = $state.raw<{ text: string; stopped: boolean } | null>(null);
+ private start = () => {};
+ private startMap = () => {};
+ private stopMap = () => {};
+
+ /** Starts a sync with the remembered device when it is ready, or after the sync that runs. */
+ run(): void { this.start(); }
+
+ /** Builds the map that waits and sends it to the remembered device, now or after the sync that runs. */
+ sendMap(): void { this.startMap(); }
+
+ /** Stops the map send that runs. */
+ stop(): void { this.stopMap(); }
+
+ /** For `startDeviceSync` only. */
+ setStart(start: () => void, startMap = () => {}, stopMap = () => {}): void {
+ this.start = start;
+ this.startMap = startMap;
+ this.stopMap = stopMap;
+ }
+}
+
+export const deviceSync = new DeviceSync();
+
+/**
+ * Syncs with the remembered device on each `ready` of it, after `rememberDevice`, on `deviceSync.run()`, and when a route
+ * starts to wait or to leave. With no remembered device, it opens no device session and never syncs. A sync never builds a
+ * map: only `deviceSync.sendMap()` does. The sync and the map send use one link, so each waits for the other. Returns the
+ * function that stops it.
+ */
+export function startDeviceSync(library: Library): () => void {
+ /** A change of `waiting` or `leaving` came during a sync. */
+ let again = false;
+ /** A connection or a new remembered device came during a sync: the next sync runs with no check. */
+ let fresh = false;
+ /** Aborts the sync that runs when the device leaves `ready`. */
+ let running: AbortController | null = null;
+ /** The ids that the last sync tried and left in `waiting` or `leaving`, such as a route that the routing could not
+ * calculate offline: only a new id, or the next connection, tries them again. */
+ let tried = new Set();
+ /** Aborts the map send that runs. */
+ let sending: AbortController | null = null;
+ /** The rider stopped the map send that runs. */
+ let stopped = false;
+ /** The rider asked for the map during a sync: the send starts after it. */
+ let mapWaits = false;
+
+ async function pending(): Promise {
+ const ids = new Set([...await library.state('waiting') ?? [], ...await library.state('leaving') ?? []]);
+ tried = new Set([...tried].filter(id => ids.has(id)));
+ return [...ids].some(id => !tried.has(id));
+ }
+
+ async function run(): Promise {
+ const session = deviceHolder.session, client = session?.client, serial = session?.info?.serialNumber;
+ // A map send ends with a sync.
+ if (session?.status !== 'ready' || !client || !serial || remembered.device?.serial !== serial || deviceSync.map) return;
+ if (deviceSync.running) { again = true; return; }
+ deviceSync.running = true;
+ const controller = running = new AbortController();
+ try {
+ const { syncDevice } = await import('./sync');
+ const work = () => syncDevice(client, serial, library, controller.signal);
+ const report = navigator.locks ? await navigator.locks.request(LOCK, { ifAvailable: true }, lock => lock ? work() : null) : await work();
+ if (report) {
+ deviceSync.report = report;
+ deviceSync.problem = report.problem;
+ tried = new Set(report.tried);
+ }
+ } catch (error) {
+ deviceSync.problem = error instanceof Error ? error.message : String(error);
+ } finally {
+ deviceSync.running = false;
+ running = null;
+ }
+ if (mapWaits) {
+ mapWaits = fresh = again = false;
+ void sendMap();
+ } else if (fresh) {
+ fresh = again = false;
+ void run();
+ } else if (again) {
+ again = false;
+ if (await pending()) void run();
+ }
+ }
+
+ async function sendMap(): Promise {
+ const session = deviceHolder.session, client = session?.client, serial = session?.info?.serialNumber;
+ if (session?.status !== 'ready' || !client || !serial || remembered.device?.serial !== serial || deviceSync.map) return;
+ if (deviceSync.running) { mapWaits = true; return; }
+ const controller = sending = new AbortController();
+ stopped = false;
+ deviceSync.mapProblem = null;
+ let phase: MapStep['phase'] = 'download', storing = false;
+ const show = (percent = 0) => {
+ const now = deviceSync.map;
+ if (now?.phase !== phase || now.percent !== percent || now.storing !== storing) deviceSync.map = { phase, percent, storing };
+ };
+ show();
+ const ctx: JobContext = {
+ signal: controller.signal,
+ cancel: reason => controller.abort(reason),
+ // After the last byte the device stores the map: the send stays at its end.
+ phase: job => {
+ storing = job === 'committing' || job === 'finalizing';
+ phase = job === 'downloading' ? 'download' : job === 'sending' || storing ? 'send' : 'build';
+ show(storing ? 100 : 0);
+ },
+ progress: (done, total) => show(total ? Math.floor(100 * done / total) : 0),
+ };
+ try {
+ const [sync, { buildMap }] = await until(Promise.all([import('./sync'), initCore().then(() => import('./map.svelte'))]), controller.signal);
+ const waits = () => { phase = 'wait'; show(); };
+ const problem = await sync.sendMap(serial, library, (next, job) => buildMap(next, client, job, waits), ctx);
+ if (problem) deviceSync.mapProblem = { text: problem, stopped };
+ } catch (error) {
+ // A stop before the build began left nothing to say.
+ if (!controller.signal.aborted) deviceSync.mapProblem = { text: error instanceof Error ? error.message : String(error), stopped: false };
+ } finally {
+ deviceSync.map = null;
+ sending = null;
+ }
+ // The sync reads the card again, and sends the routes that waited.
+ fresh = again = false;
+ void run();
+ }
+
+ function stopMap(): void {
+ if (deviceSync.map?.storing) return;
+ stopped = true;
+ sending?.abort(new DOMException('The rider stopped the map send.', 'AbortError'));
+ }
+
+ /** A sync now, or one more after the sync that runs, with no check of `tried`. */
+ function connected(): void {
+ if (deviceSync.running) fresh = true;
+ else void run();
+ }
+
+ deviceSync.setStart(connected, () => void sendMap(), stopMap);
+ if (remembered.device) void deviceHolder.open();
+ const stopEffect = $effect.root(() => {
+ $effect(() => {
+ const session = deviceHolder.session, ready = session?.status === 'ready' && session.client;
+ untrack(() => {
+ if (ready) return connected();
+ running?.abort();
+ sending?.abort();
+ });
+ });
+ });
+ const stopRemember = onRemember(connected);
+ const stopChange = library.onChange((store, key) => {
+ // The sentence of the last send was about another map.
+ if (store === 'state' && key === 'nextMap' && !deviceSync.map) deviceSync.mapProblem = null;
+ if (store !== 'state' || (key !== 'waiting' && key !== 'leaving')) return;
+ if (deviceSync.running) again = true;
+ else void pending().then(next => { if (next) void run(); });
+ });
+ return () => { stopEffect(); stopRemember(); stopChange(); deviceSync.setStart(() => {}); };
+}
diff --git a/builder/web/src/lib/device-sync/sync.test.ts b/builder/web/src/lib/device-sync/sync.test.ts
new file mode 100644
index 0000000000..a895f87a57
--- /dev/null
+++ b/builder/web/src/lib/device-sync/sync.test.ts
@@ -0,0 +1,303 @@
+import { IDBFactory } from 'fake-indexeddb';
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { loadFlatDevice } from '../../../test-support/flat-device/load';
+import { rideKeyAt } from '../library/import';
+import type { RouteRecord } from '../library/records';
+import { Library } from '../library/store';
+import { sentKey, summarize } from '../library/summary';
+import { emptyTrip, type DrawnCoordinate, type RoutePoint, type Trip } from '../planner/editor';
+import { newPlan, type Plan } from '../planner/library';
+import { DeviceError, type FlatStoreClient } from '../usb/client';
+import { flatDevice, streamCeilingFor } from '../usb/flat-device';
+import { encodeRideObject, type RideObject } from '../usb/objects';
+import { ObjectKind } from '../usb/protocol';
+import { archivedRows } from './metadata';
+import { rideRecord } from './ride';
+import { rememberCard, remembered } from './remembered.svelte';
+import { CABLE_OUT, MAP_LOST, NO_ROOM, sendMap, syncDevice } from './sync';
+
+beforeAll(loadFlatDevice);
+beforeEach(() => { remembered.device = null; });
+afterEach(() => vi.restoreAllMocks());
+
+const SERIAL = '9F3A00C1E2B47D10', CARD = '8f2c41d96b074ea3b1559c207de83466', OTHER_CARD = '11112222333344445555666677778888';
+
+function ride(start: number, extra: Partial = {}, points = 3): RideObject {
+ return {
+ version: 6, isDemo: false, name: '', startTime: start, distanceM: 0, movingTimeS: 0, avgSpeedCms: 0, climbM: 0, descentM: 0,
+ avgHr: null, maxHr: null, avgCadence: null, avgPower: null, maxPower: null, energyKj: null, bikeType: 1, trip: null,
+ effortLimits: { maxHrBpm: 186, ftpW: 240 },
+ // The clock of the device wraps during this ride.
+ points: Array.from({ length: points }, (_, i) => ({ tMs: (0xffff_f000 + i * 2000) >>> 0, latMicrodegrees: 47_000_000 + i * 100,
+ lonMicrodegrees: 8_000_000 + i * 100, elevationM: 400 + i, segmentStart: i === 0, hrBpm: 120, cadenceRpm: null, powerW: null })),
+ ...extra,
+ };
+}
+
+/** A point at `lon` on the parallel 47 at the end of a drawn leg, so no routing service is asked. */
+function point(id: string, kind: RoutePoint['kind'], lon: number, extra: Partial = {}): RoutePoint {
+ const drawn: DrawnCoordinate[] = [[lon - .05, 47, 400], [lon - .025, 47, 420], [lon, 47, 410]];
+ return { id, kind, label: id, coordinate: [lon, 47], ...kind !== 'start' && { leg: 'drawn', drawn }, ...extra };
+}
+
+function plan(finish = 8.15, leg?: RoutePoint['leg']): Plan {
+ const trip: Trip = { ...emptyTrip('trip'), days: 2, daysSet: true, routeOrder: ['night-1', 'Spring'], points: [
+ point('start', 'start', 8),
+ point('night-1', 'night', 8.05, { night: 1, label: 'Camp', placeKind: 'campsite' }),
+ point('Spring', 'waypoint', 8.1, { placeKind: 'drinking_water' }),
+ point('finish', 'finish', finish, leg && { leg }),
+ ] };
+ const summary = { ...summarize([[8, 47, 400], [finish, 47, 410]], { lengthM: 11_000, climbM: 20, seconds: 2400, bike: 'touring' as const }), days: 2 };
+ return { ...newPlan(trip, 'Black Forest'), summary };
+}
+
+function setup(storeId = CARD) {
+ const rig = flatDevice({ storeId, streamCeiling: streamCeilingFor(512) });
+ const library = new Library(new IDBFactory());
+ const sync = (client: Parameters[0] = rig.client) => syncDevice(client, SERIAL, library, new AbortController().signal);
+ const seedRide = (object: RideObject) => rig.device.seed({ kind: ObjectKind.Ride, displayName: 'ride', bytes: encodeRideObject(object) });
+ const routes = () => rig.device.entries.filter(entry => entry.kind === ObjectKind.Route);
+ const send = async (route: RouteRecord) => {
+ await library.saveRoute(route);
+ await library.changeState('waiting', ids => [...ids ?? [], route.id]);
+ };
+ return { rig, library, sync, seedRide, routes, send };
+}
+
+describe('syncDevice', () => {
+ it('takes each new ride once, keeps deleted and demo rides out, and counts what came in today', async () => {
+ const { rig, library, sync, seedRide } = setup();
+ rememberCard(SERIAL, CARD);
+ seedRide(ride(1_780_000_000));
+ const demo = seedRide(ride(1_780_050_000, { isDemo: true }));
+ seedRide(ride(1_780_100_000));
+ // A ride that the device still records cannot be fetched: a `get` of it would give a problem.
+ rig.device.seed({ kind: ObjectKind.Ride, displayName: 'recording' });
+ expect(await sync()).toMatchObject({ rides: 2, problem: null });
+ const keys = (await library.rides()).map(r => r.key).sort();
+ expect(keys).toEqual([rideKeyAt(1_780_000_000), rideKeyAt(1_780_100_000)]);
+ expect(remembered.device!.skipped).toEqual([demo.objectId.toString()]);
+ const taken = (await library.ride(keys[0]))!;
+ // The wrapped clock still gives four seconds from the first point to the last.
+ expect(taken).toMatchObject({ source: 'device', format: 'obcride', maxHr: 186, ftp: 240, summary: { bike: 'gravel', seconds: 4 } });
+
+ await library.removeRide(keys[1]);
+ seedRide(ride(1_780_200_000));
+ expect(await sync()).toMatchObject({ rides: 1 });
+ expect(await sync()).toMatchObject({ rides: 0 });
+ expect((await library.rides()).map(r => r.key).sort()).toEqual([keys[0], rideKeyAt(1_780_200_000)]);
+ expect(remembered.device!.came).toMatchObject({ count: 3 });
+ await rig.close();
+ });
+
+ it('marks only stored rides whose file is the exact object, and only with persistent storage', async () => {
+ const { rig, library, sync, seedRide } = setup();
+ rememberCard(SERIAL, CARD);
+ const persist = vi.spyOn(library, 'persist').mockResolvedValue(false);
+ const first = seedRide(ride(1_780_000_000));
+ expect(await sync()).toMatchObject({ rides: 1, marked: 0 });
+ expect(rig.device.entries.some(entry => entry.kind === ObjectKind.Metadata)).toBe(false);
+
+ // The same ride came from a file first, so the library does not hold the bytes of the device.
+ const fromFile = { ...(await library.ride(rideKeyAt(1_780_000_000)))!, key: rideKeyAt(1_780_300_000), source: 'file' as const, device: undefined };
+ await library.addRide({ ...fromFile, format: 'gpx' }, new Blob([' ']));
+ seedRide(ride(1_780_300_000));
+ // The rider deleted this ride, so the library rejects it and the device keeps it as not taken.
+ await library.addRide({ ...fromFile, key: rideKeyAt(1_780_400_000) }, new Blob([' ']));
+ await library.removeRide(rideKeyAt(1_780_400_000));
+ seedRide(ride(1_780_400_000));
+ persist.mockResolvedValue(true);
+ expect(await sync()).toMatchObject({ rides: 0, marked: 1 });
+ const metadata = rig.device.entries.find(entry => entry.kind === ObjectKind.Metadata)!;
+ expect(archivedRows(rig.device.payloadOf(metadata.objectId)!).map(row => row.objectId)).toEqual([first.objectId]);
+ expect(await sync()).toMatchObject({ marked: 0 });
+ await rig.close();
+ });
+
+ it('sends a route that waits, replaces it when it changed, creates it again when it is gone, and removes a deleted one', async () => {
+ const { rig, library, sync, routes, send } = setup();
+ rememberCard(SERIAL, CARD);
+ const route = plan();
+ await send(route);
+ expect(await sync()).toMatchObject({ sent: 1, waypointsLeft: 0, problem: null });
+ const [first] = routes();
+ expect(first.displayName).toBe('Black Forest');
+ // The night, then the stop, each with its category (`specs/obcr-route.md` §4).
+ const obcr = rig.device.payloadOf(first.objectId)!, view = new DataView(obcr.buffer, obcr.byteOffset);
+ const table = view.getUint32(112, true), waypoints = Array.from({ length: view.getUint16(116, true) }, (_, i) => table + i * 80);
+ expect(waypoints.map(at => [new TextDecoder().decode(obcr.subarray(at + 20, at + 20 + obcr[at + 15])), obcr[at + 14]]))
+ .toEqual([['Camp', 2], ['Spring', 1]]);
+ expect(await library.state('sent')).toEqual({ [route.id]: { device: `${CARD}:${first.objectId}`, key: sentKey(route) } });
+ expect(await library.state('waiting')).toEqual([]);
+
+ const changed = { ...(await library.route(route.id))!, trip: plan(8.2).trip };
+ await send(await library.saveRoute(changed));
+ await sync();
+ expect(routes()).toMatchObject([{ objectId: first.objectId }]);
+ expect(routes()[0].revision).toBeGreaterThan(first.revision);
+ // A new name leaves the line as it is, and still makes the device file old.
+ const renamed = await library.renameRoute(route.id, 'Black Forest loop');
+ expect((await library.state('sent'))![route.id].key).not.toBe(sentKey(renamed));
+
+ // The rider deletes the route on the device: the next sync forgets that it was sent.
+ await rig.client.remove(routes()[0]);
+ await sync();
+ expect(await library.state('sent')).toEqual({});
+ await send((await library.route(route.id))!);
+ await sync();
+ const [again] = routes();
+ expect(again.objectId).not.toBe(first.objectId);
+ expect((await library.state('sent'))![route.id].device).toBe(`${CARD}:${again.objectId}`);
+
+ await library.removeRoute(route.id);
+ expect(await sync()).toMatchObject({ removed: 1, tried: [route.id] });
+ expect([routes(), await library.state('sent'), await library.state('leaving')]).toEqual([[], {}, []]);
+ await rig.close();
+ });
+
+ it('removes a route that the rider deleted in the library during its first upload', async () => {
+ const { rig, library, sync, routes, send } = setup();
+ rememberCard(SERIAL, CARD);
+ const route = plan();
+ await send(route);
+ const client = rig.client, deleting: Parameters[0] = {
+ list: options => client.list(options), get: (...args) => client.get(...args), remove: (...args) => client.remove(...args),
+ archiveRide: (...args) => client.archiveRide(...args),
+ put: async (...args) => { const answer = client.put(...args); await library.removeRoute(route.id); return answer; },
+ };
+ await sync(deleting);
+ expect([routes(), await library.state('leaving')]).toMatchObject([[{ displayName: 'Black Forest' }], [route.id]]);
+ expect(await sync()).toMatchObject({ removed: 1 });
+ expect([routes(), await library.state('sent'), await library.state('leaving')]).toEqual([[], {}, []]);
+ await rig.close();
+ });
+
+ it('touches no object of another card that has the ObjectIds of the routes it sent', async () => {
+ const { rig, library, sync, send } = setup();
+ rememberCard(SERIAL, CARD);
+ const kept = plan(), deleted = plan(8.2);
+ await send(kept);
+ await send(deleted);
+ await sync();
+ await rig.close();
+ // The card is formatted, and the phone puts two routes with the same ObjectIds on it.
+ const other = setup(OTHER_CARD), phone = [1, 2].map(() => other.rig.device.seed({ kind: ObjectKind.Route, displayName: 'Phone', bytes: new Uint8Array(64) }));
+ expect(phone.map(entry => entry.objectId)).toEqual(Object.values((await library.state('sent'))!).map(route => BigInt(route.device.split(':')[1])));
+ await library.removeRoute(deleted.id);
+ await library.changeState('waiting', ids => [...ids ?? [], kept.id]);
+ const report = await syncDevice(other.rig.client, SERIAL, library, new AbortController().signal);
+ expect(report).toMatchObject({ problem: null, sent: 1, removed: 0 });
+ const [first, second, created] = other.routes();
+ expect([first, second]).toMatchObject(phone.map(entry => ({ objectId: entry.objectId, revision: entry.revision })));
+ expect([await library.state('sent'), await library.state('leaving')]).toEqual([{ [kept.id]: { device: `${OTHER_CARD}:${created.objectId}`, key: sentKey(kept) } }, []]);
+ await other.rig.close();
+ });
+
+ it('sends the routes that wait after the device refuses a ride and a mark', async () => {
+ const { rig, library, sync, routes, send, seedRide } = setup();
+ rememberCard(SERIAL, CARD);
+ seedRide(ride(1_780_000_000));
+ await sync();
+ seedRide(ride(1_780_100_000));
+ vi.spyOn(library, 'persist').mockResolvedValue(true);
+ await send(plan());
+ const client = rig.client, refusing: Parameters[0] = {
+ list: options => client.list(options), put: (...args) => client.put(...args), remove: (...args) => client.remove(...args),
+ get: (ref, options) => options?.expectedLength ? Promise.reject(new DeviceError('checksum', 'bad ride')) : client.get(ref, options),
+ archiveRide: () => Promise.reject(new DeviceError('busy', 'device busy')),
+ };
+ const report = await sync(refusing);
+ expect(report).toMatchObject({ rides: 0, marked: 0, sent: 1 });
+ expect(report.problem).toMatch(/bad ride.*device busy/);
+ expect(routes()).toHaveLength(1);
+ await rig.close();
+ });
+
+ it('keeps a route that waits when the routing service cannot be reached, and names it', async () => {
+ const { rig, library, sync, routes, send } = setup();
+ rememberCard(SERIAL, CARD);
+ vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('offline'));
+ const route = plan(8.15, 'routed');
+ await send(route);
+ const report = await sync();
+ expect(report.sent).toBe(0);
+ expect(report.problem).toContain('“Black Forest” waits');
+ expect([await library.state('waiting'), routes()]).toEqual([[route.id], []]);
+ await rig.close();
+ });
+
+ it('does not touch a device that is not remembered', async () => {
+ const { library } = setup();
+ const list = vi.fn();
+ expect(await syncDevice({ list } as unknown as FlatStoreClient, SERIAL, library, new AbortController().signal)).toMatchObject({ rides: 0 });
+ rememberCard('0000000000000001', CARD);
+ await syncDevice({ list } as unknown as FlatStoreClient, SERIAL, library, new AbortController().signal);
+ expect(list).not.toHaveBeenCalled();
+ });
+
+ it('keeps no ride when the cable comes out during its download', async () => {
+ const { rig, library, sync, seedRide } = setup();
+ rememberCard(SERIAL, CARD);
+ seedRide(ride(1_780_000_000, {}, 400));
+ const client = rig.client, cut: Parameters[0] = {
+ list: options => client.list(options), put: (...args) => client.put(...args), remove: (...args) => client.remove(...args),
+ archiveRide: (...args) => client.archiveRide(...args),
+ get: (ref, options) => client.get(ref, { ...options, onProgress: done => { if (done > 0) void rig.link.device.close(); } }),
+ };
+ expect(await sync(cut)).toMatchObject({ rides: 0, problem: CABLE_OUT });
+ expect(await library.rides()).toEqual([]);
+ await rig.close().catch(() => undefined);
+ });
+});
+
+describe('rideRecord', () => {
+ it('keeps the trip of the footer, with the key in decimal and the day from 1', () => {
+ const trip = { key: 2n ** 63n + 5n, dayIndex: 1, dayCount: 3, name: 'Alps' };
+ expect(rideRecord(ride(1_780_000_000, { trip }), 'card:1')?.trip).toEqual({ key: '9223372036854775813', day: 2, name: 'Alps' });
+ expect(rideRecord(ride(1_780_000_000), 'card:1')).not.toHaveProperty('trip');
+ });
+});
+
+describe('sendMap', () => {
+ const next = { regions: ['europe/switzerland'], boxes: [], light: 'default', dark: 'dusk', bytes: 870_000_000 };
+ const job = (controller = new AbortController()) =>
+ ({ signal: controller.signal, cancel: (reason?: unknown) => controller.abort(reason), phase() {}, progress() {} });
+
+ async function waiting() {
+ const library = new Library(new IDBFactory());
+ rememberCard(SERIAL, CARD);
+ await library.setState('nextMap', next);
+ return library;
+ }
+
+ it('remembers the area of the sent map, and the map waits no more unless the rider chose another one during the build', async () => {
+ const library = await waiting();
+ expect(await sendMap(SERIAL, library, async () => ({ objectId: 7n, revision: 2n }), job())).toBeNull();
+ expect(remembered.device).toMatchObject({ mapObject: '7:2',
+ built: { object: '7:2', regions: ['europe/switzerland'], boxes: [], light: 'default', dark: 'dusk' } });
+ expect(await library.state('nextMap')).toBeNull();
+
+ const other = { ...next, dark: 'custom-night' };
+ await library.setState('nextMap', next);
+ const build = async () => {
+ await library.setState('nextMap', other);
+ return { objectId: 7n, revision: 3n };
+ };
+ expect(await sendMap(SERIAL, library, build, job())).toBeNull();
+ expect(remembered.device?.built).toMatchObject({ object: '7:3', dark: 'dusk' });
+ expect(await library.state('nextMap')).toEqual(other);
+ });
+
+ it('keeps the map that waits and says why: a card with no room, a cut cable, a stop', async () => {
+ const library = await waiting();
+ const fail = (error: unknown) => async () => { throw error; };
+ expect(await sendMap(SERIAL, library, fail(new DeviceError('no-space', 'full')), job())).toBe(NO_ROOM);
+ expect(await sendMap(SERIAL, library, fail(new DeviceError('link', 'gone')), job())).toBe(MAP_LOST);
+ const stop = new AbortController();
+ stop.abort();
+ expect(await sendMap(SERIAL, library, fail(stop.signal.reason), job(stop))).toBe(MAP_LOST);
+ expect(await sendMap(SERIAL, library, fail(new Error('This area cannot be built: no data.')), job())).toBe('This area cannot be built: no data.');
+ expect(await library.state('nextMap')).toEqual(next);
+ expect(remembered.device?.built).toBeNull();
+ });
+});
diff --git a/builder/web/src/lib/device-sync/sync.ts b/builder/web/src/lib/device-sync/sync.ts
new file mode 100644
index 0000000000..5ba5aaf0be
--- /dev/null
+++ b/builder/web/src/lib/device-sync/sync.ts
@@ -0,0 +1,235 @@
+/** One sync with the remembered device: the new rides come into the library and are marked as taken, the deleted routes
+ * leave the device, and the routes that wait go to it. And one send of the map that waits. */
+import type { JobContext } from '../device/progress';
+import { displayName } from '../device/write';
+import type { NextMap } from '../library/records';
+import type { Library } from '../library/store';
+import { sentKey } from '../library/summary';
+import { planTitle } from '../planner/editor';
+import { isPlan } from '../planner/library';
+import { LegCache } from '../planner/route-legs';
+import { calculateLine } from '../planner/routing';
+import { takeDeviceValues } from '../settings/settings.svelte';
+import { DeviceError, type Catalog, type FlatStoreClient } from '../usb/client';
+import { Crc32 } from '../usb/crc32';
+import { decodeRideObject } from '../usb/objects';
+import { EntryFlags, ObjectKind, type CatalogEntry, type PutResponse } from '../usb/protocol';
+import { archivedRows } from './metadata';
+import { remember, rememberCard, remembered, type DeviceBytes } from './remembered.svelte';
+import { rideRecord } from './ride';
+import { routeObcr } from './route';
+
+/** What a sync uses of the client. */
+export type SyncClient = Pick;
+
+export interface SyncReport {
+ /** Rides that came into the library. */
+ rides: number;
+ /** Rides that the device now marks as taken. */
+ marked: number;
+ sent: number;
+ removed: number;
+ /** Waypoints of the sent routes past the 32 that the device reads. */
+ waypointsLeft: number;
+ /** The route ids that the sync tried to send or to remove. */
+ tried: string[];
+ /** What did not finish, in sentences for the rider; null when all finished. */
+ problem: string | null;
+}
+
+export const CABLE_OUT = 'The sync stopped when the cable came out. It goes on at the next connection.';
+export const NO_ROOM = 'The memory card has no room for the new map. The old map stays until the new one is complete, so the card needs room for both.';
+export const MAP_LOST = 'The new map was not sent. “Send the map” starts again.';
+
+/** Builds the map `next` and puts it on the device. The one of the app is `buildMap` of `map.svelte.ts`. */
+export type BuildMap = (next: NextMap, ctx: JobContext) => Promise>;
+
+const unused = (entry: CatalogEntry) => (entry.flags & (EntryFlags.Recording | EntryFlags.Retained)) === 0;
+const ofKind = (catalog: Catalog, kind: number) => catalog.entries.filter(entry => entry.kind === kind && unused(entry));
+const byId = (a: CatalogEntry, b: CatalogEntry) => a.objectId < b.objectId ? -1 : a.objectId > b.objectId ? 1 : 0;
+const text = (error: unknown) => error instanceof Error ? error.message : String(error);
+/** The link went away, or the run was cancelled: nothing more can be done in this run. */
+const cut = (error: unknown) => error instanceof DeviceError && ['link', 'timeout', 'aborted'].includes(error.code);
+const refused = (error: unknown, ...codes: string[]) => error instanceof DeviceError && codes.includes(error.code);
+
+function today(): string {
+ const now = new Date(), pad = (value: number) => String(value).padStart(2, '0');
+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
+}
+
+/** Runs one sync with the device `serial`, only when it is the remembered device. State writes use `changeState`, so a
+ * write of another tab or page is not lost. A ride is stored only after its whole `get`, and a route is `sent` only after
+ * its `put`, so a cut cable loses nothing. A lost `put` answer, and then a new line from the routing, can leave a second
+ * copy of a route on the device. */
+export async function syncDevice(client: SyncClient, serial: string, library: Library, signal: AbortSignal): Promise {
+ const report: SyncReport = { rides: 0, marked: 0, sent: 0, removed: 0, waypointsLeft: 0, tried: [], problem: null };
+ const problems: string[] = [];
+ if (remembered.device?.serial !== serial) return report;
+ try {
+ const catalog = await client.list({ signal });
+ rememberCard(serial, catalog.storeId);
+ const card = catalog.storeId, rides = ofKind(catalog, ObjectKind.Ride).sort(byId);
+ const ref = (entry: CatalogEntry) => `${card}:${entry.objectId}`;
+
+ const known = await library.deviceRides(), skipped = new Set(remembered.device!.skipped);
+ for (const entry of rides) {
+ const id = entry.objectId.toString();
+ if (known.has(ref(entry)) || skipped.has(id)) continue;
+ let bytes;
+ try { bytes = (await client.get(entry, { signal, expectedLength: Number(entry.payloadLength) })).bytes; } catch (error) {
+ if (cut(error)) throw error;
+ problems.push(text(error));
+ continue;
+ }
+ let record;
+ try { record = rideRecord(decodeRideObject(bytes), ref(entry)); } catch {
+ problems.push('A ride on the device cannot be read by this page. Reload the page to take it.');
+ continue;
+ }
+ if (!record) {
+ skipped.add(id);
+ remember({ skipped: [...skipped] });
+ } else if (await library.addRide(record, new Blob([bytes as Uint8Array]))) {
+ report.rides++;
+ takeDeviceValues(record.summary.start, record.maxHr, record.ftp);
+ const came = remembered.device!.came, day = today();
+ remember({ came: { day, count: came?.day === day ? came.count + 1 : 1 } });
+ }
+ }
+
+ // The device marks a ride as taken only while the browser keeps the library when the disk is full.
+ if (await library.persist()) report.marked = await mark(client, catalog, rides, library, signal, problems);
+
+ // A route sent to another card is not on this one: it has nothing to remove here, and a new send creates it.
+ const sent = await library.state('sent') ?? {};
+ for (const id of await library.state('leaving') ?? []) {
+ report.tried.push(id);
+ const entry = ofKind(catalog, ObjectKind.Route).find(e => ref(e) === sent[id]?.device);
+ try {
+ if (entry) await client.remove(entry, signal);
+ } catch (error) {
+ if (!refused(error, 'not-found')) { if (cut(error)) throw error; problems.push(text(error)); continue; }
+ }
+ await library.changeState('sent', routes => Object.fromEntries(Object.entries(routes ?? {}).filter(([other]) => other !== id)));
+ await library.changeState('leaving', ids => (ids ?? []).filter(other => other !== id));
+ if (entry) report.removed++;
+ }
+
+ const legs = new LegCache();
+ for (const id of await library.state('waiting') ?? []) {
+ report.tried.push(id);
+ const route = await library.item(id);
+ if (!route || !('revision' in route) || !isPlan(route)) { problems.push('A route that waits cannot be read.'); continue; }
+ const name = displayName(route.name || planTitle(route.trip), 'Route');
+ let file;
+ try { file = await routeObcr(route, await calculateLine(route.trip, signal, legs)); } catch (error) {
+ if (signal.aborted) throw error;
+ problems.push(`“${name}” waits: ${text(error)}`);
+ continue;
+ }
+ const crc = Crc32.of(file.bytes), length = BigInt(file.bytes.length), routes = ofKind(catalog, ObjectKind.Route);
+ const others = await library.state('sent') ?? {}, object = others[id]?.device;
+ // A lost answer of an earlier put left this copy; the copy of another route of the library is not it.
+ const taken = new Set(Object.entries(others).flatMap(([other, route]) => other === id ? [] : [route.device]));
+ const target = routes.find(e => ref(e) === object)
+ ?? routes.find(e => e.payloadLength === length && e.payloadCrc32 === crc && e.displayName === name && !taken.has(ref(e)));
+ // Without a target, the put creates an object.
+ const put = (on?: CatalogEntry) =>
+ client.put({ objectId: on?.objectId, expectedRevision: on?.revision, kind: ObjectKind.Route, displayName: name }, file.bytes, { signal });
+ let answer;
+ try {
+ answer = await put(target).catch(error => target && refused(error, 'not-found') ? put() : Promise.reject(error));
+ } catch (error) {
+ if (cut(error)) throw error;
+ problems.push(`“${name}” waits: ${text(error)}`);
+ continue;
+ }
+ await library.changeState('sent', routes => ({ ...routes, [id]: { device: `${card}:${answer.objectId}`, key: sentKey(route) } }));
+ // The rider deleted the route during its upload, after `removeRoute` looked at `sent`.
+ if (!await library.item(id)) await library.changeState('leaving', ids => [...(ids ?? []).filter(other => other !== id), id]);
+ await library.changeState('waiting', ids => (ids ?? []).filter(other => other !== id));
+ report.sent++;
+ report.waypointsLeft += file.left;
+ }
+
+ const last = await client.list({ signal });
+ // A route that the device lost, or that the rider deleted on it, can be sent again.
+ const on = new Set(ofKind(last, ObjectKind.Route).map(entry => `${last.storeId}:${entry.objectId}`));
+ if (Object.values(await library.state('sent') ?? {}).some(route => route.device.startsWith(`${last.storeId}:`) && !on.has(route.device))) {
+ await library.changeState('sent', routes => Object.fromEntries(Object.entries(routes ?? {})
+ .filter(([, route]) => !route.device.startsWith(`${last.storeId}:`) || on.has(route.device))));
+ }
+ rememberContents(last);
+ } catch (error) {
+ problems.push(cut(error) || signal.aborted ? CABLE_OUT : text(error));
+ }
+ report.problem = problems.join(' ') || null;
+ return report;
+}
+
+/**
+ * Sends the map that waits to the device `serial`, only when it is the remembered device. After the put it remembers the
+ * area and the colours of the map object, and the map waits no more. A map that the rider chose during the build still
+ * waits. Returns the sentence for the rider when the map did not go, else null. A cut cable and a stop keep the old map
+ * on the card.
+ */
+export async function sendMap(serial: string, library: Library, build: BuildMap, ctx: JobContext): Promise {
+ const next = await library.state('nextMap');
+ if (!next || remembered.device?.serial !== serial) return null;
+ let object: string;
+ try {
+ const { objectId, revision } = await build(next, ctx);
+ object = `${objectId}:${revision}`;
+ } catch (error) {
+ if (refused(error, 'no-space')) return NO_ROOM;
+ return cut(error) || ctx.signal.aborted ? MAP_LOST : text(error);
+ }
+ // The map is on the device: a failed write of the library is no failed send.
+ const { bytes: _, ...area } = next, sent = JSON.stringify(next);
+ remember({ mapObject: object, built: { object, ...area } });
+ await library.changeState('nextMap', now => now && JSON.stringify(now) !== sent ? now : null);
+ return null;
+}
+
+/** Marks each stored ride of `rides` that the Metadata object does not mark, after a check that the stored file is the exact
+ * object. It stops when the device has no archive or no room for it. */
+async function mark(client: SyncClient, catalog: Catalog, rides: CatalogEntry[], library: Library, signal: AbortSignal,
+ problems: string[]): Promise {
+ const metadata = ofKind(catalog, ObjectKind.Metadata)[0];
+ let rows;
+ try { rows = metadata ? archivedRows((await client.get(metadata, { signal })).bytes) : []; } catch (error) {
+ if (cut(error)) throw error;
+ problems.push(`No ride is marked as taken on the device: ${text(error)}`);
+ return 0;
+ }
+ const stored = new Map((await library.rides()).flatMap(ride => ride.device ? [[ride.device, ride.key] as const] : []));
+ let marked = 0;
+ for (const entry of rides) {
+ const key = stored.get(`${catalog.storeId}:${entry.objectId}`);
+ if (!key || rows.some(row => row.objectId === entry.objectId && row.revision === entry.revision
+ && row.payloadLength === entry.payloadLength && row.payloadCrc32 === entry.payloadCrc32)) continue;
+ const file = await library.rideFile(key);
+ if (!file || BigInt(file.size) !== entry.payloadLength || Crc32.of(new Uint8Array(await file.arrayBuffer())) !== entry.payloadCrc32) continue;
+ try {
+ await client.archiveRide({ storeId: catalog.storeId, ...entry }, signal);
+ marked++;
+ } catch (error) {
+ if (cut(error)) throw error;
+ if (refused(error, 'invalid-request')) continue;
+ if (!refused(error, 'unsupported', 'no-space')) problems.push(text(error));
+ break;
+ }
+ }
+ return marked;
+}
+
+/** Remembers the map, the number of routes and the bytes by kind of `catalog`. */
+function rememberContents(catalog: Catalog): void {
+ const bytes: DeviceBytes = { map: 0, routes: 0, rides: 0, other: 0 };
+ for (const entry of catalog.entries) {
+ const kind = entry.kind === ObjectKind.MapShard ? 'map' : entry.kind === ObjectKind.Route ? 'routes' : entry.kind === ObjectKind.Ride ? 'rides' : 'other';
+ bytes[kind] += Number(entry.payloadLength);
+ }
+ const map = ofKind(catalog, ObjectKind.MapShard).sort(byId)[0];
+ remember({ at: Date.now(), map: map?.displayName ?? null, mapObject: map ? `${map.objectId}:${map.revision}` : null, routes: ofKind(catalog, ObjectKind.Route).length, bytes });
+}
diff --git a/builder/web/src/lib/device-sync/until.ts b/builder/web/src/lib/device-sync/until.ts
new file mode 100644
index 0000000000..9c43ece2f4
--- /dev/null
+++ b/builder/web/src/lib/device-sync/until.ts
@@ -0,0 +1,10 @@
+/** The result of `work`, or the reason of `signal` when it aborts first. `work` itself goes on: this only ends the wait for
+ * a step that takes no signal, such as a module import. */
+export function until(work: Promise, signal: AbortSignal): Promise {
+ return new Promise((resolve, reject) => {
+ // First, so a failure of `work` after an abort has a handler.
+ work.then(resolve, reject);
+ if (signal.aborted) return reject(signal.reason);
+ signal.addEventListener('abort', () => reject(signal.reason), { once: true });
+ });
+}
diff --git a/builder/web/src/lib/device/dashboard.svelte.test.ts b/builder/web/src/lib/device/dashboard.svelte.test.ts
deleted file mode 100644
index 7a3215f111..0000000000
--- a/builder/web/src/lib/device/dashboard.svelte.test.ts
+++ /dev/null
@@ -1,194 +0,0 @@
-/**
- * The device page's store, against the loopback device: loading and grouping, the serialization
- * chain, busy-conflict accounting, and scope invalidation.
- *
- * A `LIST` is an ordinary control exchange, served beside a live transfer — but a trip's stage list
- * is a `GET`, and one transfer at a time is a device-wide rule, so two of those fired together
- * still collide. That is what these
- * tests drive the chain with.
- */
-
-import { beforeAll, describe, expect, it } from "vitest";
-
-import { DeviceDashboard } from "./dashboard.svelte";
-import type { RideScope } from "./rides";
-import { Crc32 } from "../usb/crc32";
-import { encodeTripObject, wholeDay } from "../usb/objects";
-import { FlatDevice, flatDevice } from "../usb/flat-device";
-import { loadFlatDevice } from "../../../test-support/flat-device/load";
-import { EntryFlags, ObjectKind } from "../usb/protocol";
-
-beforeAll(loadFlatDevice);
-
-const SCOPE: RideScope = { serial: "0011223344556677", storeId: "a1b2c3d4000000000000000000000000" };
-
-/** An OBCR-sized payload with a distinct byte at every offset — the page never looks inside one. */
-function routeBytes(seed: number): Uint8Array {
- const out = new Uint8Array(128);
- for (let i = 0; i < out.length; i++) out[i] = (i * 31 + seed) & 0xff;
- return out;
-}
-
-/** The store assigns the id; `seed` is the payload's own, so a test can name the bytes it expects. */
-function seedRoute(device: FlatDevice, name: string, seed = 0) {
- return device.seed({ kind: ObjectKind.Route, displayName: name, bytes: routeBytes(seed) });
-}
-
-function seedTrip(device: FlatDevice, name: string, stages: bigint[]) {
- const bytes = encodeTripObject({ key: 1n, name, startDate: 0, days: stages.map(wholeDay) });
- return device.seed({ kind: ObjectKind.Trip, displayName: name, bytes });
-}
-
-async function withDevice(
- body: (rig: ReturnType, dash: DeviceDashboard) => Promise,
-): Promise {
- const rig = flatDevice({});
- try {
- await body(rig, new DeviceDashboard());
- expect(rig.device.faults, "the device adapter saw a reaction it did not expect").toEqual([]);
- } finally {
- await rig.close();
- }
-}
-
-describe("DeviceDashboard", () => {
- it("loads and groups: trips resolve their stages, top-level excludes them", async () => {
- await withDevice(async ({ client, device }, dash) => {
- const first = seedRoute(device, "Day 1");
- const second = seedRoute(device, "Day 2");
- const loop = seedRoute(device, "Home loop");
- seedTrip(device, "Jura Crest Trail", [first.objectId, second.objectId]);
-
- await dash.ensureLoaded(client, SCOPE);
- expect(dash.error).toBeNull();
- expect(dash.routes.map((r) => r.objectId)).toEqual([first.objectId, second.objectId, loop.objectId]);
- expect(dash.topLevelRoutes.map((r) => r.objectId)).toEqual([loop.objectId]);
- expect(dash.trips).toHaveLength(1);
- expect(dash.stagesOf(dash.trips[0]).map((s) => s.route?.displayName)).toEqual(["Day 1", "Day 2"]);
- });
- });
-
- it("lists a ride the device is still recording, and marks it rather than offering it", async () => {
- // A `GET` of a `RECORDING` entry is refused — its length and CRC are zero until the commit
- // that ends it — so the page's job is to show it as in progress, not to hide it.
- await withDevice(async ({ client, device }, dash) => {
- const finished = device.seed({ kind: ObjectKind.Ride, displayName: "Tuesday", bytes: routeBytes(9) });
- const live = device.seed({ kind: ObjectKind.Ride, displayName: "Now", flags: EntryFlags.Recording });
-
- await dash.ensureLoaded(client, SCOPE);
- expect(dash.rides.map((r) => r.objectId)).toEqual([finished.objectId, live.objectId]);
- expect(dash.rides.map((r) => dash.isRecording(r))).toEqual([false, true]);
- });
- });
-
- it("marks a dangling stage instead of dropping it", async () => {
- await withDevice(async ({ client, device }, dash) => {
- const kept = seedRoute(device, "Still here");
- // Stage 9 is a reference the trip's payload carries to an object that is not on the card.
- seedTrip(device, "Half gone", [9n, kept.objectId]);
-
- await dash.ensureLoaded(client, SCOPE);
- const stages = dash.stagesOf(dash.trips[0]);
- expect(stages[0]).toEqual({ id: 9n, route: null });
- expect(stages[1].route?.displayName).toBe("Still here");
- });
- });
-
- it("does not re-list for the same scope, and reloads for a new one", async () => {
- await withDevice(async ({ client, device }, dash) => {
- seedRoute(device, "First");
- await dash.ensureLoaded(client, SCOPE);
- seedRoute(device, "Second");
- await dash.ensureLoaded(client, SCOPE);
- expect(dash.routes, "same scope: the cached lists stand").toHaveLength(1);
- await dash.ensureLoaded(client, { ...SCOPE, storeId: "00000000000000000000000000000007" });
- expect(dash.routes, "new scope: reloaded").toHaveLength(2);
- });
- });
-
- it("serializes enqueued transfers instead of tripping §1's one-at-a-time rule", async () => {
- await withDevice(async ({ client, device }, dash) => {
- const first = seedRoute(device, "One", 1);
- const second = seedRoute(device, "Two", 2);
- // Fired together; without the chain the second `GET` would throw `busy` before it left.
- const [a, b] = await Promise.all([
- dash.enqueue(() => client.get({ objectId: first.objectId, revision: first.revision })),
- dash.enqueue(() => client.get({ objectId: second.objectId, revision: second.revision })),
- ]);
- expect(a.bytes).toEqual(routeBytes(1));
- expect(b.bytes).toEqual(routeBytes(2));
- expect(dash.busy).toBe(false);
- });
- });
-
- it("keeps the chain alive after a failed operation", async () => {
- await withDevice(async ({ client, device }, dash) => {
- seedRoute(device, "Survivor");
- await expect(dash.enqueue(() => client.get({ objectId: 99n, revision: 0n }))).rejects.toMatchObject({
- code: "not-found",
- });
- const catalog = await dash.enqueue(() => client.list({ kind: ObjectKind.Route }));
- expect(catalog.entries).toHaveLength(1);
- });
- });
-
- it("flags busy when a foreign transfer holds the slot, and recovers after clearBusy", async () => {
- await withDevice(async ({ client, device }, dash) => {
- const route = seedRoute(device, "One");
- // A transfer the page does not own: started directly on the client, outside the chain —
- // the builder tab's map send, in miniature. The rule is device-wide, so the page cannot
- // serialize its way out of this one; it renders it.
- let releaseForeign!: () => void;
- const gate = new Promise((resolve) => (releaseForeign = resolve));
- const payload = new Uint8Array([1, 2, 3, 4]);
- const foreign = client.put({ kind: ObjectKind.Route, displayName: "Foreign" }, {
- totalLen: payload.length,
- crc32: Crc32.of(payload),
- chunks: async function* () {
- await gate;
- yield payload;
- },
- });
-
- await expect(
- dash.enqueue(() => client.get({ objectId: route.objectId, revision: route.revision })),
- ).rejects.toMatchObject({ code: "busy" });
- expect(dash.busy).toBe(true);
-
- releaseForeign();
- await foreign;
- dash.clearBusy();
- const catalog = await dash.enqueue(() => client.list({ kind: ObjectKind.Route }));
- expect(catalog.entries.map((entry) => entry.objectId)).toContain(route.objectId);
- expect(dash.busy).toBe(false);
- });
- });
-
- it("refresh after a remove drops the row", async () => {
- await withDevice(async ({ client, device }, dash) => {
- const doomed = seedRoute(device, "Doomed");
- const stays = seedRoute(device, "Stays");
- await dash.ensureLoaded(client, SCOPE);
- expect(dash.routes).toHaveLength(2);
- await dash.enqueue(() => client.remove({ objectId: doomed.objectId, revision: doomed.revision }));
- await dash.refresh(client);
- expect(dash.routes.map((r) => r.objectId)).toEqual([stays.objectId]);
- });
- });
-
- it("invalidate drops everything, so the next connect decides what to load", async () => {
- await withDevice(async ({ client, device }, dash) => {
- seedRoute(device, "Loaded");
- await dash.ensureLoaded(client, SCOPE);
- expect(dash.routes).toHaveLength(1);
-
- dash.invalidate();
- expect(dash.routes).toEqual([]);
- expect(dash.trips).toEqual([]);
- expect(dash.rides).toEqual([]);
- // The same scope loads again, because nothing is remembered about it.
- await dash.ensureLoaded(client, SCOPE);
- expect(dash.routes).toHaveLength(1);
- });
- });
-});
diff --git a/builder/web/src/lib/device/dashboard.svelte.ts b/builder/web/src/lib/device/dashboard.svelte.ts
deleted file mode 100644
index 99fca8ba3a..0000000000
--- a/builder/web/src/lib/device/dashboard.svelte.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-/**
- * The device page's model of what is on the card: routes, trips (with their stage lists), rides.
- *
- * Three rules shape everything here, all inherited from the protocol:
- *
- * 1. **One transfer at a time, enforced by throwing.** A `LIST` is an ordinary control exchange,
- * served beside a live upload, but a trip's stage list is a `GET`. `enqueue` keeps every cable
- * operation this page makes on one promise chain, so the page can never collide with *itself*.
- * It can still collide with a transfer another surface started, since the rule is device-wide,
- * and that is not an error to retry into but a state to render.
- *
- * 2. **Ids are only meaningful inside `(serial, era)`.** A card swap or a different device makes
- * every cached entry a claim about different objects, so the store reloads when the scope
- * changes.
- *
- * 3. **The catalog is what a client can know without downloading.** A route's distance, a ride's
- * start time and a trip's stage list live in the payload. Only the last is fetched here,
- * because a trip object is 56 bytes plus eight per stage and the page cannot draw a trip
- * without it.
- *
- * A module singleton, deliberately: the lists survive a tab switch, so returning to the Device tab
- * does not re-list the card.
- */
-
-import type { FlatStoreClient } from "../usb/client";
-import { DeviceError } from "../usb/client";
-import { EntryFlags, ObjectKind, type CatalogEntry } from "../usb/protocol";
-import { decodeTripObject, type TripObject } from "../usb/objects";
-import { scopeKey, type RideScope } from "./rides";
-
-/** A trip as the page renders it: the catalog row plus the stage list behind it. `detail` is null
- * only when the trip object itself could not be read — rendered as a group with no rows. */
-export interface TripView extends CatalogEntry {
- readonly detail: TripObject | null;
-}
-
-export class DeviceDashboard {
- routes = $state([]);
- trips = $state([]);
- rides = $state([]);
- loading = $state(false);
- /** A failure loading or mutating, rendered once at the top of the page. */
- error = $state(null);
- /** A transfer owned by another surface holds the link's one slot. */
- busy = $state(false);
-
- private chain: Promise = Promise.resolve();
- private loadedFor: string | null = null;
-
- /**
- * Run one cable operation, strictly after every previously enqueued one.
- *
- * The chain never rejects — each link settles — but the caller's promise still carries the
- * failure, so call sites decide what a failure means.
- */
- enqueue(op: () => Promise): Promise {
- const run = this.chain.then(op, op);
- this.chain = run.then(
- () => undefined,
- () => undefined,
- );
- return run.catch((cause: unknown) => {
- if (cause instanceof DeviceError && cause.code === "busy") this.busy = true;
- throw cause;
- });
- }
-
- /** Forget the slot conflict — called when the rider retries, or when the header's readout
- * shows the foreign transfer finished. */
- clearBusy(): void {
- this.busy = false;
- }
-
- /**
- * Load the three lists, once per `(serial, StoreId)`. A remount of the page on the same device
- * renders what is already here; a card swap or another device reloads.
- */
- async ensureLoaded(client: FlatStoreClient, scope: RideScope): Promise {
- const key = scopeKey(scope);
- if (this.loadedFor === key) return;
- this.loadedFor = key;
- await this.refresh(client);
- }
-
- /** Re-read everything. Called after every mutation — a catalog page is metadata and the card is
- * the authority, so re-listing beats mirroring each edit locally and drifting. */
- async refresh(client: FlatStoreClient): Promise {
- this.loading = true;
- this.error = null;
- try {
- // One listing, filtered here rather than three filtered by the device. A kind filter
- // exists, but three round trips buy nothing when the whole catalog fits in a couple of
- // pages and the page wants all three kinds every time.
- const catalog = await this.enqueue(() => client.list());
- const routes = catalog.entries.filter((entry) => entry.kind === ObjectKind.Route);
- const trips = catalog.entries.filter((entry) => entry.kind === ObjectKind.Trip);
- const details: TripView[] = [];
- for (const entry of trips) {
- // Sequential on purpose — each is a `GET`, and the chain is the page's
- // serialization guarantee.
- const detail = await this.enqueue(() =>
- client.get({ objectId: entry.objectId, revision: entry.revision }),
- )
- .then((result) => decodeTripObject(result.bytes))
- .catch(() => null);
- details.push({ ...entry, detail });
- }
- this.routes = routes;
- this.trips = details;
- // A ride the device is still recording has a zero length and CRC until the commit that
- // ends it, so it is listed and not offered: the page shows it as recording.
- this.rides = catalog.entries.filter((entry) => entry.kind === ObjectKind.Ride);
- } catch (cause) {
- this.error = cause instanceof Error ? cause.message : String(cause);
- // Nothing loaded is a fact worth retrying, not a scope worth remembering.
- this.loadedFor = null;
- } finally {
- this.loading = false;
- }
- }
-
- /**
- * Every route id that is a stage of some trip — the rows the top-level list leaves out. Full-width
- * flat-store ObjectIds, exactly as the trip payload carries them.
- */
- get stagedIds(): Set {
- const staged = new Set();
- for (const trip of this.trips) for (const day of trip.detail?.days ?? []) staged.add(day.route);
- return staged;
- }
-
- /** Routes that are not inside any trip, in list order. */
- get topLevelRoutes(): CatalogEntry[] {
- const staged = this.stagedIds;
- return this.routes.filter((route) => !staged.has(route.objectId));
- }
-
- /**
- * A trip's stages resolved against the route list. Null marks a dangling id — a member route
- * deleted on its own, which the device tolerates and serves verbatim.
- *
- * A trip stores the catalog's complete `u64` ObjectId, so resolution stays exact even after the
- * allocation cursor has moved beyond JavaScript's safe integer range.
- */
- stagesOf(trip: TripView): Array<{ id: bigint; route: CatalogEntry | null }> {
- const byId = new Map(this.routes.map((route) => [route.objectId, route]));
- return (trip.detail?.days ?? []).map(({ route: id }) => ({ id, route: byId.get(id) ?? null }));
- }
-
- /** True where this entry is a ride the device is still recording, which cannot be served. */
- isRecording(entry: CatalogEntry): boolean {
- return (entry.flags & EntryFlags.Recording) !== 0;
- }
-
- /** Drop everything, for a disconnect: the next connect decides what to load. */
- invalidate(): void {
- this.loadedFor = null;
- this.routes = [];
- this.trips = [];
- this.rides = [];
- this.error = null;
- this.busy = false;
- }
-}
-
-export const dashboard = new DeviceDashboard();
diff --git a/builder/web/src/lib/device/elevation.test.ts b/builder/web/src/lib/device/elevation.test.ts
deleted file mode 100644
index 10101e2554..0000000000
--- a/builder/web/src/lib/device/elevation.test.ts
+++ /dev/null
@@ -1,287 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- FULL_WINDOW,
- MIN_WINDOW_SPAN,
- clampWindow,
- cumulativeDistances,
- elevationAtDistance,
- elevationProfile,
- isFullWindow,
- nearestPointIndex,
- panWindow,
- pointAtDistance,
- windowIndexRange,
- zoomWindow,
-} from "./elevation";
-
-const climb = [
- { lat: 48.0, lon: 7.82, ele: 236 },
- { lat: 48.01, lon: 7.83, ele: 400 },
- { lat: 48.02, lon: 7.84, ele: 320 },
-];
-
-/** Four points spaced ~1.11 km apart along a meridian — a near-uniform distance axis. */
-const ladder = [
- { lat: 48.0, lon: 7.82, ele: 100 },
- { lat: 48.01, lon: 7.82, ele: 200 },
- { lat: 48.02, lon: 7.82, ele: 300 },
- { lat: 48.03, lon: 7.82, ele: 400 },
-];
-
-describe("elevationProfile", () => {
- it("draws a climb: paths inside the box, extremes reported, distance positive", () => {
- const profile = elevationProfile(climb, 600, 64);
- expect(profile).not.toBeNull();
- expect(profile!.minEle).toBe(236);
- expect(profile!.maxEle).toBe(400);
- expect(profile!.totalM).toBeGreaterThan(1000);
- expect(profile!.startM).toBe(0);
- expect(profile!.endM).toBe(profile!.totalM);
- expect(profile!.linePath.startsWith("M")).toBe(true);
- expect(profile!.areaPath.endsWith("Z")).toBe(true);
- // The peak maps to the top of the box (pad), the lowest point to the bottom.
- const ys = profile!.linePath.match(/ (\d+\.\d)/g)!.map(Number);
- expect(Math.min(...ys)).toBeCloseTo(2, 0);
- expect(Math.max(...ys)).toBeCloseTo(62, 0);
- });
-
- it("draws a flat track mid-box rather than refusing it", () => {
- const flat = climb.map((p) => ({ ...p, ele: 100 }));
- const profile = elevationProfile(flat, 600, 64);
- expect(profile).not.toBeNull();
- expect(profile!.minEle).toBe(100);
- expect(profile!.maxEle).toBe(100);
- });
-
- it("returns null where nothing honest can be drawn", () => {
- expect(elevationProfile([], 600, 64)).toBeNull();
- expect(elevationProfile([climb[0]], 600, 64)).toBeNull();
- expect(elevationProfile(climb.map((p) => ({ ...p, ele: null })), 600, 64)).toBeNull();
- // Two points at the same place: no distance axis.
- expect(elevationProfile([climb[0], climb[0]], 600, 64)).toBeNull();
- });
-
- it("keeps elevation-less points on the distance axis but out of the drawn series", () => {
- const gappy = [climb[0], { lat: 48.005, lon: 7.825, ele: null }, climb[1], climb[2]];
- const profile = elevationProfile(gappy, 600, 64);
- expect(profile).not.toBeNull();
- expect(profile!.maxEle).toBe(400);
- // The gap point advances the axis: the total matches the all-points cumulative distance,
- // not a collapsed one.
- const cum = cumulativeDistances(gappy);
- expect(profile!.totalM).toBeCloseTo(cum[cum.length - 1], 6);
- });
-
- describe("windowed", () => {
- it("redraws only the window, with its own extremes and metre bounds", () => {
- const full = elevationProfile(ladder, 600, 64)!;
- const half = elevationProfile(ladder, 600, 64, [0.5, 1])!;
- expect(half.startM).toBeCloseTo(full.totalM / 2, 6);
- expect(half.endM).toBeCloseTo(full.totalM, 6);
- expect(half.totalM).toBeCloseTo(full.totalM, 6);
- // Only the back half's elevations: min is the interpolated 250 m at the cut.
- expect(half.minEle).toBeCloseTo(250, 0);
- expect(half.maxEle).toBe(400);
- // The redrawn path spans the whole box, not a squeezed half of it.
- const xs = half.linePath.match(/[ML](\d+\.\d)/g)!.map((m) => Number(m.slice(1)));
- expect(Math.min(...xs)).toBeCloseTo(2, 0);
- expect(Math.max(...xs)).toBeCloseTo(598, 0);
- });
-
- it("interpolates the elevation where the window cuts between samples", () => {
- // A window strictly inside the middle segment: both edges are interpolants.
- const profile = elevationProfile(ladder, 600, 64, [0.4, 0.6])!;
- expect(profile.minEle).toBeCloseTo(220, 0);
- expect(profile.maxEle).toBeCloseTo(280, 0);
- });
-
- it("returns null when the window holds no drawable elevation", () => {
- const headOnly = [
- { lat: 48.0, lon: 7.82, ele: 100 },
- { lat: 48.01, lon: 7.82, ele: 200 },
- { lat: 48.02, lon: 7.82, ele: null },
- { lat: 48.03, lon: 7.82, ele: null },
- ];
- expect(elevationProfile(headOnly, 600, 64, [0.75, 1])).toBeNull();
- });
- });
-});
-
-describe("cumulativeDistances", () => {
- it("starts at zero, one entry per point, monotonic", () => {
- const cum = cumulativeDistances(ladder);
- expect(cum.length).toBe(4);
- expect(cum[0]).toBe(0);
- for (let i = 1; i < cum.length; i++) expect(cum[i]).toBeGreaterThan(cum[i - 1]);
- // ~1.11 km per 0.01° of latitude.
- expect(cum[3]).toBeGreaterThan(3200);
- expect(cum[3]).toBeLessThan(3500);
- });
-
- it("is empty for no points and [0] for one", () => {
- expect(cumulativeDistances([])).toEqual([]);
- expect(cumulativeDistances([ladder[0]])).toEqual([0]);
- });
-});
-
-describe("clampWindow", () => {
- it("orders and clamps a dragged pair", () => {
- expect(clampWindow(0.8, 0.2)).toEqual([0.2, 0.8]);
- expect(clampWindow(-0.5, 1.5)).toEqual([0, 1]);
- });
-
- it("grows a degenerate drag to the minimum span, kept inside the track", () => {
- const [t0, t1] = clampWindow(0.5, 0.5);
- expect(t1 - t0).toBeCloseTo(MIN_WINDOW_SPAN, 9);
- expect(t0).toBeCloseTo(0.5 - MIN_WINDOW_SPAN / 2, 9);
- expect(clampWindow(0, 0)).toEqual([0, MIN_WINDOW_SPAN]);
- expect(clampWindow(1, 1)).toEqual([1 - MIN_WINDOW_SPAN, 1]);
- });
-});
-
-describe("zoomWindow", () => {
- it("zooms in about the anchor, keeping the ground under it still", () => {
- const [t0, t1] = zoomWindow([0, 1], 0.5, 0.5);
- expect(t1 - t0).toBeCloseTo(0.5, 9);
- expect((0.5 - t0) / (t1 - t0)).toBeCloseTo(0.5, 9);
- // An off-centre anchor keeps its relative position.
- const [u0, u1] = zoomWindow([0, 1], 0.5, 0.2);
- expect((0.2 - u0) / (u1 - u0)).toBeCloseTo(0.2, 9);
- });
-
- it("never inverts, undershoots the minimum span, or leaves the track", () => {
- const tiny = zoomWindow([0.4, 0.4 + MIN_WINDOW_SPAN], 0.1, 0.405);
- expect(tiny[1] - tiny[0]).toBeCloseTo(MIN_WINDOW_SPAN, 9);
- const out = zoomWindow([0.9, 1], 4, 0.99);
- expect(out[0]).toBeGreaterThanOrEqual(0);
- expect(out[1]).toBeLessThanOrEqual(1);
- expect(zoomWindow([0, 1], 3, 0.5)).toEqual([0, 1]);
- });
-});
-
-describe("windowIndexRange", () => {
- // Four points, three equal segments: cum = [0, 1, 2, 3].
- const cum = [0, 1, 2, 3];
-
- it("covers the whole track at the full window", () => {
- expect(windowIndexRange(cum, FULL_WINDOW)).toEqual([0, 3]);
- });
-
- it("rounds outward so the highlight covers the window", () => {
- // [0.5, 0.83] in distance = [1.5 m, 2.5 m]: needs points 1..3 to cover.
- expect(windowIndexRange(cum, [0.5, 5 / 6])).toEqual([1, 3]);
- // Exactly on vertices: no widening.
- expect(windowIndexRange(cum, [1 / 3, 2 / 3])).toEqual([1, 2]);
- });
-
- it("degenerates safely", () => {
- expect(windowIndexRange([], FULL_WINDOW)).toEqual([0, 0]);
- expect(windowIndexRange([0], FULL_WINDOW)).toEqual([0, 0]);
- });
-});
-
-describe("panWindow", () => {
- it("slides without resizing", () => {
- const [t0, t1] = panWindow([0.2, 0.4], 0.3);
- expect(t0).toBeCloseTo(0.5, 9);
- expect(t1).toBeCloseTo(0.7, 9);
- });
-
- it("clamps at both ends, span preserved", () => {
- expect(panWindow([0.2, 0.4], -1)).toEqual([0, 0.2]);
- const [t0, t1] = panWindow([0.2, 0.4], 1);
- expect(t0).toBeCloseTo(0.8, 9);
- expect(t1).toBeCloseTo(1, 9);
- // The full window has nowhere to go.
- expect(panWindow([0, 1], 0.5)).toEqual([0, 1]);
- });
-});
-
-describe("pointAtDistance", () => {
- const cum = cumulativeDistances(ladder);
-
- it("lands on vertices at their exact distances", () => {
- expect(pointAtDistance(ladder, cum, 0)).toEqual({ lat: 48.0, lon: 7.82 });
- expect(pointAtDistance(ladder, cum, cum[2])).toEqual({ lat: 48.02, lon: 7.82 });
- expect(pointAtDistance(ladder, cum, cum[3])).toEqual({ lat: 48.03, lon: 7.82 });
- });
-
- it("interpolates within a segment", () => {
- const mid = pointAtDistance(ladder, cum, (cum[1] + cum[2]) / 2)!;
- expect(mid.lat).toBeCloseTo(48.015, 6);
- expect(mid.lon).toBeCloseTo(7.82, 9);
- });
-
- it("clamps past the ends and degenerates safely", () => {
- expect(pointAtDistance(ladder, cum, -5)).toEqual({ lat: 48.0, lon: 7.82 });
- expect(pointAtDistance(ladder, cum, cum[3] + 500)).toEqual({ lat: 48.03, lon: 7.82 });
- expect(pointAtDistance([], [], 0)).toBeNull();
- expect(pointAtDistance([ladder[0]], [0], 10)).toEqual({ lat: 48.0, lon: 7.82 });
- // A mismatched axis is a caller bug, answered with null rather than a wrong point.
- expect(pointAtDistance(ladder, [0, 1], 0.5)).toBeNull();
- });
-});
-
-describe("elevationAtDistance", () => {
- const cum = cumulativeDistances(ladder);
-
- it("reads vertices exactly and interpolates within a segment", () => {
- expect(elevationAtDistance(ladder, cum, 0)).toBe(100);
- expect(elevationAtDistance(ladder, cum, cum[2])).toBe(300);
- expect(elevationAtDistance(ladder, cum, (cum[1] + cum[2]) / 2)).toBeCloseTo(250, 6);
- });
-
- it("clamps past the ends", () => {
- expect(elevationAtDistance(ladder, cum, -5)).toBe(100);
- expect(elevationAtDistance(ladder, cum, cum[3] + 500)).toBe(400);
- });
-
- it("goes quiet inside a null gap instead of printing the profile's interpolated ramp", () => {
- // The middle two points recorded no elevation: the drawn line spans them (samples at the
- // outer two), but any hover between points 0→1, 1→2 or 2→3 has a null neighbour.
- const gappy = [
- { ...ladder[0], ele: 100 },
- { ...ladder[1], ele: null },
- { ...ladder[2], ele: null },
- { ...ladder[3], ele: 400 },
- ];
- const gcum = cumulativeDistances(gappy);
- expect(elevationAtDistance(gappy, gcum, gcum[1] / 2)).toBeNull();
- expect(elevationAtDistance(gappy, gcum, (gcum[1] + gcum[2]) / 2)).toBeNull();
- expect(elevationAtDistance(gappy, gcum, (gcum[2] + gcum[3]) / 2)).toBeNull();
- // The real samples at the ends still read.
- expect(elevationAtDistance(gappy, gcum, 0)).toBe(100);
- expect(elevationAtDistance(gappy, gcum, gcum[3])).toBe(400);
- // On a null vertex itself the answer is the vertex's: nothing.
- expect(elevationAtDistance(gappy, gcum, gcum[3] + 1), "clamp lands on a real end").toBe(400);
- });
-
- it("degenerates safely", () => {
- expect(elevationAtDistance([], [], 0)).toBeNull();
- expect(elevationAtDistance([ladder[0]], [0], 10)).toBe(100);
- expect(elevationAtDistance([{ ...ladder[0], ele: null }], [0], 0)).toBeNull();
- // A mismatched axis is a caller bug, answered with null rather than a wrong number.
- expect(elevationAtDistance(ladder, [0, 1], 0.5)).toBeNull();
- });
-});
-
-describe("nearestPointIndex", () => {
- it("finds the closest vertex, ends included", () => {
- expect(nearestPointIndex(ladder, 48.001, 7.82)).toBe(0);
- expect(nearestPointIndex(ladder, 48.014, 7.821)).toBe(1);
- expect(nearestPointIndex(ladder, 48.9, 7.82)).toBe(3);
- });
-
- it("is -1 for an empty track", () => {
- expect(nearestPointIndex([], 48, 7.82)).toBe(-1);
- });
-});
-
-describe("isFullWindow", () => {
- it("tells the reset state from a zoom", () => {
- expect(isFullWindow(FULL_WINDOW)).toBe(true);
- expect(isFullWindow([0, 0.999])).toBe(false);
- expect(isFullWindow([0.001, 1])).toBe(false);
- });
-});
diff --git a/builder/web/src/lib/device/elevation.ts b/builder/web/src/lib/device/elevation.ts
deleted file mode 100644
index 59f54cdca9..0000000000
--- a/builder/web/src/lib/device/elevation.ts
+++ /dev/null
@@ -1,303 +0,0 @@
-/**
- * The preview's elevation profile: distance-along-track on x, elevation on y, as one SVG path, plus
- * the windowing math behind the preview's zoom.
- *
- * Pure geometry, shared by the route preview and the ride preview. Distance is equirectangular with
- * a `cos(lat)` correction, which is metres-accurate at track scale.
- *
- * One distance axis for everything: {@link cumulativeDistances} runs over **all** points, including
- * elevation-less ones, since they exist on the map polyline. A zoom window is a `[t0, t1]` pair of
- * fractions of the total distance.
- */
-
-/** The minimum a profile is drawn from: with one point there is no distance axis at all. */
-const MIN_POINTS = 2;
-
-export interface ProfilePoint {
- readonly lat: number;
- readonly lon: number;
- /** Metres; null where the source recorded none. */
- readonly ele: number | null;
-}
-
-/** A zoom window over the track: fractions of the total distance, `0 <= t0 < t1 <= 1`. */
-export type ProfileWindow = readonly [number, number];
-
-/** The whole track — the reset state, and the only window a profile-less preview ever has. */
-export const FULL_WINDOW: ProfileWindow = [0, 1];
-
-/** The narrowest a window may get — 1% of the track, so a zoom can never collapse or invert. */
-export const MIN_WINDOW_SPAN = 0.01;
-
-export interface ElevationProfile {
- /** `M … L …` path in a `width` × `height` viewBox, baseline-closed for an area fill. */
- readonly areaPath: string;
- /** The same polyline without the baseline, for the stroke on top. */
- readonly linePath: string;
- /** Extremes of the elevation *within the window*. */
- readonly minEle: number;
- readonly maxEle: number;
- /** The window's bounds and the whole track's length, metres — the axis captions' numbers. */
- readonly startM: number;
- readonly endM: number;
- readonly totalM: number;
-}
-
-/**
- * Cumulative ground distance at every point, metres — `result[0] === 0`, one entry per point,
- * elevation-less points included. The shared axis: the profile's x, the map split's cut, and a
- * waypoint tick's position are all fractions of `result[result.length - 1]`.
- */
-export function cumulativeDistances(points: readonly ProfilePoint[]): number[] {
- const cum: number[] = points.length ? [0] : [];
- for (let i = 1; i < points.length; i++) {
- cum.push(cum[i - 1] + groundDistanceM(points[i - 1], points[i]));
- }
- return cum;
-}
-
-/** Is `window` (effectively) the whole track — the state with no gray on the map, no reset. */
-export function isFullWindow([t0, t1]: ProfileWindow): boolean {
- return t0 <= 0 && t1 >= 1;
-}
-
-/**
- * Order and clamp a dragged pair of fractions into a valid window: inside `[0, 1]`, at least
- * {@link MIN_WINDOW_SPAN} wide (grown symmetrically around the pair's centre, pushed back inside
- * the track when the centre sits near an end).
- */
-export function clampWindow(a: number, b: number): ProfileWindow {
- let t0 = Math.max(0, Math.min(a, b));
- let t1 = Math.min(1, Math.max(a, b));
- if (t1 - t0 < MIN_WINDOW_SPAN) {
- const centre = (t0 + t1) / 2;
- t0 = centre - MIN_WINDOW_SPAN / 2;
- t1 = centre + MIN_WINDOW_SPAN / 2;
- if (t0 < 0) [t0, t1] = [0, MIN_WINDOW_SPAN];
- if (t1 > 1) [t0, t1] = [1 - MIN_WINDOW_SPAN, 1];
- }
- return [t0, t1];
-}
-
-/**
- * Scale a window by `factor` (>1 zooms out, <1 zooms in) about `centreT` — an absolute fraction
- * of the track, normally the cursor's position — keeping the centre's relative position in the
- * window so the ground under the cursor stays put. Clamped to `[0, 1]` and the minimum span.
- */
-export function zoomWindow(window: ProfileWindow, factor: number, centreT: number): ProfileWindow {
- const [t0, t1] = window;
- const span = t1 - t0;
- const next = Math.min(1, Math.max(MIN_WINDOW_SPAN, span * factor));
- // Where the anchor sits within the window (0 = left edge, 1 = right), kept across the scale.
- const r = span > 0 ? (centreT - t0) / span : 0.5;
- let n0 = centreT - r * next;
- n0 = Math.max(0, Math.min(1 - next, n0));
- return [n0, n0 + next];
-}
-
-/**
- * The point indices the map highlights for `window`: `[first, last]` such that the polyline
- * `points[first..=last]` covers the window's distance span (the boundary segments are included
- * whole — a cut mid-segment rounds outward, so the coral never falls short of the window).
- * `[0, points.length - 1]` at the full window.
- */
-export function windowIndexRange(cum: readonly number[], window: ProfileWindow): [number, number] {
- const last = cum.length - 1;
- if (last < 1) return [0, Math.max(0, last)];
- const total = cum[last];
- const d0 = window[0] * total;
- const d1 = window[1] * total;
- let first = 0;
- while (first < last && cum[first + 1] <= d0) first++;
- let end = last;
- while (end > 0 && cum[end - 1] >= d1) end--;
- return first <= end ? [first, end] : [end, first];
-}
-
-/**
- * Slide the window along the track by `deltaT` (a fraction of the total distance), preserving its
- * span — the Ctrl/⌘-drag pan. Clamped so the window never leaves `[0, 1]` and never resizes.
- */
-export function panWindow(window: ProfileWindow, deltaT: number): ProfileWindow {
- const [t0, t1] = window;
- const span = t1 - t0;
- const n0 = Math.max(0, Math.min(1 - span, t0 + deltaT));
- return [n0, n0 + span];
-}
-
-/**
- * The `[lat, lon]` at distance `d` metres along the track — interpolated within the segment that
- * contains it, clamped to the ends. The hover cursor's map position: one distance axis
- * ({@link cumulativeDistances}) in, one point on the drawn polyline out. Null on an empty track.
- */
-export function pointAtDistance(
- points: readonly ProfilePoint[],
- cum: readonly number[],
- d: number,
-): { lat: number; lon: number } | null {
- if (points.length === 0 || cum.length !== points.length) return null;
- if (points.length === 1) return { lat: points[0].lat, lon: points[0].lon };
- const target = Math.max(0, Math.min(d, cum[cum.length - 1]));
- // Binary search for the segment holding `target` — hover runs per animation frame.
- let lo = 0;
- let hi = cum.length - 1;
- while (lo + 1 < hi) {
- const mid = (lo + hi) >> 1;
- if (cum[mid] <= target) lo = mid;
- else hi = mid;
- }
- const span = cum[hi] - cum[lo];
- const t = span > 0 ? (target - cum[lo]) / span : 0;
- return {
- lat: points[lo].lat + (points[hi].lat - points[lo].lat) * t,
- lon: points[lo].lon + (points[hi].lon - points[lo].lon) * t,
- };
-}
-
-/**
- * The elevation at distance `d` metres along the track, or null where there is no honest number.
- * Interpolated between the two track points bracketing `d`, and **only** when both carry real
- * elevation. A null-elevation neighbour means `d` falls in a gap the source recorded nothing for:
- * the profile's line spans such a gap, but a readout that printed that ramp would be inventing a
- * number, so the label goes quiet instead.
- */
-export function elevationAtDistance(
- points: readonly ProfilePoint[],
- cum: readonly number[],
- d: number,
-): number | null {
- if (points.length === 0 || cum.length !== points.length) return null;
- if (points.length === 1) return points[0].ele;
- const target = Math.max(0, Math.min(d, cum[cum.length - 1]));
- // The same binary search the map dot uses — hover runs per animation frame.
- let lo = 0;
- let hi = cum.length - 1;
- while (lo + 1 < hi) {
- const mid = (lo + hi) >> 1;
- if (cum[mid] <= target) lo = mid;
- else hi = mid;
- }
- const span = cum[hi] - cum[lo];
- const t = span > 0 ? (target - cum[lo]) / span : 0;
- // Exactly on a point (the clamped ends, mostly): that point's own value is the honest
- // answer, whatever its neighbour recorded.
- if (t <= 0) return points[lo].ele;
- if (t >= 1) return points[hi].ele;
- const a = points[lo].ele;
- const b = points[hi].ele;
- if (a === null || b === null) return null;
- return a + (b - a) * t;
-}
-
-/**
- * The index of the track point nearest `(lat, lon)`, by the same equirectangular metric the distance
- * axis uses. A plain scan: preview tracks are thousands of points, and one pass per animation frame
- * is nothing. `-1` on an empty track.
- */
-export function nearestPointIndex(points: readonly ProfilePoint[], lat: number, lon: number): number {
- const probe: ProfilePoint = { lat, lon, ele: null };
- let best = -1;
- let bestM = Infinity;
- for (let i = 0; i < points.length; i++) {
- const m = groundDistanceM(points[i], probe);
- if (m < bestM) {
- bestM = m;
- best = i;
- }
- }
- return best;
-}
-
-/**
- * Build the profile for the window, or null where there is nothing honest to draw — fewer than two
- * usable points in the window, or no elevation anywhere in it. A *flat* track still draws, because a
- * flat line is a true statement; a track with no elevation data does not.
- *
- * The x axis is true distance along the whole track: points without elevation still advance it, they
- * just contribute no sample. Where the window's edge cuts between two samples, the elevation at the
- * cut is interpolated so the drawn span is exactly the window.
- */
-export function elevationProfile(
- points: readonly ProfilePoint[],
- width: number,
- height: number,
- window: ProfileWindow = FULL_WINDOW,
- pad = 2,
-): ElevationProfile | null {
- const cum = cumulativeDistances(points);
- const totalM = cum.length ? cum[cum.length - 1] : 0;
- if (totalM <= 0) return null;
-
- // The usable series: (distance, elevation) samples over the whole track.
- const samples: Array<{ d: number; ele: number }> = [];
- for (let i = 0; i < points.length; i++) {
- const ele = points[i].ele;
- if (ele !== null) samples.push({ d: cum[i], ele });
- }
- if (samples.length < MIN_POINTS) return null;
-
- const startM = window[0] * totalM;
- const endM = window[1] * totalM;
- const drawn = windowSamples(samples, startM, endM);
- if (drawn.length < MIN_POINTS) return null;
-
- let minEle = Infinity;
- let maxEle = -Infinity;
- for (const s of drawn) {
- if (s.ele < minEle) minEle = s.ele;
- if (s.ele > maxEle) maxEle = s.ele;
- }
- // A dead-flat profile gets a nominal band so the line sits mid-box instead of on an edge.
- const span = Math.max(maxEle - minEle, 1);
-
- const w = width - 2 * pad;
- const h = height - 2 * pad;
- const x = (d: number) => pad + ((d - startM) / (endM - startM)) * w;
- const y = (ele: number) => pad + (1 - (ele - minEle) / span) * h;
-
- const parts = drawn.map((s, i) => `${i === 0 ? "M" : "L"}${x(s.d).toFixed(1)} ${y(s.ele).toFixed(1)}`);
- const linePath = parts.join(" ");
- const baselineY = (height - pad).toFixed(1);
- const first = drawn[0];
- const last = drawn[drawn.length - 1];
- const areaPath = `${linePath} L${x(last.d).toFixed(1)} ${baselineY} L${x(first.d).toFixed(1)} ${baselineY} Z`;
-
- return { areaPath, linePath, minEle, maxEle, startM, endM, totalM };
-}
-
-/** The samples inside `[d0, d1]`, with interpolated samples at any edge that cuts the series. */
-function windowSamples(
- samples: ReadonlyArray<{ d: number; ele: number }>,
- d0: number,
- d1: number,
-): Array<{ d: number; ele: number }> {
- const out: Array<{ d: number; ele: number }> = [];
- for (let i = 0; i < samples.length; i++) {
- const s = samples[i];
- if (s.d < d0) {
- const next = samples[i + 1];
- if (next && next.d > d0) out.push({ d: d0, ele: lerp(s, next, d0) });
- } else if (s.d > d1) {
- const prev = samples[i - 1];
- if (prev && prev.d < d1) out.push({ d: d1, ele: lerp(prev, s, d1) });
- break;
- } else {
- out.push(s);
- }
- }
- return out;
-}
-
-function lerp(a: { d: number; ele: number }, b: { d: number; ele: number }, d: number): number {
- const t = b.d === a.d ? 0 : (d - a.d) / (b.d - a.d);
- return a.ele + (b.ele - a.ele) * t;
-}
-
-/** Equirectangular ground distance in metres — fine at the scale of one track. */
-function groundDistanceM(a: ProfilePoint, b: ProfilePoint): number {
- const R = 6_371_000;
- const toRad = Math.PI / 180;
- const dLat = (b.lat - a.lat) * toRad;
- const dLon = (b.lon - a.lon) * toRad * Math.cos(((a.lat + b.lat) / 2) * toRad);
- return Math.sqrt(dLat * dLat + dLon * dLon) * R;
-}
diff --git a/builder/web/src/lib/device/library.test.ts b/builder/web/src/lib/device/library.test.ts
deleted file mode 100644
index 480be8b844..0000000000
--- a/builder/web/src/lib/device/library.test.ts
+++ /dev/null
@@ -1,523 +0,0 @@
-/**
- * The managed ride library's pull, end to end against the simulated device.
- *
- * Each test here is a *library* assertion rather than a call-count assertion: what the library holds
- * afterwards, and whether the files behind those rows exist. The failure modes this feature has are
- * not "the wrong function was called" — they are "the app believes it has a rider's only copy of a
- * ride and it does not".
- *
- * The real durable write is Rust (`builder/desktop/src/rides.rs`) and is tested there, against the
- * real filesystem, with the power cut between `write()` and `fsync()`. What *this* file owns is the
- * other half of the same claim: a ride only counts as held once the library's `import()` has
- * resolved. {@link RecordingLibrary} is a fake, not a mock of the Tauri boundary: it holds real
- * state, it can fail, and the tests read its state rather than its call log.
- *
- * A possession acknowledgement is deliberately absent from this cable surface: it changes no object,
- * so it has no store meaning and USB does not carry it. The ordering discipline it needed — an
- * import resolves only after fsync — is kept regardless, because it is what makes
- * {@link PullReport} true.
- */
-
-import { existsSync, readFileSync } from "node:fs";
-import { dirname, join } from "node:path";
-import { fileURLToPath } from "node:url";
-import { beforeAll, describe, expect, it } from "vitest";
-
-import { initConvert } from "../convert/bridge";
-import type { FlatStoreClient } from "../usb/client";
-import { flatDevice } from "../usb/flat-device";
-import { loadFlatDevice } from "../../../test-support/flat-device/load";
-import { encodeRideObject, type RideObject, type RidePoint } from "../usb/objects";
-import { EntryFlags, ObjectKind } from "../usb/protocol";
-import {
- PREVIEW_POINTS,
- previewTrack,
- pullRide,
- pullRides,
- trackPath,
- type LibraryRide,
- type LibraryView,
- type RideImport,
- type RideLibrary,
-} from "./library";
-import { rideAccess, rideKey, rideScope, type RideScope } from "./rides";
-import type { JobContext, JobPhase } from "./progress";
-
-beforeAll(async () => {
- const wasm = join(dirname(fileURLToPath(import.meta.url)), "..", "core", "pkg", "obc_builder_bridge_bg.wasm");
- if (!existsSync(wasm)) {
- throw new Error(`the wasm bridge is not built (${wasm} missing). Run \`npm run build:wasm\`.`);
- }
- await initConvert(readFileSync(wasm));
- await loadFlatDevice();
-});
-
-/** The loopback link's default serial, and the two cards these tests swap between. */
-const SERIAL = "0011223344556677";
-const CARD_A = "8f2c41d96b074ea3b1559c207de83466";
-const CARD_B = CARD_A.slice(0, 8) + "00000000000000000000abcd";
-
-function ctx(): JobContext {
- const phases: JobPhase[] = [];
- return {
- signal: new AbortController().signal,
- cancel() {},
- phase: (phase) => phases.push(phase),
- progress: () => undefined,
- };
-}
-
-/** A ride the device would have recorded: a short, real-looking track through the Black Forest. */
-function rideObject(name: string, startTime: number, points = 24): RideObject {
- const track: RidePoint[] = [];
- for (let i = 0; i < points; i++) {
- track.push({
- tMs: i * 5_000,
- latMicrodegrees: Math.round((47.9 + i * 0.0012) * 1e6),
- lonMicrodegrees: Math.round((7.85 + i * 0.0009) * 1e6),
- elevationM: 300 + i * 4,
- segmentStart: i === 0,
- hrBpm: 140 + (i % 7),
- cadenceRpm: 80,
- powerW: null,
- });
- }
- return {
- version: 6,
- isDemo: false,
- effortLimits: { maxHrBpm: null, ftpW: null },
- name,
- startTime,
- distanceM: 12_340,
- movingTimeS: 2_700,
- avgSpeedCms: 457,
- climbM: 96,
- descentM: 96,
- avgHr: 143,
- maxHr: 171,
- avgCadence: 80,
- avgPower: null,
- maxPower: null,
- energyKj: null,
- bikeType: 0,
- trip: null,
- points: track,
- };
-}
-
-/**
- * A ride library that keeps real state and can be made to fail.
- *
- * Not a mock of the `invoke()` calls — the tests below never look at what was called. It models the
- * one property the whole feature hangs off: **`import()` resolving is what makes a ride held**. A
- * rejected import leaves nothing behind, exactly as a power cut before fsync does on the real thing.
- */
-class RecordingLibrary implements RideLibrary {
- readonly rides = new Map();
- /** Every library call, in order — read by the ordering assertions and nothing else. */
- readonly events: string[] = [];
- /** Keys whose import must fail, as a crash between write and fsync would. */
- failFor = new Set();
- folder = "/library";
-
- async view(): Promise {
- return { folder: this.folder, isDefault: true, rides: [...this.rides.values()] };
- }
-
- async import(ride: RideImport): Promise<{ ride: LibraryRide; imported: boolean }> {
- const key = `${ride.serial}:${ride.storeId}:${ride.objectId}`;
- if (this.failFor.has(key)) {
- this.events.push(`import-failed:${ride.objectId}`);
- throw new Error("simulated power loss between write() and fsync()");
- }
- const held = this.rides.get(key);
- if (held) {
- // The real thing rewrites the files it is missing, keeps the names and keeps
- // `importedAt`, and reports `imported: false` — this is the same ride arriving again,
- // not a new one. Mirrored here so the pull's repair path is exercised rather than
- // stubbed.
- const repaired = { ...held, present: true, gpxPresent: true };
- this.rides.set(key, repaired);
- this.gpx.set(key, ride.gpx);
- this.objects.set(key, ride.object);
- this.events.push(held.present ? `import-noop:${ride.objectId}` : `repaired:${ride.objectId}`);
- return { ride: repaired, imported: false };
- }
- const landed: LibraryRide = {
- key,
- serial: ride.serial,
- storeId: ride.storeId,
- objectId: ride.objectId,
- name: ride.name,
- startTime: ride.startTime,
- distanceM: ride.distanceM,
- movingTimeS: ride.movingTimeS,
- climbM: ride.climbM,
- points: ride.points,
- bytes: ride.object.length,
- crc32: ride.crc32,
- importedAt: 1_700_000_000 + this.rides.size,
- // The split layout: the archive lives in app data, only the GPX in the visible folder.
- ridePath: `/app-data/ride-archive/${ride.objectId}.obcride`,
- gpxPath: `${this.folder}/${ride.objectId}.gpx`,
- track: ride.track,
- present: true,
- gpxPresent: true,
- };
- this.rides.set(key, landed);
- this.gpx.set(key, ride.gpx);
- this.objects.set(key, ride.object);
- this.events.push(`imported:${ride.objectId}`);
- return { ride: landed, imported: true };
- }
-
- readonly gpx = new Map();
- readonly objects = new Map();
-
- async readObject(key: string): Promise {
- const bytes = this.objects.get(key);
- if (!bytes) throw new Error(`no ride ${key}`);
- return bytes;
- }
-
- async writeGpx(key: string, gpx: string): Promise {
- this.gpx.set(key, gpx);
- return `${this.folder}/${key}.gpx`;
- }
-
- async reveal(): Promise {}
- async chooseFolder(): Promise {
- return null;
- }
-
- /** A ride the rider deleted in the file manager: the record stays, the bytes are gone. */
- loseFile(key: string): void {
- const held = this.rides.get(key);
- if (held) this.rides.set(key, { ...held, present: false });
- }
-
- /** Keys whose file is really there — "what is on the disk", which is what a pull asks. */
- held(): string[] {
- return [...this.rides.values()].filter((ride) => ride.present).map((ride) => ride.key).sort();
- }
-}
-
-/** A live client + device pair over the loopback pipe, plus the narrowed source the pull is given. */
-function connect(options: { storeId?: string } = {}) {
- const rig = flatDevice({ storeId: options.storeId ?? CARD_A });
- return { ...rig, source: rideAccess(rig.client) };
-}
-
-/**
- * The connected device's `(serial, era)`, derived exactly as the UI derives it — over the two reads
- * every connection already does. Re-read rather than remembered, because that is the point of the
- * era: a card swap changes it under a running app.
- */
-async function scopeNow(client: FlatStoreClient): Promise {
- const page = await client.listPage({});
- return rideScope(await client.deviceInfo(), { storeId: page.storeId, commitSequence: page.commitSequence });
-}
-
-/**
- * Put a ride on the device's card, catalog entry and all.
- *
- * The store assigns the id, so a caller that needs one reads it off the entry that comes back.
- * Seeding in order gives 1, 2, 3 — which is what the keys below are written against.
- */
-function seedRide(device: ReturnType["device"], name: string, startTime: number) {
- const bytes = encodeRideObject(rideObject(name, startTime));
- const entry = device.seed({ kind: ObjectKind.Ride, displayName: name, bytes });
- return { entry, bytes };
-}
-
-// --- acceptance ----------------------------------------------------------------
-
-describe("pulling rides into the library", () => {
- it("pulls every ride the card holds and deduplicates them by the id the card assigned", async () => {
- // The ids are the store's, not this test's. That a key survives an id above 2^53 is pinned
- // where the key is built (`rides.test.ts`, "keys the complete card identity and decimal u64
- // object id"); what is pinned here is that a pull uses that key and repeats nothing.
- const { device, client, source, close } = connect();
- try {
- const scope = await scopeNow(client);
- const seeded = ["Dawn", "Noon", "Dusk"].map((name) => seedRide(device, name, 1_700_000_000).entry);
- const ids = seeded.map((entry) => entry.objectId);
- const library = new RecordingLibrary();
- const first = await pullRides(source, library, scope, ctx());
- expect(first.failed).toEqual([]);
- expect(first.imported.map((ride) => ride.objectId)).toEqual(ids);
- expect(library.held()).toEqual(ids.map((id) => `${SERIAL}:${CARD_A}:${id}`).sort());
- const second = await pullRides(source, library, scope, ctx());
- expect(second.imported).toEqual([]);
- expect(second.alreadyHeld).toBe(3);
- } finally {
- await close();
- }
- });
-
- it("is idempotent: a second pull downloads nothing, duplicates nothing and re-stamps nothing", async () => {
- const { device, client, source, close } = connect();
- try {
- const scope = await scopeNow(client);
- seedRide(device, "Dawn Patrol", 1_700_000_000);
- seedRide(device, "Gravel Hour", 1_700_100_000);
- const library = new RecordingLibrary();
-
- const first = await pullRides(source, library, scope, ctx());
- expect(first.listed).toBe(2);
- expect(first.imported.map((ride) => ride.objectId)).toEqual([1n, 2n]);
- const stamps = [...library.rides.values()].map((r) => [r.key, r.importedAt] as const);
-
- const second = await pullRides(source, library, scope, ctx());
- expect(second.imported).toEqual([]);
- expect(second.alreadyHeld).toBe(2);
- expect(library.rides.size).toBe(2);
- // The ride files were never touched a second time.
- expect(library.events.filter((e) => e.startsWith("imported:"))).toEqual(["imported:1", "imported:2"]);
- expect([...library.rides.values()].map((r) => [r.key, r.importedAt] as const)).toEqual(stamps);
- } finally {
- await close();
- }
- });
-
- it("skips a ride the device is still recording, and names it in the report", async () => {
- // A `GET` of a `RECORDING` entry is refused — its length and CRC are zero until the commit
- // that ends it — so there is nothing to copy yet. Counting it is what lets the page say "one
- // ride is still being recorded" rather than silently listing fewer rides than the device has.
- const { device, client, source, close } = connect();
- try {
- const scope = await scopeNow(client);
- seedRide(device, "Finished", 1_700_000_000);
- device.seed({ kind: ObjectKind.Ride, displayName: "Still going", flags: EntryFlags.Recording });
- const library = new RecordingLibrary();
-
- const report = await pullRides(source, library, scope, ctx());
-
- expect(report.recording).toBe(1);
- expect(report.listed, "the recording ride is not something the pull could act on").toBe(1);
- expect(report.imported.map((ride) => ride.objectId)).toEqual([1n]);
- expect(report.failed).toEqual([]);
- expect(library.held()).toEqual([rideKey(scope, 1n)]);
- } finally {
- await close();
- }
- });
-
- it("leaves a ride out of the library when its durable write fails, and fetches it again next time", async () => {
- const { device, client, source, close } = connect();
- try {
- const scope = await scopeNow(client);
- seedRide(device, "Landed", 1_700_000_000);
- seedRide(device, "Interrupted", 1_700_100_000);
- seedRide(device, "Also landed", 1_700_200_000);
- const library = new RecordingLibrary();
- library.failFor.add(rideKey(scope, 2n));
-
- const report = await pullRides(source, library, scope, ctx());
-
- expect(report.failed.map((f) => f.objectId)).toEqual([2n]);
- expect(report.imported.map((r) => r.objectId)).toEqual([1n, 3n]);
- expect(library.held()).toEqual([rideKey(scope, 1n), rideKey(scope, 3n)].sort());
-
- // …and the next pull, with the write working, fetches ride 2 and only then holds it.
- library.failFor.clear();
- const retry = await pullRides(source, library, scope, ctx());
- expect(retry.imported.map((r) => r.objectId)).toEqual([2n]);
- expect(library.held()).toHaveLength(3);
- } finally {
- await close();
- }
- });
-
- it("imports both rides when a card swap recycles an object id", async () => {
- // A re-initialized card mints a new `StoreId` and starts its ids at 1 again, so a *different*
- // ride lands on id 1. A bare-id library would hold one row and answer "up to date" forever.
- const library = new RecordingLibrary();
-
- const first = connect({ storeId: CARD_A });
- const oldEra = await scopeNow(first.client);
- expect(oldEra.storeId).toBe(CARD_A);
- seedRide(first.device, "Old era ride", 1_700_000_000);
- await pullRides(first.source, library, oldEra, ctx());
- expect(library.rides.size).toBe(1);
- await first.close();
-
- const second = connect({ storeId: CARD_B });
- try {
- const newEra = await scopeNow(second.client);
- expect(newEra.storeId).toBe(CARD_B);
- expect(newEra.serial).toBe(oldEra.serial);
- seedRide(second.device, "New era ride", 1_800_000_000);
-
- const after = await pullRides(second.source, library, newEra, ctx());
- expect(after.imported.map((r) => r.name)).toEqual(["New era ride"]);
- // Two rows, two keys, one object id.
- expect([...library.rides.keys()].sort()).toEqual(
- [`${SERIAL}:${CARD_A}:1`, `${SERIAL}:${CARD_B}:1`].sort(),
- );
- expect(new Set([...library.rides.values()].map((r) => r.objectId))).toEqual(new Set([1n]));
- } finally {
- await second.close();
- }
- });
-
- it("re-downloads a ride whose file the rider deleted, keeping its original importedAt", async () => {
- // "Do I already have it" is a question about the disk, not about the index: a record whose
- // file is gone is not a durable copy, so the ride is fetched again — and it is a repair
- // rather than an import, because the rider first got it long ago.
- const { device, client, source, close } = connect();
- try {
- const scope = await scopeNow(client);
- for (const [at, name] of ["One", "Two", "Three"].entries()) {
- seedRide(device, name, 1_700_000_000 + at * 1000);
- }
- const library = new RecordingLibrary();
- await pullRides(source, library, scope, ctx());
- const firstStamp = library.rides.get(rideKey(scope, 2n))!.importedAt;
-
- library.loseFile(rideKey(scope, 2n));
- const again = await pullRides(source, library, scope, ctx());
-
- expect(again.imported).toEqual([]);
- expect(again.repaired.map((r) => r.objectId)).toEqual([2n]);
- expect(again.repaired[0].importedAt).toBe(firstStamp);
- expect(again.alreadyHeld).toBe(2);
- expect(library.held()).toHaveLength(3);
- } finally {
- await close();
- }
- });
-
- it("refuses to import anything from a device whose card identity it could not read", async () => {
- // The fail-closed posture: without both halves of the era, an id from this device cannot be
- // told apart from another device's, so nothing is keyed and nothing is copied. A missing
- // StoreId never shares an identity with a readable card.
- const { device, source, close } = connect();
- try {
- seedRide(device, "Unkeyable", 1_700_000_000);
- const library = new RecordingLibrary();
- await expect(pullRides(source, library, { serial: SERIAL, storeId: null }, ctx())).rejects.toMatchObject({
- name: "RideLibraryError",
- code: "no-scope",
- });
- await expect(pullRides(source, library, { serial: "", storeId: CARD_A }, ctx())).rejects.toThrow(
- /card identity/,
- );
- expect(library.rides.size).toBe(0);
- } finally {
- await close();
- }
- });
-
- it("stores a GPX the device itself would have written, and the object it sent", async () => {
- const { device, client, source, close } = connect();
- try {
- const scope = await scopeNow(client);
- const { bytes } = seedRide(device, "Schauinsland", 1_700_000_000);
- const library = new RecordingLibrary();
- await pullRides(source, library, scope, ctx());
-
- const key = rideKey(scope, 1n);
- // The archive is the device's bytes, unaltered — which is what makes the library
- // lossless while `track_to_gpx` still omits ``.
- expect(library.objects.get(key)).toEqual(bytes);
- const gpx = library.gpx.get(key) ?? "";
- expect(gpx).toContain('Schauinsland ");
- expect(gpx.match(/ {
- // An 88-byte catalog entry is id, revision, length, CRC, kind, flags and a display name. A
- // ride's start time, distance and moving time exist only inside the object — which this path
- // downloads anyway, so nothing is lost; what is gone is showing those figures beforehand.
- const { device, client, source, close } = connect();
- try {
- const scope = await scopeNow(client);
- const ride = rideObject("Kaiserstuhl", 1_700_300_000);
- const seeded = device.seed({
- kind: ObjectKind.Ride,
- displayName: "Kaiserstuhl",
- bytes: encodeRideObject(ride),
- });
- const library = new RecordingLibrary();
-
- const landed = (await pullRides(source, library, scope, ctx())).imported[0];
-
- expect(landed).toMatchObject({
- objectId: seeded.objectId,
- serial: scope.serial,
- storeId: scope.storeId,
- name: ride.name,
- startTime: ride.startTime,
- distanceM: ride.distanceM,
- movingTimeS: ride.movingTimeS,
- climbM: ride.climbM,
- points: ride.points.length,
- });
- } finally {
- await close();
- }
- });
-
- it("pulls one ride down the same path the batch uses", async () => {
- const { device, client, source, close } = connect();
- try {
- const scope = await scopeNow(client);
- seedRide(device, "First", 1_700_000_000);
- seedRide(device, "Second", 1_700_100_000);
- const library = new RecordingLibrary();
-
- const listed = await source.listRides();
- const one = await pullRide(source, library, scope, listed[1], ctx());
-
- expect(one.imported).toBe(true);
- expect(library.held()).toEqual([rideKey(scope, 2n)]);
- } finally {
- await close();
- }
- });
-});
-
-describe("the track preview", () => {
- it("is drawn from the ride's own points, keeping the first and the last", () => {
- const ride = rideObject("Long", 1_700_000_000, 5_000);
- const track = previewTrack(ride);
- expect(track.length).toBeLessThanOrEqual(PREVIEW_POINTS);
- expect(track.length).toBeGreaterThan(2);
- expect(track[0]).toEqual([
- ride.points[0].latMicrodegrees / 1e6,
- ride.points[0].lonMicrodegrees / 1e6,
- ]);
- const last = ride.points[ride.points.length - 1];
- expect(track[track.length - 1]).toEqual([
- last.latMicrodegrees / 1e6,
- last.lonMicrodegrees / 1e6,
- ]);
- });
-
- it("keeps a short ride whole", () => {
- expect(previewTrack(rideObject("Short", 1, 10))).toHaveLength(10);
- expect(previewTrack({ ...rideObject("None", 1, 1), points: [] })).toEqual([]);
- });
-
- it("fits inside its box and never divides by zero on a ride that never moved", () => {
- const path = trackPath(previewTrack(rideObject("Loop", 1, 100)), 120, 60);
- expect(path).toMatch(/^M[\d.]+ [\d.]+L/);
- const coords = [...(path ?? "").matchAll(/([\d.]+) ([\d.]+)/g)];
- expect(coords.length).toBeGreaterThan(2);
- for (const [, x, y] of coords) {
- expect(Number(x)).toBeGreaterThanOrEqual(0);
- expect(Number(x)).toBeLessThanOrEqual(120);
- expect(Number(y)).toBeGreaterThanOrEqual(0);
- expect(Number(y)).toBeLessThanOrEqual(60);
- }
- // A stationary ride is a dot, not a NaN.
- expect(trackPath([[48, 7.8], [48, 7.8]], 100, 50)).not.toContain("NaN");
- expect(trackPath([[48, 7.8]], 100, 50)).toBeNull();
- expect(trackPath([], 100, 50)).toBeNull();
- });
-});
diff --git a/builder/web/src/lib/device/library.ts b/builder/web/src/lib/device/library.ts
deleted file mode 100644
index f5cfbc1e48..0000000000
--- a/builder/web/src/lib/device/library.ts
+++ /dev/null
@@ -1,462 +0,0 @@
-/**
- * The managed ride library, and the pull that fills it.
- *
- * The counterpart to `rides.ts`, which is the hosted tier's one-shot GPX export and is deliberately
- * a dead end. This is the real product for Android and no-phone riders: rides land in a folder they
- * can see, back up and drag into anything.
- *
- * Nothing in this file is Tauri-aware. The {@link RideLibrary} it writes through is an interface
- * whose only shipped implementation is `lib/desktop/library.ts`, and whose other implementation is
- * the fake in `library.test.ts`. That split is what lets the two rules below be tested as behaviour
- * rather than as a mocked call sequence.
- *
- * **Always pull the full ride list and dedupe locally.** What decides whether a ride is fetched is
- * whether *this library* already holds it, never anything the device says about it. Pulling twice is
- * then a no-op by construction. `LIST` makes that cheap: a catalog page is metadata, and nothing is
- * downloaded to decide what to download.
- *
- * **The key is `(serial, StoreId, ObjectId)`.** An `ObjectId` is never reused within one card, but a
- * re-initialized card mints a new `StoreId` and starts its ids again, so a bare id names two
- * different rides on either side of one. The iOS companion uses the same key, so the two libraries
- * agree about what "the same ride" is.
- *
- * A possession acknowledgement is not on the USB cable: it changes no object and therefore has no
- * store meaning, so it keeps the BLE control surface it already had. A rider who syncs only over the
- * cable gets their rides copied and the device is not told. The ordering discipline that ack needed
- * — import resolves only after fsync — is kept anyway, because it is what makes
- * {@link PullReport} true.
- */
-
-import { trackToGpx } from "../convert/bridge";
-import { Crc32 } from "../usb/crc32";
-import { decodeRideObject, encodeRideObject, type RideObject } from "../usb/objects";
-import type { CatalogEntry } from "../usb/protocol";
-import {
- RideExportError,
- recordedRides,
- rideKey,
- type RideScope,
- type RideSource,
-} from "./rides";
-import type { JobContext } from "./progress";
-
-export type { CatalogEntry, RideObject, RideScope };
-
-/**
- * One ride in the library, as the index stores it.
- *
- * Mirrors `rides::LibraryRide` in `builder/desktop/src/rides.rs` field for field. `present` and
- * `gpxPresent` are recomputed against the filesystem on every read there, so they describe the disk
- * now rather than when the entry was written. The two paths point at different places: `ridePath` is
- * the archived `.obcride` in **app data**, `gpxPath` the `.gpx` in the **visible** folder, and
- * `present` means the archive file exists.
- */
-export interface LibraryRide {
- readonly key: string;
- readonly serial: string;
- /** The complete lowercase 32-digit StoreId hex string. */
- readonly storeId: string;
- readonly objectId: bigint;
- readonly name: string;
- /** Ride start, unix seconds UTC. `0` on a device that never had a trusted clock. */
- readonly startTime: number;
- readonly distanceM: number;
- readonly movingTimeS: number;
- readonly climbM: number;
- readonly points: number;
- readonly bytes: number;
- readonly crc32: number;
- /** When this app first landed the ride. Never re-stamped by a second pull. */
- readonly importedAt: number;
- readonly ridePath: string;
- readonly gpxPath: string;
- /** The downsampled `[lat, lon]` preview, in degrees — drawn from the ride's own points. */
- readonly track: readonly (readonly [number, number])[];
- readonly present: boolean;
- readonly gpxPresent: boolean;
-}
-
-/** One ride, on its way into the library. */
-export interface RideImport {
- readonly serial: string;
- readonly storeId: string;
- readonly objectId: bigint;
- readonly name: string;
- readonly startTime: number;
- readonly distanceM: number;
- readonly movingTimeS: number;
- readonly climbM: number;
- readonly points: number;
- readonly crc32: number;
- readonly track: readonly (readonly [number, number])[];
- /** The ride object exactly as it came off the wire — the lossless archive. */
- readonly object: Uint8Array;
- readonly gpx: string;
-}
-
-/** Where the library is, and what is in it. */
-export interface LibraryView {
- readonly folder: string;
- /** False once the rider has relocated it. Only affects what the UI says. */
- readonly isDefault: boolean;
- readonly rides: readonly LibraryRide[];
-}
-
-/**
- * The managed folder, as this module needs it.
- *
- * Every method is a promise because the only implementation is a filesystem behind an IPC boundary,
- * and because {@link import} has to be awaited for its durability to mean anything.
- */
-export interface RideLibrary {
- view(): Promise;
- /**
- * Land one ride durably. **Resolves only after fsync** — of the ride object, of the GPX, and of
- * the index that names them. Idempotent on `(serial, storeId, id)`: a second import of a ride
- * already held writes nothing and does not move its `importedAt`.
- */
- import(ride: RideImport): Promise<{ ride: LibraryRide; imported: boolean }>;
- /** The stored ride object of one key — what a GPX re-export decodes. */
- readObject(key: string): Promise;
- /** (Re-)write one ride's GPX. Resolves to where it went. */
- writeGpx(key: string, gpx: string): Promise;
- /** Show a file (or the folder) in the OS file manager. */
- reveal(path: string): Promise;
- /** Open the native chooser and move the library. `null` when the rider dismissed it. */
- chooseFolder(): Promise;
-}
-
-/**
- * - `no-scope` — the device reported no serial, or no `StoreId`. Ids from it cannot be keyed to an
- * era, so nothing is imported.
- */
-export type RideLibraryErrorCode = "no-scope";
-
-export class RideLibraryError extends Error {
- readonly code: RideLibraryErrorCode;
-
- constructor(code: RideLibraryErrorCode, message: string) {
- super(message);
- this.name = "RideLibraryError";
- this.code = code;
- }
-}
-
-/** One ride the pull could not land, and why. The rest of the batch still lands. */
-interface RideFailure {
- readonly objectId: bigint;
- readonly name: string;
- readonly message: string;
-}
-
-export interface PullReport {
- /** Rides the device listed — the *whole* catalog, always. */
- readonly listed: number;
- /** Rides new to this library. */
- readonly imported: readonly LibraryRide[];
- /**
- * Rides the library had a *record* of but not the file — most often because the rider deleted
- * something in the file manager. Re-downloaded and re-written; their `importedAt` is untouched,
- * so they are not new and are not counted as such.
- */
- readonly repaired: readonly LibraryRide[];
- /** Rides the library already held whole, so nothing was downloaded. */
- readonly alreadyHeld: number;
- readonly failed: readonly RideFailure[];
- /** Rides the device is still recording, which it refuses to serve. Named, never silent. */
- readonly recording: number;
-}
-
-/**
- * Pull every ride the device does not already hold a durable copy of here.
- *
- * The order is the contract:
- *
- * 1. list the whole ride catalog, unconditionally, minus what is still recording;
- * 2. dedupe locally by `(serial, StoreId, ObjectId)` against the library's own index;
- * 3. download, decode, convert and import each missing ride one at a time, each import resolving
- * only after its fsync.
- *
- * A ride that fails at step 3 is reported and skipped; the others still land.
- */
-export async function pullRides(
- source: RideSource,
- library: RideLibrary,
- scope: RideScope,
- ctx: JobContext,
-): Promise {
- requireScope(scope);
-
- ctx.phase("reading");
- // Rule 1: the full catalog, every time. There is no "what's new" query and there must not be
- // one — the device does not know what this library holds.
- const listed = await source.listRides(ctx.signal);
- const available = recordedRides(listed);
-
- // Rule 2: dedupe here, by the composite key. `present` is part of the test on purpose — a record
- // whose ride object the rider deleted is not a durable copy, so it is fetched again.
- //
- // `gpxPresent` deliberately is *not*: a missing GPX is a derived file and the archive it comes
- // from is right there, so the logbook's auto-repair regenerates it locally instead
- // ({@link reexportGpx}).
- const held = new Map((await library.view()).rides.map((ride) => [ride.key, ride]));
- const wanted = [...available]
- // Oldest first, by `ObjectId`. A `LIST` entry carries no start time, and the id is a
- // monotonic allocation cursor — so on one card, id order *is* recording order. It is a proxy,
- // and it is the only one the catalog offers.
- .sort((a, b) => (a.objectId < b.objectId ? -1 : a.objectId > b.objectId ? 1 : 0))
- .filter((entry) => !held.get(rideKey(scope, entry.objectId))?.present);
-
- const imported: LibraryRide[] = [];
- const repaired: LibraryRide[] = [];
- const failed: RideFailure[] = [];
- for (const entry of wanted) {
- ctx.signal.throwIfAborted();
- try {
- const landed = await importRide(source, library, scope, entry, ctx);
- // Everything in `wanted` was missing something, so a ride the library reports as not
- // new was a record without its file — repaired rather than imported.
- (landed.imported ? imported : repaired).push(landed.ride);
- } catch (cause) {
- if (ctx.signal.aborted) throw cause;
- failed.push({
- objectId: entry.objectId,
- name: entry.displayName || `Ride ${entry.objectId}`,
- message: cause instanceof Error ? cause.message : String(cause),
- });
- }
- }
-
- ctx.phase("done");
- return {
- listed: available.length,
- imported,
- repaired,
- alreadyHeld: available.length - wanted.length,
- failed,
- recording: listed.length - available.length,
- };
-}
-
-/** Both halves of the era, or nothing is copied. */
-function requireScope(scope: RideScope): asserts scope is RideScope & { storeId: string } {
- if (!scope.serial || scope.storeId === null) {
- throw new RideLibraryError(
- "no-scope",
- "This device did not report both a serial number and a card identity, so its ride ids " +
- "cannot be told apart from another device's. Nothing was copied.",
- );
- }
-}
-
-/** Pull one ride and land it. Split out so a single-ride retry is the same code path. */
-async function importRide(
- source: RideSource,
- library: RideLibrary,
- scope: RideScope & { storeId: string },
- entry: CatalogEntry,
- ctx: JobContext,
-): Promise<{ ride: LibraryRide; imported: boolean }> {
- ctx.phase("downloading", Number(entry.payloadLength));
- const object = await source.downloadRide(entry, {
- signal: ctx.signal,
- onProgress: (done: number, total: number) => ctx.progress(done, total),
- });
-
- ctx.phase("converting", object.length);
- // The client verified the whole-payload CRC before returning, so a decode failure here is a
- // *format* disagreement — firmware newer than this build — and needs the other sentence.
- let ride: RideObject;
- try {
- ride = decodeRideObject(object);
- } catch (cause) {
- throw new RideExportError(
- "unreadable-ride",
- "That ride arrived intact but this build cannot read it. That usually means the device " +
- "is running newer firmware than the app.",
- { cause },
- );
- }
- if (ride.points.length === 0) {
- throw new RideExportError(
- "empty-ride",
- "That ride has no recorded points — it was probably stopped before the device had a fix.",
- );
- }
-
- const gpx = await gpxOf(ride);
- ctx.phase("verifying");
- // Everything below this line is the durable write.
- //
- // Every field but the id and the name comes from the **payload**: a `LIST` entry carries id,
- // revision, length, CRC, kind, flags and a display name, so the distance, the duration and the
- // start time exist only inside the ride object. This path downloads the object anyway; what is
- // gone is the ability to show those figures *before* downloading.
- return library.import({
- serial: scope.serial,
- storeId: scope.storeId,
- objectId: entry.objectId,
- name: ride.name || entry.displayName,
- startTime: ride.startTime,
- distanceM: ride.distanceM,
- movingTimeS: ride.movingTimeS,
- climbM: ride.climbM,
- points: ride.points.length,
- // The device's own CRC-32 over the same bytes, kept in the index so the archive can be
- // re-checked without the device. It is also what a lost create is reconciled against.
- crc32: Crc32.of(object),
- track: previewTrack(ride),
- object,
- gpx,
- });
-}
-
-/** Pull one ride: the per-row pull, same code path as the bulk one. */
-export async function pullRide(
- source: RideSource,
- library: RideLibrary,
- scope: RideScope,
- entry: CatalogEntry,
- ctx: JobContext,
-): Promise<{ ride: LibraryRide; imported: boolean }> {
- requireScope(scope);
- const result = await importRide(source, library, scope, entry, ctx);
- ctx.phase("done");
- return result;
-}
-
-/**
- * The GPX, from the same `obc_route::track_to_gpx` the device runs at Finish.
- *
- * Through the wasm bridge over the same finished bytes the device serves, pinned byte-for-byte
- * against `specs/vectors/track-export.gpx`. There is no TypeScript GPX writer in this app and there
- * must never be one — a library whose files disagreed with the device's own export would be a
- * slow-burning support problem.
- */
-export async function gpxOf(ride: RideObject): Promise {
- return trackToGpx(encodeRideObject(ride), ride.name);
-}
-
-/** Re-export one library ride's GPX from its stored object. The auto-repair is this, in a loop. */
-export async function reexportGpx(library: RideLibrary, ride: LibraryRide): Promise {
- const object = await library.readObject(ride.key);
- return library.writeGpx(ride.key, await gpxOf(decodeRideObject(object)));
-}
-
-/**
- * How many points a stored preview keeps.
- *
- * The list draws a track a couple of hundred pixels wide, so more than this is index weight nobody
- * can see — and the index is read on every open. The Rust side enforces the same number, because a
- * ceiling only one end believes in is not a ceiling.
- */
-export const PREVIEW_POINTS = 256;
-
-/**
- * Downsample any `[lat, lon]` track to at most {@link PREVIEW_POINTS}, rounded to six decimals.
- *
- * Uniform stride rather than Douglas–Peucker: this is a thumbnail, the input is already a recorded
- * track, and a stride cannot introduce a shortcut across a switchback the way a tolerance-based
- * simplifier can. The first and last points are always kept. Shared by the library index and the
- * device page's thumbnail store, so a ride thumbnail is the same points in both places.
- */
-export function downsampleTrack(points: readonly (readonly [number, number])[]): Array<[number, number]> {
- if (points.length === 0) return [];
- // At or under the cap nothing is dropped — which also makes a second pass a no-op, so a track
- // that went through the ride library's downsample once is not thinned again by the thumb store.
- const stride = points.length <= PREVIEW_POINTS ? 1 : Math.ceil(points.length / (PREVIEW_POINTS - 1));
- const out: Array<[number, number]> = [];
- for (let i = 0; i < points.length; i += stride) {
- out.push([round6(points[i][0]), round6(points[i][1])]);
- }
- const last = points[points.length - 1];
- const tail: [number, number] = [round6(last[0]), round6(last[1])];
- if (out.length === 0 || out[out.length - 1][0] !== tail[0] || out[out.length - 1][1] !== tail[1]) {
- out.push(tail);
- }
- return out;
-}
-
-/** A downsampled `[lat, lon]` track for the list — {@link downsampleTrack} over a ride's points. */
-export function previewTrack(ride: RideObject): Array<[number, number]> {
- return downsampleTrack(ride.points.map((p) => [p.latMicrodegrees / 1e6, p.lonMicrodegrees / 1e6]));
-}
-
-/** Six decimals is a ~11 cm grid — the device's own GPX precision, and about a third of the JSON. */
-export function round6(deg: number): number {
- return Math.round(deg * 1e6) / 1e6;
-}
-
-/** One track fitted into a box by {@link fitTracks}: its path, and where it starts and ends. */
-export interface FittedTrack {
- /** `M … L …` path in the `width × height` viewBox. */
- readonly d: string;
- /** Projected `[x, y]` of the first point — the start dot. */
- readonly start: readonly [number, number];
- /** Projected `[x, y]` of the last point — the end dot. */
- readonly end: readonly [number, number];
-}
-
-/**
- * Fit one or more `[lat, lon]` tracks into a shared `width × height` box.
- *
- * One projection for the lot — a trip's stages are drawn against common bounds, so where stage 2
- * begins is where stage 1 ended. Equirectangular with a `cos(lat)` correction on longitude, which is
- * the projection a few kilometres of track deserves. A track with fewer than two points maps to
- * `null`.
- */
-export function fitTracks(
- tracks: ReadonlyArray,
- width: number,
- height: number,
- pad = 2,
-): Array {
- const all = tracks.flat();
- if (all.length < 2) return tracks.map(() => null);
- const lats = all.map((p) => p[0]);
- const lons = all.map((p) => p[1]);
- const midLat = (Math.min(...lats) + Math.max(...lats)) / 2;
- const kx = Math.cos((midLat * Math.PI) / 180) || 1e-6;
-
- const xs = lons.map((lon) => lon * kx);
- const minX = Math.min(...xs);
- const maxX = Math.max(...xs);
- const minY = Math.min(...lats);
- const maxY = Math.max(...lats);
- // A ride that never moved is a dot, not a divide-by-zero.
- const spanX = maxX - minX || 1e-9;
- const spanY = maxY - minY || 1e-9;
- const scale = Math.min((width - 2 * pad) / spanX, (height - 2 * pad) / spanY);
- const offsetX = (width - spanX * scale) / 2;
- const offsetY = (height - spanY * scale) / 2;
-
- const project = (point: readonly [number, number]): [number, number] => [
- offsetX + (point[1] * kx - minX) * scale,
- // SVG y grows downwards; north is up.
- height - offsetY - (point[0] - minY) * scale,
- ];
-
- return tracks.map((track) => {
- if (track.length < 2) return null;
- const d = track
- .map((point, i) => {
- const [x, y] = project(point);
- return `${i === 0 ? "M" : "L"}${x.toFixed(1)} ${y.toFixed(1)}`;
- })
- .join("");
- return { d, start: project(track[0]), end: project(track[track.length - 1]) };
- });
-}
-
-/**
- * An SVG path for one preview track, fitted to a `width × height` box — {@link fitTracks} for the
- * single-track case. Returns `null` when there is nothing to draw.
- */
-export function trackPath(
- track: readonly (readonly [number, number])[],
- width: number,
- height: number,
- pad = 2,
-): string | null {
- return fitTracks([track], width, height, pad)[0]?.d ?? null;
-}
diff --git a/builder/web/src/lib/device/manage.test.ts b/builder/web/src/lib/device/manage.test.ts
deleted file mode 100644
index 15ced6110f..0000000000
--- a/builder/web/src/lib/device/manage.test.ts
+++ /dev/null
@@ -1,187 +0,0 @@
-/**
- * Rename and trip editing: byte-level checks for the name rewrite (the one place this code edits a
- * format by hand), loopback round-trips for the replace-at-same-id semantics everything rests on.
- *
- * Both mutations are a `PUT` naming an existing object, so the two properties worth pinning
- * against a real device are that the replace keeps the `ObjectId` — every reference to the route
- * survives — and that it carries the revision it expects, so a listing something else has already
- * overtaken fails the compare-and-swap instead of clobbering.
- */
-
-import { beforeAll, describe, expect, it } from "vitest";
-
-import {
- MAX_TRIP_STAGE_ID,
- TripStageError,
- addStage,
- createTrip,
- moveStage,
- removeStage,
- renameRoute,
- renameRouteBytes,
- stageId,
- updateTrip,
-} from "./manage";
-import { decodeRouteHeader } from "./route";
-import { decodeTripObject, wholeDay, type TripObject } from "../usb/objects";
-import { flatDevice } from "../usb/flat-device";
-import { loadFlatDevice } from "../../../test-support/flat-device/load";
-import { ObjectKind } from "../usb/protocol";
-
-/** A minimal, valid OBCR: the 160-byte header + no points — enough for the header codec. */
-function obcrWithName(name: string): Uint8Array {
- const out = new Uint8Array(160);
- const view = new DataView(out.buffer);
- view.setUint32(0, 0x4f424352, false); // "OBCR"
- out[4] = 5; // version
- const bytes = new TextEncoder().encode(name);
- out[6] = bytes.length;
- out.set(bytes, 64);
- return out;
-}
-
-describe("renameRouteBytes", () => {
- it("rewrites the name and only the name", () => {
- const original = obcrWithName("Old name");
- original[100 + 12] = 0; // (offset 112 is outside the name field)
- const renamed = renameRouteBytes(original, "Grimsel – Furka");
- expect(decodeRouteHeader(renamed).name).toBe("Grimsel – Furka");
- // Everything outside the name field is untouched…
- expect(renamed.subarray(0, 6)).toEqual(original.subarray(0, 6));
- expect(renamed.subarray(7, 64)).toEqual(original.subarray(7, 64));
- // …and the input was not mutated.
- expect(decodeRouteHeader(original).name).toBe("Old name");
- });
-
- it("zero-pads: a shorter name leaves no tail of the longer one", () => {
- const renamed = renameRouteBytes(obcrWithName("A very long route name here"), "Short");
- expect(decodeRouteHeader(renamed).name).toBe("Short");
- expect(renamed.subarray(64 + 5, 64 + 48).every((b) => b === 0)).toBe(true);
- });
-
- it("caps at 48 bytes without splitting a codepoint, and refuses non-routes", () => {
- const long = "Ü".repeat(30); // 60 bytes of UTF-8
- const renamed = renameRouteBytes(obcrWithName("x"), long);
- const name = decodeRouteHeader(renamed).name;
- expect(new TextEncoder().encode(name).length).toBeLessThanOrEqual(48);
- expect(name).toBe("Ü".repeat(24));
- expect(() => renameRouteBytes(new Uint8Array(200), "x")).toThrow(/not an OBCR/);
- });
-
- it("falls back rather than writing an empty name", () => {
- expect(decodeRouteHeader(renameRouteBytes(obcrWithName("x"), " ")).name).toBe("Route");
- });
-});
-
-describe("stage mutators", () => {
- const trip: TripObject = { key: 1n, name: "T", startDate: 0, days: [1n, 2n, 3n].map(wholeDay) };
- const routes = (t: TripObject) => t.days.map((day) => day.route);
-
- it("add dedupes, remove drops by index, move clamps", () => {
- expect(addStage(trip, 2n)).toBe(trip);
- expect(routes(addStage(trip, 4n))).toEqual([1n, 2n, 3n, 4n]);
- expect(routes(removeStage(trip, 1))).toEqual([1n, 3n]);
- expect(routes(moveStage(trip, 0, 1))).toEqual([2n, 1n, 3n]);
- expect(routes(moveStage(trip, 2, 5))).toEqual([1n, 2n, 3n]);
- expect(moveStage(trip, 0, -1)).toBe(trip);
- });
-});
-
-describe("stageId", () => {
- it("refuses an ObjectId the trip format cannot name", () => {
- expect(stageId(1n)).toBe(1n);
- expect(stageId(MAX_TRIP_STAGE_ID)).toBe(MAX_TRIP_STAGE_ID);
- expect(() => stageId(MAX_TRIP_STAGE_ID + 1n)).toThrow(TripStageError);
- expect(() => stageId(0n)).toThrow(TripStageError);
- });
-});
-
-describe("against the real device", () => {
- beforeAll(loadFlatDevice);
-
- async function withDevice(body: (rig: ReturnType) => Promise) {
- const rig = flatDevice({});
- try {
- await body(rig);
- expect(rig.device.faults, "the device adapter saw a reaction it did not expect").toEqual([]);
- } finally {
- await rig.close();
- }
- }
-
- it("renames in both places: the OBCR header and §3.6's display name", async () => {
- // The two fields have different readers — the header's name is what the device shows while
- // navigating, the display name is what a catalog listing shows — so writing only one of them
- // would make the device and the device page disagree about what a route is called.
- await withDevice(async ({ client, device }) => {
- const seeded = device.seed({ kind: ObjectKind.Route, displayName: "Before", bytes: obcrWithName("Before") });
-
- const written = await renameRoute(client, seeded, "After");
-
- expect(written.objectId, "the id — and every reference to it — survives").toBe(seeded.objectId);
- expect(written.revision).toBe(2n);
- expect(device.entries).toHaveLength(1);
- expect(device.entries[0].displayName).toBe("After");
- expect(decodeRouteHeader(device.payloadOf(seeded.objectId)!).name).toBe("After");
- });
- });
-
- it("refuses a rename against a revision the object has already left, and changes nothing", async () => {
- // The page renames the entry it listed. A retaining replace by another peer leaves that
- // revision readable while moving the head on, which is exactly the state where a client that
- // did not carry an expected revision would silently overwrite the newer bytes.
- await withDevice(async ({ client, device }) => {
- const listed = device.seed({ kind: ObjectKind.Route, bytes: obcrWithName("Listed") });
- const head = obcrWithName("Someone else's");
- device.retain(listed, head, "Someone else's");
-
- await expect(renameRoute(client, listed, "Mine")).rejects.toMatchObject({ code: "revision-conflict" });
- expect(device.payloadOf(listed.objectId)).toEqual(head);
- expect(device.entries.map((entry) => [entry.revision, entry.displayName])).toEqual([
- [1n, ""],
- [2n, "Someone else's"],
- ]);
- });
- });
-
- it("creates, edits and reorders a trip through replace-at-same-id", async () => {
- await withDevice(async ({ client, device }) => {
- const created = await createTrip(client, " Tour du Mont Blanc ", [3n, 1n]);
- expect(decodeTripObject(device.payloadOf(created.objectId)!)).toMatchObject({
- name: "Tour du Mont Blanc",
- startDate: 0,
- days: [wholeDay(3n), wholeDay(1n)],
- });
-
- // The page re-lists after every mutation, so the revision each edit expects is the one
- // the catalog just reported — never one this code remembered.
- const revisionOf = async () => (await client.list({ kind: ObjectKind.Trip })).entries[0].revision;
- await updateTrip(client, { objectId: created.objectId, revision: await revisionOf() }, (t) =>
- addStage(t, 7n),
- );
- const moved = await updateTrip(client, { objectId: created.objectId, revision: await revisionOf() }, (t) =>
- moveStage(t, 2, -2),
- );
-
- expect(moved.days.map((day) => day.route)).toEqual([7n, 3n, 1n]);
- expect(decodeTripObject(device.payloadOf(created.objectId)!)).toEqual(moved);
- const trips = await client.list({ kind: ObjectKind.Trip });
- expect(trips.entries.map((entry) => [entry.objectId, entry.revision, entry.displayName])).toEqual([
- [created.objectId, 3n, "Tour du Mont Blanc"],
- ]);
- });
- });
-
- it("refuses to build a trip over a route the format cannot name, before sending anything", async () => {
- await withDevice(async ({ client, device }) => {
- await expect(createTrip(client, "Too far", [MAX_TRIP_STAGE_ID + 1n])).rejects.toBeInstanceOf(
- TripStageError,
- );
- expect(device.entries).toEqual([]);
- });
- });
-
- // Gone with the v1 wire: "uploading identical trip bytes twice converges on one object". The
- // A create is reconciled by the client rather than deduped on the wire —
- // `FlatStoreClient.findCreated`, covered in `flows.test.ts` and `client.test.ts`.
-});
diff --git a/builder/web/src/lib/device/manage.ts b/builder/web/src/lib/device/manage.ts
deleted file mode 100644
index 08aab8e5a2..0000000000
--- a/builder/web/src/lib/device/manage.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-/**
- * Renaming routes and editing trips — the mutations the device page offers beyond remove.
- *
- * Neither is a protocol feature, and that is the point: both ride on the one primitive the wire
- * already has, **a `PUT` naming an existing object replaces it in one commit**. A rename gets the
- * OBCR, rewrites the 48-byte name field in the payload, and puts the same object back under the same
- * `ObjectId`, so every reference to it survives. A trip edit does the same to its day list.
- *
- * **Every replace carries the revision it expects**, checked at admission and again immediately
- * before the commit, so an object something else replaced in between fails the compare-and-swap
- * instead of silently clobbering. A stale entry earns `revisionConflict` and the page re-lists.
- *
- * A rename writes the name in **two** places, because they have different readers: the OBCR header's
- * name is what the device shows while navigating, and the display name is what a catalog listing
- * shows. Writing only one would make the device page and the device disagree.
- *
- * Nothing here talks to the store: callers run these inside `dashboard.enqueue` and refresh after.
- */
-
-import type { FlatStoreClient } from "../usb/client";
-import { truncateUtf8 } from "../format";
-import { decodeTripObject, encodeTripObject, wholeDay, type TripObject } from "../usb/objects";
-import { ObjectKind, type CatalogEntry, type PutResponse } from "../usb/protocol";
-import { decodeRouteHeader, ROUTE_NAME_MAX } from "./route";
-
-/** The trip name field's cap — the same 48-byte field a route's name and the display name use. */
-export const TRIP_NAME_MAX = 48;
-
-/** The largest route id a trip can name: the flat store's complete nonzero `u64` ObjectId. */
-export const MAX_TRIP_STAGE_ID = 0xffff_ffff_ffff_ffffn;
-
-/** A route this trip format cannot name. Its own error, because the fix is not "try again". */
-export class TripStageError extends Error {
- constructor(objectId: bigint) {
- super(
- `Route ${objectId} cannot be put in a trip: its id is outside the trip format's nonzero ` +
- `u64 range (maximum ${MAX_TRIP_STAGE_ID}).`,
- );
- this.name = "TripStageError";
- }
-}
-
-/** Validate an `ObjectId` for the trip object's nonzero `u64` stage field. */
-export function stageId(objectId: bigint): bigint {
- if (objectId <= 0n || objectId > MAX_TRIP_STAGE_ID) throw new TripStageError(objectId);
- return objectId;
-}
-
-/**
- * The OBCR bytes with a new name in the header: length byte at offset 6, the null-padded 48-byte
- * field at 64. The old name is zeroed before the new one lands, because the field is *null-padded*
- * and a shorter name over a longer one would otherwise leave the tail of the old name in the file.
- */
-export function renameRouteBytes(obcr: Uint8Array, name: string): Uint8Array {
- decodeRouteHeader(obcr); // magic, version, length — refuse to "rename" something else
- const bytes = new TextEncoder().encode(cleanName(name, ROUTE_NAME_MAX, "Route"));
- const out = obcr.slice();
- out[6] = bytes.length;
- out.fill(0, 64, 64 + ROUTE_NAME_MAX);
- out.set(bytes, 64);
- return out;
-}
-
-/** Get, rewrite the name, replace at the same id. The `ObjectId` — and with it every reference to
- * the route — is exactly what this dance preserves. */
-export async function renameRoute(
- client: FlatStoreClient,
- route: Pick,
- name: string,
- signal?: AbortSignal,
-): Promise {
- const obcr = await client.get({ objectId: route.objectId, revision: route.revision }, { signal });
- const clean = cleanName(name, ROUTE_NAME_MAX, "Route");
- return client.put(
- {
- objectId: route.objectId,
- expectedRevision: route.revision,
- kind: ObjectKind.Route,
- displayName: clean,
- },
- renameRouteBytes(obcr.bytes, clean),
- { signal },
- );
-}
-
-/** Create a trip over existing routes. Returns what the commit published, id included. */
-export async function createTrip(
- client: FlatStoreClient,
- name: string,
- stages: readonly bigint[],
- signal?: AbortSignal,
-): Promise {
- const clean = cleanName(name, TRIP_NAME_MAX, "Trip");
- // The key names this trip for life; zero is reserved for "no trip".
- const key = crypto.getRandomValues(new BigUint64Array(1))[0] || 1n;
- const days = stages.map((id) => wholeDay(stageId(id)));
- const bytes = encodeTripObject({ key, name: clean, startDate: 0, days });
- return client.put({ kind: ObjectKind.Trip, displayName: clean }, bytes, { signal });
-}
-
-/**
- * Edit a trip: get, apply `mutate`, replace at the same id. Returns what was written.
- *
- * The read-modify-write is serialized against this page's other operations by the caller's queue,
- * and against everything else by the compare-and-swap: a trip that moved underneath this returns
- * `revisionConflict` rather than overwriting the change.
- */
-export async function updateTrip(
- client: FlatStoreClient,
- trip: Pick,
- mutate: (trip: TripObject) => TripObject,
- signal?: AbortSignal,
-): Promise {
- const current = decodeTripObject(
- (await client.get({ objectId: trip.objectId, revision: trip.revision }, { signal })).bytes,
- );
- const next = mutate(current);
- const written: TripObject = { ...next, name: cleanName(next.name, TRIP_NAME_MAX, "Trip") };
- await client.put(
- {
- objectId: trip.objectId,
- expectedRevision: trip.revision,
- kind: ObjectKind.Trip,
- displayName: written.name,
- },
- encodeTripObject(written),
- { signal },
- );
- return written;
-}
-
-export function addStage(trip: TripObject, routeId: bigint): TripObject {
- // Adding a stage that is already in the trip is a no-op, not a duplicate: the
- // menu offering the add has no way to know the trip's current stages are stale.
- if (trip.days.some((day) => day.route === routeId)) return trip;
- return { ...trip, days: [...trip.days, wholeDay(routeId)] };
-}
-
-export function removeStage(trip: TripObject, index: number): TripObject {
- return { ...trip, days: trip.days.filter((_, i) => i !== index) };
-}
-
-/** Move the stage at `index` by `delta` places, clamped to the list. */
-export function moveStage(trip: TripObject, index: number, delta: number): TripObject {
- const to = Math.max(0, Math.min(trip.days.length - 1, index + delta));
- if (to === index || index < 0 || index >= trip.days.length) return trip;
- const days = [...trip.days];
- const [moved] = days.splice(index, 1);
- days.splice(to, 0, moved);
- return { ...trip, days };
-}
-
-/** Trimmed, non-empty, inside the field's byte cap. */
-function cleanName(name: string, maxBytes: number, fallback: string): string {
- return truncateUtf8(name.trim() || fallback, maxBytes);
-}
diff --git a/builder/web/src/lib/device/multidrop.test.ts b/builder/web/src/lib/device/multidrop.test.ts
deleted file mode 100644
index b24badf9a6..0000000000
--- a/builder/web/src/lib/device/multidrop.test.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { commonPrefixName, sortForTrip } from "./multidrop";
-
-describe("sortForTrip", () => {
- it("orders naturally, so day 10 follows day 2", () => {
- const files = [{ name: "tmb-day10.gpx" }, { name: "tmb-day2.gpx" }, { name: "tmb-day1.gpx" }];
- expect(sortForTrip(files).map((f) => f.name)).toEqual([
- "tmb-day1.gpx",
- "tmb-day2.gpx",
- "tmb-day10.gpx",
- ]);
- });
-});
-
-describe("commonPrefixName", () => {
- it("suggests the shared stem, shorn of day numbering", () => {
- expect(commonPrefixName(["tour-mont-blanc-day1.gpx", "tour-mont-blanc-day2.gpx"])).toBe(
- "tour-mont-blanc",
- );
- expect(commonPrefixName(["Jura Crest 1.gpx", "Jura Crest 2.gpx"])).toBe("Jura Crest");
- expect(commonPrefixName(["Etappe_1.gpx", "Etappe_2.gpx"])).toBe("Etappe");
- });
-
- it("suggests nothing rather than something silly", () => {
- expect(commonPrefixName([])).toBe("");
- expect(commonPrefixName(["alps.gpx", "coast.gpx"])).toBe("");
- expect(commonPrefixName(["a1.gpx", "a2.gpx"])).toBe("");
- });
-
- it("stays inside the trip name's 48-byte cap", () => {
- const long = "Ü".repeat(40); // 80 UTF-8 bytes shared by both names
- const name = commonPrefixName([`${long} one.gpx`, `${long} two.gpx`]);
- expect(new TextEncoder().encode(name).length).toBeLessThanOrEqual(48);
- expect(name.length).toBeGreaterThan(0);
- });
-});
diff --git a/builder/web/src/lib/device/multidrop.ts b/builder/web/src/lib/device/multidrop.ts
deleted file mode 100644
index 7ef1115cdf..0000000000
--- a/builder/web/src/lib/device/multidrop.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- * Several GPX files at once: the small pure pieces behind the "add as a trip?" dialog.
- *
- * The uploads themselves are ordinary `sendRoute` calls the page sequences; what lives here is
- * only what a test can hold still — the ordering and the suggested trip name.
- */
-
-import { truncateUtf8 } from "../format";
-import { TRIP_NAME_MAX } from "./manage";
-
-/**
- * Sort dropped files the way a rider numbered them: natural order ("day 2" before "day 10"),
- * case-insensitive. `DataTransfer` order is whatever the OS felt like; filenames are the one
- * ordering hint the drop actually carries.
- */
-export function sortForTrip(files: readonly T[]): T[] {
- return [...files].sort((a, b) =>
- a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" }),
- );
-}
-
-/**
- * A trip name suggested from the files' common prefix — "tmb-day1.gpx, tmb-day2.gpx" → "tmb".
- * Empty when the names share nothing usable, so the dialog shows a blank field rather than a
- * guess nobody typed.
- */
-export function commonPrefixName(filenames: readonly string[]): string {
- if (filenames.length === 0) return "";
- const stems = filenames.map(stem);
- let prefix = stems[0];
- for (const name of stems.slice(1)) {
- let i = 0;
- while (i < prefix.length && i < name.length && prefix[i].toLowerCase() === name[i].toLowerCase()) i++;
- prefix = prefix.slice(0, i);
- if (!prefix) return "";
- }
- // Trim the numbering tail ("tmb-day" → "tmb", "Etappe_" → "Etappe"): digits and separators
- // always; an ordinal word only when a separator precedes it, so a name that *is* the word
- // ("Etappe") survives. A two-character residue is noise, not a name.
- const base = prefix.replace(/[\s._-]*\d*$/, "").replace(/[\s._-]+$/, "");
- const shorn = base.replace(/[\s._-]+(day|stage|etappe|part|tag)$/i, "");
- const trimmed = shorn || base;
- return trimmed.length >= 3 ? truncateUtf8(trimmed, TRIP_NAME_MAX) : "";
-}
-
-/** A filename without its extension or any path. */
-function stem(filename: string): string {
- return filename.replace(/^.*[\\/]/, "").replace(/\.[^./\\]+$/, "");
-}
diff --git a/builder/web/src/lib/device/progress.ts b/builder/web/src/lib/device/progress.ts
index 8040c533d8..48452bb63b 100644
--- a/builder/web/src/lib/device/progress.ts
+++ b/builder/web/src/lib/device/progress.ts
@@ -3,7 +3,7 @@
* TypeScript, tested under Node) and the thing that renders them (`job.svelte.ts`, runes).
*
* It lives in its own file so the flows never import a `.svelte.ts` module: everything with logic in
- * it stays framework-free and reusable by the desktop app.
+ * it stays framework-free.
*/
/**
diff --git a/builder/web/src/lib/device/rideMap.test.ts b/builder/web/src/lib/device/rideMap.test.ts
deleted file mode 100644
index ced581699a..0000000000
--- a/builder/web/src/lib/device/rideMap.test.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-// The logbook map's clustering, pinned as pure math (see rideMap.ts): membership and counts,
-// the adjacent-cell merge, the zoom threshold, and the representative point. No Leaflet here —
-// the component draws whatever these functions answer, so these answers are the behavior.
-
-import { describe, expect, it } from "vitest";
-import {
- CLUSTER_BELOW_ZOOM,
- clusterRides,
- clustersAt,
- projectPx,
- representativePoint,
- type RideTrack,
-} from "./rideMap";
-
-/** A tiny synthetic track around a center — enough points for a midpoint and real bounds. */
-function trackAround(lat: number, lon: number, key: string, span = 0.02): RideTrack {
- const track: Array<[number, number]> = [];
- for (let i = 0; i < 9; i++) {
- const t = i / 8;
- track.push([lat - span / 2 + span * t, lon + span * Math.sin(t * Math.PI)]);
- }
- return { key, track };
-}
-
-const FREIBURG_A = trackAround(47.99, 7.85, "a");
-const FREIBURG_B = trackAround(48.01, 7.87, "b");
-const KAISERSTUHL = trackAround(48.09, 7.66, "c");
-const INNSBRUCK = trackAround(47.27, 11.39, "d");
-
-describe("clustersAt", () => {
- it("clusters below the threshold and shows tracks at and above it", () => {
- expect(clustersAt(CLUSTER_BELOW_ZOOM - 1)).toBe(true);
- expect(clustersAt(CLUSTER_BELOW_ZOOM)).toBe(false);
- expect(clustersAt(CLUSTER_BELOW_ZOOM + 5)).toBe(false);
- expect(clustersAt(2)).toBe(true);
- });
-});
-
-describe("representativePoint", () => {
- it("is the track's midpoint by index", () => {
- const odd = [[1, 1], [2, 2], [3, 3]] as const;
- expect(representativePoint(odd)).toEqual([2, 2]);
- const even = [[1, 1], [2, 2], [3, 3], [4, 4]] as const;
- expect(representativePoint(even)).toEqual([3, 3]);
- expect(representativePoint([[5, 6]])).toEqual([5, 6]);
- expect(representativePoint([])).toBeNull();
- });
-});
-
-describe("clusterRides", () => {
- it("groups nearby rides and keeps a lone ride its own badge, with counts", () => {
- // Zoom 7: Freiburg and the Kaiserstuhl (~20 km) share a neighborhood of ~60 px cells;
- // Innsbruck (~280 km away) cannot.
- const clusters = clusterRides([FREIBURG_A, FREIBURG_B, KAISERSTUHL, INNSBRUCK], 7);
- expect(clusters).toHaveLength(2);
- const [black_forest, alps] = clusters;
- expect(black_forest.keys).toEqual(["a", "b", "c"]);
- expect(black_forest.count).toBe(3);
- expect(alps.keys).toEqual(["d"]);
- expect(alps.count).toBe(1);
- });
-
- it("separates the same rides as the zoom grows — the grid is the threshold behavior", () => {
- // At zoom 9 the Kaiserstuhl ride (~15 km from Freiburg) gets its own badge…
- const mid = clusterRides([FREIBURG_A, FREIBURG_B, KAISERSTUHL], 9);
- expect(mid.map((c) => [...c.keys].sort().join(""))).toEqual(["ab", "c"]);
- // …and at zoom 13 every ride stands alone.
- const close = clusterRides([FREIBURG_A, FREIBURG_B, KAISERSTUHL], 13);
- expect(close).toHaveLength(3);
- expect(close.every((c) => c.count === 1)).toBe(true);
- });
-
- it("merges rides in adjacent cells into one badge", () => {
- // Two representative points straddling a cell edge: same cluster, even though their cells
- // differ — a badge pair two pixels apart would be the bug this rule exists for.
- const zoom = 8;
- const cell = 60;
- const [ax] = projectPx(48.0, 7.85, zoom);
- expect(Math.floor(ax / cell)).not.toBe(Math.floor((ax + cell) / cell));
- // Build a second ride whose midpoint lands one cell to the east.
- const scale = 256 * 2 ** zoom;
- const lonShift = ((cell * 1.001) / scale) * 360;
- const neighbour = trackAround(48.0, 7.85 + lonShift, "n");
- const clusters = clusterRides([trackAround(48.0, 7.85, "m"), neighbour], zoom, cell);
- expect(clusters).toHaveLength(1);
- expect(clusters[0].keys).toEqual(["m", "n"]);
- });
-
- it("centers a badge between its members and bounds it around every member point", () => {
- const clusters = clusterRides([FREIBURG_A, FREIBURG_B], 7);
- expect(clusters).toHaveLength(1);
- const { center, bounds } = clusters[0];
- const reps = [representativePoint(FREIBURG_A.track)!, representativePoint(FREIBURG_B.track)!];
- expect(center[0]).toBeCloseTo((reps[0][0] + reps[1][0]) / 2, 10);
- expect(center[1]).toBeCloseTo((reps[0][1] + reps[1][1]) / 2, 10);
- // The click-to-zoom bounds cover every point of every member track.
- const [[south, west], [north, east]] = bounds;
- for (const ride of [FREIBURG_A, FREIBURG_B]) {
- for (const [lat, lon] of ride.track) {
- expect(lat).toBeGreaterThanOrEqual(south);
- expect(lat).toBeLessThanOrEqual(north);
- expect(lon).toBeGreaterThanOrEqual(west);
- expect(lon).toBeLessThanOrEqual(east);
- }
- }
- });
-
- it("skips rides with no track and answers an empty library with no clusters", () => {
- expect(clusterRides([], 7)).toEqual([]);
- expect(clusterRides([{ key: "x", track: [] }], 7)).toEqual([]);
- const clusters = clusterRides([{ key: "x", track: [] }, FREIBURG_A], 7);
- expect(clusters).toHaveLength(1);
- expect(clusters[0].keys).toEqual(["a"]);
- });
-
- it("projects north up and east right, like the map it feeds", () => {
- const [x1, y1] = projectPx(48, 7, 7);
- const [x2, y2] = projectPx(49, 8, 7);
- expect(x2).toBeGreaterThan(x1);
- expect(y2).toBeLessThan(y1); // pixel y grows southwards
- // The poles clamp instead of diverging.
- expect(Number.isFinite(projectPx(90, 0, 7)[1])).toBe(true);
- });
-});
diff --git a/builder/web/src/lib/device/rideMap.ts b/builder/web/src/lib/device/rideMap.ts
deleted file mode 100644
index a4f631095a..0000000000
--- a/builder/web/src/lib/device/rideMap.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-/**
- * The logbook map's clustering: pure math, no Leaflet.
- *
- * Zoomed out, the all-rides map draws forest circles with counts, one per area, and a click zooms
- * into that area. Zoomed in past {@link CLUSTER_BELOW_ZOOM}, the circles dissolve into the actual
- * tracks. The two never show at once.
- *
- * The grouping is a **grid cluster in projected pixel space**: each ride is reduced to one
- * representative point — the track's midpoint, a better "where was this" than its start, which for
- * loops is the rider's front door — projected to Web-Mercator pixels at the current zoom, and binned
- * into ~{@link DEFAULT_CELL_PX}-pixel cells. Occupied cells that touch merge into one cluster, so a
- * group of rides straddling a cell edge reads as one badge. Because the projection scales with zoom,
- * the same rides separate into more clusters as the map zooms in.
- *
- * Everything here is a pure function over `[lat, lon]` arrays, so the behaviour can be pinned
- * without a DOM or a tile server.
- */
-
-/** One ride as the map needs it: its key (for hover/click identity) and its preview track. */
-export interface RideTrack {
- readonly key: string;
- readonly track: readonly (readonly [number, number])[];
-}
-
-/** One badge on the zoomed-out map. */
-export interface RideCluster {
- /** The member rides' keys, in input order. */
- readonly keys: readonly string[];
- readonly count: number;
- /** Where the badge sits: the mean of the members' representative points, `[lat, lon]`. */
- readonly center: readonly [number, number];
- /**
- * `[[south, west], [north, east]]` over **every point of every member track** — what a click
- * on the badge zooms to, so the whole rides come into view, not just their midpoints.
- */
- readonly bounds: readonly [readonly [number, number], readonly [number, number]];
-}
-
-/** Below this Leaflet zoom the map shows clusters; at or above it, the tracks themselves. */
-export const CLUSTER_BELOW_ZOOM = 10;
-
-/** A chosen ~60 px cell: two badges can get no closer than a badge's own diameter. */
-export const DEFAULT_CELL_PX = 60;
-
-/** Whether `zoom` is in cluster territory. The component's one branch. */
-export function clustersAt(zoom: number): boolean {
- return zoom < CLUSTER_BELOW_ZOOM;
-}
-
-/** A ride's one point for clustering: the track's midpoint (by index). `null` for an empty track. */
-export function representativePoint(
- track: readonly (readonly [number, number])[],
-): readonly [number, number] | null {
- if (track.length === 0) return null;
- return track[Math.floor(track.length / 2)];
-}
-
-/** Web-Mercator's latitude limit; beyond it the projection diverges. */
-const MAX_LAT = 85.05112878;
-
-/**
- * `[lat, lon]` → Web-Mercator pixels at `zoom` (256 px tiles, Leaflet's own convention). Exported
- * for the tests, which assert cell membership in the same space the clustering bins in.
- */
-export function projectPx(lat: number, lon: number, zoom: number): [number, number] {
- const scale = 256 * 2 ** zoom;
- const clamped = Math.max(-MAX_LAT, Math.min(MAX_LAT, lat));
- const s = Math.sin((clamped * Math.PI) / 180);
- return [
- ((lon + 180) / 360) * scale,
- (0.5 - Math.log((1 + s) / (1 - s)) / (4 * Math.PI)) * scale,
- ];
-}
-
-/**
- * Group rides into clusters for one zoom level.
- *
- * Rides with empty tracks are skipped — there is nothing to place. The result is deterministic:
- * clusters come out ordered by their first member's input position, members in input order.
- */
-export function clusterRides(
- rides: readonly RideTrack[],
- zoom: number,
- cellPx: number = DEFAULT_CELL_PX,
-): RideCluster[] {
- interface Placed {
- readonly ride: RideTrack;
- readonly rep: readonly [number, number];
- readonly cx: number;
- readonly cy: number;
- }
- const placed: Placed[] = [];
- for (const ride of rides) {
- const rep = representativePoint(ride.track);
- if (!rep) continue;
- const [x, y] = projectPx(rep[0], rep[1], zoom);
- placed.push({ ride, rep, cx: Math.floor(x / cellPx), cy: Math.floor(y / cellPx) });
- }
- if (placed.length === 0) return [];
-
- // Union occupied cells that touch (8-neighborhood), BFS over the occupancy map.
- const byCell = new Map();
- for (const p of placed) {
- const id = `${p.cx}:${p.cy}`;
- const cell = byCell.get(id);
- if (cell) cell.push(p);
- else byCell.set(id, [p]);
- }
- const seen = new Set();
- const clusters: RideCluster[] = [];
- for (const p of placed) {
- const startId = `${p.cx}:${p.cy}`;
- if (seen.has(startId)) continue;
- const members: Placed[] = [];
- const queue = [startId];
- seen.add(startId);
- while (queue.length > 0) {
- const id = queue.pop()!;
- const cell = byCell.get(id)!;
- members.push(...cell);
- const [cx, cy] = id.split(":").map(Number);
- for (let dx = -1; dx <= 1; dx++) {
- for (let dy = -1; dy <= 1; dy++) {
- const next = `${cx + dx}:${cy + dy}`;
- if ((dx !== 0 || dy !== 0) && byCell.has(next) && !seen.has(next)) {
- seen.add(next);
- queue.push(next);
- }
- }
- }
- }
- // Input order inside the cluster, so the result never depends on Map iteration details.
- members.sort((a, b) => placed.indexOf(a) - placed.indexOf(b));
- clusters.push(toCluster(members.map((m) => ({ ride: m.ride, rep: m.rep }))));
- }
- return clusters;
-}
-
-/**
- * Known limit: a track crossing the antimeridian makes its cluster's bounds span most of the world,
- * so a badge click zooms way out instead of in. Left as-is deliberately — unwrapping longitudes is
- * real complexity for a case a bikepacking track effectively never hits, and the failure is a wrong
- * zoom, not a lost ride.
- */
-function toCluster(members: ReadonlyArray<{ ride: RideTrack; rep: readonly [number, number] }>): RideCluster {
- let south = Infinity;
- let west = Infinity;
- let north = -Infinity;
- let east = -Infinity;
- let latSum = 0;
- let lonSum = 0;
- for (const { ride, rep } of members) {
- latSum += rep[0];
- lonSum += rep[1];
- for (const [lat, lon] of ride.track) {
- if (lat < south) south = lat;
- if (lat > north) north = lat;
- if (lon < west) west = lon;
- if (lon > east) east = lon;
- }
- }
- return {
- keys: members.map((m) => m.ride.key),
- count: members.length,
- center: [latSum / members.length, lonSum / members.length],
- bounds: [
- [south, west],
- [north, east],
- ],
- };
-}
diff --git a/builder/web/src/lib/device/rides.ts b/builder/web/src/lib/device/rides.ts
index 0491877cda..b11a65977c 100644
--- a/builder/web/src/lib/device/rides.ts
+++ b/builder/web/src/lib/device/rides.ts
@@ -2,7 +2,7 @@
* Pulling a recorded ride off the device and handing it to the browser as a GPX.
*
* This is the hosted tier's **only** ride feature, and it is deliberately a dead end: a file lands
- * in a Downloads folder and nothing else happens anywhere. The managed library is the desktop app's.
+ * in a Downloads folder and nothing else happens anywhere.
*
* {@link RideSource} holds exactly two reads: list the catalog, download one ride. There is no
* delete and no arm — not as discipline, but because the object {@link rideAccess} hands over does
@@ -98,7 +98,7 @@ export function scopeKey(scope: RideScope): string {
return `${scope.serial}:${scope.storeId ?? "no-store"}`;
}
-/** Shared with the desktop index: full StoreId hex and decimal u64 ObjectId. */
+/** The key of a ride in one scope: full StoreId hex and decimal u64 ObjectId. */
export function rideKey(scope: RideScope, objectId: bigint): string {
return `${scopeKey(scope)}:${objectId}`;
}
diff --git a/builder/web/src/lib/device/segments.test.ts b/builder/web/src/lib/device/segments.test.ts
deleted file mode 100644
index 9c7a61bb29..0000000000
--- a/builder/web/src/lib/device/segments.test.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { cumulativeDistances, type ProfilePoint } from "./elevation";
-import { concatSegments, waypointDistanceM } from "./segments";
-
-/** Points ~1.11 km apart along a meridian — a near-uniform axis, like elevation.test.ts's ladder. */
-const meridian = (fromLat: number, count: number, lon = 7.82): ProfilePoint[] =>
- Array.from({ length: count }, (_, i) => ({ lat: fromLat + i * 0.01, lon, ele: 100 + i }));
-
-/** One 0.01°-of-latitude step in metres, per the module's own metric. */
-const STEP = cumulativeDistances(meridian(48, 2))[1];
-
-describe("concatSegments", () => {
- it("concatenates points in order onto one cumulative axis", () => {
- // Two contiguous stages: the second starts exactly where the first ends.
- const a = meridian(48.0, 3); // 48.00 .. 48.02
- const b = meridian(48.02, 4); // 48.02 .. 48.05
- const axis = concatSegments([a, b]);
- expect(axis.points.length).toBe(7);
- expect(axis.cum).toEqual(cumulativeDistances([...a, ...b]));
- expect(axis.totalM).toBeCloseTo(5 * STEP, 6);
- expect(axis.ranges).toEqual([
- [0, 2],
- [3, 6],
- ]);
- });
-
- it("gives each stage its offset and drawn length, and marks the seam", () => {
- const a = meridian(48.0, 3); // 2 steps long
- const b = meridian(48.02, 4); // 3 steps long
- const axis = concatSegments([a, b]);
- expect(axis.offsetsM[0]).toBe(0);
- expect(axis.lengthsM[0]).toBeCloseTo(2 * STEP, 6);
- // The seam jump is zero here (contiguous stages), so b starts at a's end.
- expect(axis.offsetsM[1]).toBeCloseTo(2 * STEP, 6);
- expect(axis.lengthsM[1]).toBeCloseTo(3 * STEP, 6);
- expect(axis.boundariesM.length).toBe(1);
- expect(axis.boundariesM[0]).toBeCloseTo(2 * STEP, 6);
- });
-
- it("keeps a gap between non-contiguous stages on the axis but out of the stage lengths", () => {
- const a = meridian(48.0, 2); // ends at 48.01
- const b = meridian(48.03, 2); // starts 2 steps later
- const axis = concatSegments([a, b]);
- // The axis walks the jump; the second stage's own length is still one step.
- expect(axis.totalM).toBeCloseTo(4 * STEP, 6);
- expect(axis.offsetsM[1]).toBeCloseTo(3 * STEP, 6);
- expect(axis.lengthsM[1]).toBeCloseTo(1 * STEP, 6);
- expect(axis.boundariesM[0]).toBeCloseTo(3 * STEP, 6);
- });
-
- it("tolerates empty segments without ranges or boundaries", () => {
- const a = meridian(48.0, 3);
- const axis = concatSegments([[], a, []]);
- expect(axis.ranges).toEqual([null, [0, 2], null]);
- expect(axis.offsetsM).toEqual([0, 0, axis.totalM]);
- expect(axis.lengthsM[0]).toBe(0);
- expect(axis.lengthsM[2]).toBe(0);
- expect(axis.boundariesM).toEqual([]);
- });
-
- it("a single segment is the plain track: no boundaries, full range", () => {
- const a = meridian(48.0, 4);
- const axis = concatSegments([a]);
- expect(axis.ranges).toEqual([[0, 3]]);
- expect(axis.offsetsM).toEqual([0]);
- expect(axis.lengthsM[0]).toBeCloseTo(axis.totalM, 9);
- expect(axis.boundariesM).toEqual([]);
- expect(axis.cum).toEqual(cumulativeDistances(a));
- });
-
- it("degenerates safely on nothing at all", () => {
- const axis = concatSegments([]);
- expect(axis.points).toEqual([]);
- expect(axis.totalM).toBe(0);
- expect(axis.boundariesM).toEqual([]);
- });
-});
-
-describe("waypointDistanceM", () => {
- const axis = concatSegments([meridian(48.0, 3), meridian(48.02, 4)]);
-
- it("offsets a stage waypoint by everything before its stage", () => {
- expect(waypointDistanceM(axis, 0, 0)).toBe(0);
- expect(waypointDistanceM(axis, 1, 0)).toBeCloseTo(axis.offsetsM[1], 9);
- expect(waypointDistanceM(axis, 1, STEP)).toBeCloseTo(axis.offsetsM[1] + STEP, 6);
- });
-
- it("clamps into the stage's drawn span — a raw-track overshoot lands on the stage's end", () => {
- expect(waypointDistanceM(axis, 0, 99_999)).toBeCloseTo(axis.lengthsM[0], 6);
- expect(waypointDistanceM(axis, 0, -5)).toBe(0);
- expect(waypointDistanceM(axis, 1, 99_999)).toBeCloseTo(axis.totalM, 6);
- });
-
- it("passes the raw distance through on a degenerate axis", () => {
- expect(waypointDistanceM(concatSegments([]), 0, 1234)).toBe(1234);
- });
-});
diff --git a/builder/web/src/lib/device/segments.ts b/builder/web/src/lib/device/segments.ts
deleted file mode 100644
index ea74469e1e..0000000000
--- a/builder/web/src/lib/device/segments.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-/**
- * The trip preview's shared distance axis: several stage tracks, concatenated in trip order into the
- * one polyline the chart-room modal already knows how to window, hover and zoom, plus the
- * bookkeeping that keeps each stage addressable on that axis.
- *
- * Pure geometry, like `elevation.ts`: the modal derives everything else from this one result.
- *
- * The axis is `cumulativeDistances` over the **concatenated** points, so the straight-line jump
- * between one stage's end and the next stage's start is part of the axis, exactly as it would be had
- * the stages been one recorded track.
- *
- * Deliberate tradeoff for a *discontinuous* trip: the map marks the jump with a thin dashed
- * connector, so the hover dot visibly travels a transfer leg, but the elevation profile still draws
- * one straight interpolated ramp across the jump's span. Masking that ramp would mean splitting the
- * profile's SVG path per stage, and the seam rules already say where the stages meet.
- */
-
-import type { RouteWaypoint } from "../convert/bridge";
-import { cumulativeDistances, type ProfilePoint } from "./elevation";
-
-/** One stage of a trip as the preview draws it: the decoded track, the stage's band color, and
- * the stage's own waypoints (distances measured from *its* start — see {@link waypointDistanceM}). */
-export interface TrackSegment {
- readonly name: string;
- /** The stage color — the same palette entry the trip band's dot uses. */
- readonly color: string;
- readonly points: readonly ProfilePoint[];
- readonly waypoints: readonly RouteWaypoint[];
-}
-
-/** The concatenated axis and each segment's place on it. All distances metres, all on the drawn
- * (post-decimation) polyline. */
-export interface SegmentAxis {
- /** Every segment's points, in order — the one track the modal windows and hovers. */
- readonly points: ProfilePoint[];
- /** `cumulativeDistances(points)` — computed once here, shared by every consumer. */
- readonly cum: number[];
- /** The whole axis's length. */
- readonly totalM: number;
- /** Per segment: its `[first, last]` point indices in {@link points}, or null for a segment
- * that brought no points. */
- readonly ranges: ReadonlyArray;
- /** Per segment: the axis distance at its first point (for an empty segment: where it would
- * have started). `offsetsM[0] === 0`. */
- readonly offsetsM: number[];
- /** Per segment: the drawn length of its own track — `cum[last] - cum[first]`, 0 if empty. */
- readonly lengthsM: number[];
- /** The seams between consecutive non-empty segments — the axis distance where a later
- * segment begins. One entry per internal boundary; empty for 0 or 1 drawable segments. */
- readonly boundariesM: number[];
-}
-
-/** Concatenate stage tracks into one shared axis. */
-export function concatSegments(segments: ReadonlyArray): SegmentAxis {
- const points: ProfilePoint[] = [];
- const spans: Array = [];
- for (const segment of segments) {
- if (segment.length === 0) {
- spans.push(null);
- continue;
- }
- const first = points.length;
- points.push(...segment);
- spans.push([first, points.length - 1]);
- }
- const cum = cumulativeDistances(points);
- const totalM = cum.length ? cum[cum.length - 1] : 0;
-
- const offsetsM: number[] = [];
- const lengthsM: number[] = [];
- const boundariesM: number[] = [];
- let cursorM = 0;
- let drawnBefore = false;
- for (const span of spans) {
- if (span === null) {
- offsetsM.push(cursorM);
- lengthsM.push(0);
- continue;
- }
- const [first, last] = span;
- offsetsM.push(cum[first]);
- lengthsM.push(cum[last] - cum[first]);
- if (drawnBefore) boundariesM.push(cum[first]);
- drawnBefore = true;
- cursorM = cum[last];
- }
- return { points, cum, totalM, ranges: spans, offsetsM, lengthsM, boundariesM };
-}
-
-/**
- * A stage waypoint's position on the shared axis: its stored `distAlongM` — measured from the
- * stage's own start on the RAW pre-decimation track, so it can slightly exceed the drawn stage's
- * length — clamped into the stage's drawn span, then offset by everything before the stage.
- *
- * On a degenerate axis the raw value is passed through: there is no span to clamp into, and the
- * caption should say what was stored rather than 0.
- */
-export function waypointDistanceM(axis: SegmentAxis, segment: number, distAlongM: number): number {
- if (axis.totalM <= 0) return distAlongM;
- const clamped = Math.max(0, Math.min(distAlongM, axis.lengthsM[segment] ?? 0));
- return (axis.offsetsM[segment] ?? 0) + clamped;
-}
diff --git a/builder/web/src/lib/device/session.svelte.ts b/builder/web/src/lib/device/session.svelte.ts
index b65151c137..c84207a044 100644
--- a/builder/web/src/lib/device/session.svelte.ts
+++ b/builder/web/src/lib/device/session.svelte.ts
@@ -11,7 +11,6 @@
* a click, is what shows the chooser the first time. Neither can substitute for the other.
*/
-import { platform } from "../platform";
import type { DeviceSession } from "../usb/session";
/** Reactive holder for the shared session. */
@@ -47,18 +46,18 @@ class DeviceHolder {
private opening: Promise | null = null;
- /** Open the host's device session, at most once per page. Safe to call from several components' `onMount`. */
+ /** Open the device session, at most once per page. Safe to call from several components' `onMount`. */
open(): Promise {
- this.opening ??= this.start(platform.device);
+ this.opening ??= this.start();
return this.opening;
}
- private async start(openDevice: (() => Promise) | null): Promise {
- // Null on a tier without USB at all. The UI never reaches here in that case — `` has
- // already replaced the control — so this is a guard, not a branch anyone renders.
- if (!openDevice) return null;
+ private async start(): Promise {
try {
- const session = await openDevice();
+ // Dynamic, so the transport, the protocol codecs and the client stay in their own chunk:
+ // a visitor who only downloads a map never loads the device code.
+ const { openDeviceSession } = await import("../usb/session.svelte");
+ const session = await openDeviceSession();
this.session = session;
return session;
} catch (cause) {
diff --git a/builder/web/src/lib/device/thumbs.svelte.ts b/builder/web/src/lib/device/thumbs.svelte.ts
deleted file mode 100644
index 2eb884aa85..0000000000
--- a/builder/web/src/lib/device/thumbs.svelte.ts
+++ /dev/null
@@ -1,309 +0,0 @@
-/**
- * Track thumbnails for the device page's tiles: one downsampled `[lat, lon]` track per route and
- * ride on the card. The hosted web app holds them for the current page session; the installed
- * desktop app keeps a bounded local cache so reconnecting a device does not download every object
- * again after each restart.
- *
- * Cache keys carry the device scope and an object fingerprint, so changed routes are never shown
- * with an old track. Entries without a stable fingerprint remain session-only on every host.
- *
- * `fill` walks the dashboard's lists sequentially. Every load runs through the page's `enqueue`,
- * FIFO with whatever the rider clicks, because the cable has one transfer slot and thumbnails are
- * the least important work on it. What is held is points, not pixels.
- */
-
-import { SvelteMap } from "svelte/reactivity";
-
-import { platform, type PlatformName } from "../platform";
-import { downsampleTrack, round6 } from "./library";
-import { scopeKey, type RideScope } from "./rides";
-
-/** A downsampled `[lat, lon]` polyline, ready for `fitTracks`. */
-export type Thumb = ReadonlyArray;
-
-export type ThumbKind = "route" | "ride";
-
-/** The stage colors of a trip's combined preview, cycled — the field-guide palette. */
-export const STAGE_COLORS = ["#3c6b39", "#cf6a2a", "#33575b", "#e3ad33", "#5f7d3d"] as const;
-
-const PREFIX = "obc-thumb:v1:";
-
-/** A chosen cap: about 1.5 MiB at the usual track size. Older entries go least-recently-used first. */
-export const THUMB_CACHE_CAP = 300;
-
-/** The small persistent-storage seam, injectable for tests. */
-export interface ThumbStorage {
- get(key: string): string | null;
- set(key: string, value: string): void;
- remove(key: string): void;
- keys(): string[];
-}
-
-/**
- * A catalog entry's content identity, for the cache key.
- *
- * One function for every kind, because a committed object's payload never changes under one
- * revision: the payload's CRC names exactly those bytes, and a replace publishes a new revision with
- * a new CRC, which is what makes a stale thumbnail impossible.
- *
- * `null` where the device declared no CRC — a ride it is still recording — which keeps that entry
- * out of the durable cache rather than caching a thumbnail of a payload that is still growing.
- */
-export function entryFingerprint(entry: { readonly payloadCrc32: number }): string | null {
- return entry.payloadCrc32 !== 0 ? `c${entry.payloadCrc32 >>> 0}` : null;
-}
-
-export function thumbKey(scope: RideScope, kind: ThumbKind, id: bigint, fingerprint: string): string {
- return `${PREFIX}${scopeKey(scope)}:${kind}:${id}:${fingerprint}`;
-}
-
-interface StoredThumb {
- at: number;
- track: Array<[number, number]>;
-}
-
-const QUOTA_HEADROOM = 25;
-
-/** Bounded, defensive LRU storage. A corrupt or unavailable entry is simply downloaded again. */
-export class ThumbCache {
- constructor(
- private readonly storage: ThumbStorage,
- private readonly cap: number = THUMB_CACHE_CAP,
- private readonly now: () => number = Date.now,
- ) {}
-
- get(key: string): Thumb | null {
- const raw = this.storage.get(key);
- if (raw === null) return null;
- const parsed = parseStored(raw);
- if (parsed === null) {
- this.storage.remove(key);
- return null;
- }
- this.write(key, { at: this.now(), track: parsed.track });
- return parsed.track;
- }
-
- put(key: string, track: Thumb): void {
- this.write(key, {
- at: this.now(),
- track: track.map((point) => [round6(point[0]), round6(point[1])]),
- });
- this.evict(this.cap);
- }
-
- clear(): number {
- let removed = 0;
- for (const key of this.storage.keys()) {
- if (!key.startsWith(PREFIX)) continue;
- this.storage.remove(key);
- removed += 1;
- }
- return removed;
- }
-
- private write(key: string, stored: StoredThumb): void {
- const value = JSON.stringify(stored);
- try {
- this.storage.set(key, value);
- } catch {
- this.evict(Math.max(0, this.cap - QUOTA_HEADROOM));
- try {
- this.storage.set(key, value);
- } catch {
- // A full or denied store removes the optimization, not the feature.
- }
- }
- }
-
- private evict(keep: number): void {
- const entries: Array<{ key: string; at: number }> = [];
- for (const key of this.storage.keys()) {
- if (!key.startsWith(PREFIX)) continue;
- const parsed = parseStored(this.storage.get(key) ?? "");
- if (parsed === null) {
- this.storage.remove(key);
- } else {
- entries.push({ key, at: parsed.at });
- }
- }
- if (entries.length <= keep) return;
- entries.sort((a, b) => a.at - b.at);
- for (const entry of entries.slice(0, entries.length - keep)) this.storage.remove(entry.key);
- }
-}
-
-function parseStored(raw: string): StoredThumb | null {
- let value: unknown;
- try {
- value = JSON.parse(raw);
- } catch {
- return null;
- }
- if (typeof value !== "object" || value === null) return null;
- const { at, track } = value as { at?: unknown; track?: unknown };
- if (typeof at !== "number" || !Number.isFinite(at) || !Array.isArray(track)) return null;
- for (const point of track) {
- if (
- !Array.isArray(point) ||
- point.length !== 2 ||
- typeof point[0] !== "number" ||
- typeof point[1] !== "number" ||
- !Number.isFinite(point[0]) ||
- !Number.isFinite(point[1])
- ) {
- return null;
- }
- }
- return { at, track: track as Array<[number, number]> };
-}
-
-/** One thumbnail the page wants and how to fetch its full-resolution points. */
-export interface ThumbRequest {
- readonly kind: ThumbKind;
- readonly id: bigint;
- /** Stable content identity. Without one, persistence is intentionally skipped. */
- readonly fingerprint: string | null;
- /** A cable download for most objects, or the ride library's held preview for a pulled ride. */
- readonly load: (signal: AbortSignal) => Promise;
-}
-
-/** Run one operation behind every previously queued one — the dashboard's `enqueue`, in practice. */
-export type ThumbQueue = (op: () => Promise) => Promise;
-
-export class DeviceThumbs {
- /** What the tiles read, keyed `kind:id` within the current scope. */
- private readonly tracks = new SvelteMap();
- private readonly cache: ThumbCache | null;
- private scope: string | null = null;
-
- constructor(storage: ThumbStorage | null = null) {
- this.cache = storage ? new ThumbCache(storage) : null;
- }
-
- /** The track for a tile, or null while it is still on its way. Reactive. */
- get(kind: ThumbKind, id: bigint): Thumb | null {
- return this.tracks.get(memKey(kind, id))?.track ?? null;
- }
-
- /** Forget the map when `(serial, StoreId)` changes; ids are recycled across device scopes. */
- ensureScope(scope: RideScope): void {
- const key = scopeKey(scope);
- if (this.scope === key) return;
- this.scope = key;
- this.tracks.clear();
- }
-
- /**
- * One thumbnail: memory, then the loader. The load runs through `queue`, so it cannot race a
- * user action on the single transfer slot.
- *
- * A completion that crossed an abort or scope change is dropped: device A's route 1 must never
- * land on device B's route 1 tile.
- */
- async ensure(scope: RideScope, request: ThumbRequest, queue: ThumbQueue, signal: AbortSignal): Promise {
- this.ensureScope(scope);
- const started = this.scope;
- const key = memKey(request.kind, request.id);
- const held = this.tracks.get(key);
- if (held?.fingerprint === request.fingerprint) return held.track;
- const storageKey =
- request.fingerprint === null ? null : thumbKey(scope, request.kind, request.id, request.fingerprint);
- const stored = storageKey === null ? null : (this.cache?.get(storageKey) ?? null);
- if (stored) {
- this.tracks.set(key, { fingerprint: request.fingerprint, track: stored });
- return stored;
- }
- const track = await queue(async () => {
- // A preview click and the background fill can both ask for the same object while one is
- // queued. Recheck after entering the slot so the second request reuses the first.
- const landed = this.scope === started ? this.tracks.get(key) : null;
- if (landed?.fingerprint === request.fingerprint) return landed.track;
- return downsampleTrack(await request.load(signal));
- });
- if (!signal.aborted && this.scope === started) {
- if (storageKey !== null) this.cache?.put(storageKey, track);
- this.tracks.set(key, { fingerprint: request.fingerprint, track });
- }
- return track;
- }
-
- /** Delete durable previews. Current on-screen previews stay in memory until the app closes. */
- clearPersistent(): number {
- return this.cache?.clear() ?? 0;
- }
-
- /** Fill every missing thumbnail one at a time. A failed load is skipped; abort ends the walk. */
- async fill(
- scope: RideScope,
- requests: readonly ThumbRequest[],
- queue: ThumbQueue,
- signal: AbortSignal,
- ): Promise {
- for (const request of requests) {
- if (signal.aborted) return;
- try {
- await this.ensure(scope, request, queue, signal);
- } catch {
- if (signal.aborted) return;
- }
- }
- }
-}
-
-function memKey(kind: ThumbKind, id: bigint): string {
- return `${kind}:${id}`;
-}
-
-/** `localStorage` behind the seam, when the host permits it. */
-function browserStorage(): ThumbStorage | null {
- try {
- const storage = globalThis.localStorage;
- storage.getItem(`${PREFIX}probe`);
- return {
- get: (key) => storage.getItem(key),
- set: (key, value) => storage.setItem(key, value),
- remove: (key) => storage.removeItem(key),
- keys: () => {
- const keys: string[] = [];
- for (let i = 0; i < storage.length; i++) {
- const key = storage.key(i);
- if (key !== null) keys.push(key);
- }
- return keys;
- },
- };
- } catch {
- return null;
- }
-}
-
-/** A Map wearing the storage interface, used by tests and harmless fallbacks. */
-export function memoryStorage(): ThumbStorage {
- const map = new Map();
- return {
- get: (key) => map.get(key) ?? null,
- set: (key, value) => void map.set(key, value),
- remove: (key) => void map.delete(key),
- keys: () => [...map.keys()],
- };
-}
-
-/** Pure policy seam: only the installed desktop build receives durable thumbnail storage. */
-export function thumbnailStorageFor(host: PlatformName, storage: ThumbStorage | null): ThumbStorage | null {
- return host === "desktop" ? storage : null;
-}
-
-/** Remove old web entries while preserving the desktop cache. */
-function purgeWebThumbs(storage: ThumbStorage | null): void {
- if (platform.name === "desktop" || storage === null) return;
- for (const key of storage.keys()) {
- if (key.startsWith(PREFIX)) storage.remove(key);
- }
-}
-
-const hostStorage = browserStorage();
-purgeWebThumbs(hostStorage);
-
-/** Shared session store; durable backing exists in the installed desktop build only. */
-export const deviceThumbs = new DeviceThumbs(thumbnailStorageFor(platform.name, hostStorage));
diff --git a/builder/web/src/lib/device/thumbs.test.ts b/builder/web/src/lib/device/thumbs.test.ts
deleted file mode 100644
index 3b83c99895..0000000000
--- a/builder/web/src/lib/device/thumbs.test.ts
+++ /dev/null
@@ -1,314 +0,0 @@
-/** The host-specific thumbnail store, with device I/O represented by loader functions. */
-
-import { describe, expect, it } from "vitest";
-
-import { PREVIEW_POINTS } from "./library";
-import type { RideScope } from "./rides";
-import {
- DeviceThumbs,
- ThumbCache,
- memoryStorage,
- entryFingerprint,
- thumbKey,
- thumbnailStorageFor,
- type Thumb,
- type ThumbRequest,
- type ThumbStorage,
-} from "./thumbs.svelte";
-
-const SCOPE: RideScope = { serial: "OBC-0042", storeId: "00000000000000000000000000000007" };
-const TRACK: Thumb = [
- [47.9950001234, 7.8420009876],
- [47.996, 7.843],
- [47.997, 7.844],
-];
-
-const request = (id: number, load: ThumbRequest["load"]): ThumbRequest => ({
- kind: "route",
- id: BigInt(id),
- fingerprint: `c${id}`,
- load,
-});
-
-function recordedStorage(): { storage: ThumbStorage; map: Map } {
- const map = new Map();
- return {
- map,
- storage: {
- get: (key) => map.get(key) ?? null,
- set: (key, value) => void map.set(key, value),
- remove: (key) => void map.delete(key),
- keys: () => [...map.keys()],
- },
- };
-}
-
-function ticker(): { now: () => number; tick: () => void } {
- let value = 1_000;
- return { now: () => value, tick: () => void (value += 1) };
-}
-
-describe("thumb keys", () => {
- it("carry device scope, kind, id and fingerprint", () => {
- const key = thumbKey(SCOPE, "route", 12n, "c123");
- expect(key).toContain("OBC-0042");
- expect(thumbKey(SCOPE, "ride", 9007199254740992n, "c123")).not.toBe(
- thumbKey(SCOPE, "ride", 9007199254740993n, "c123"),
- );
- expect(key).toContain(":00000000000000000000000000000007:route:12:c123");
- expect(thumbKey({ ...SCOPE, storeId: "00000000000000000000000000000008" }, "route", 12n, "c123")).not.toBe(key);
- });
-
- it("uses the route CRC and does not invent a missing fingerprint", () => {
- expect(entryFingerprint({ payloadCrc32: 0xdeadbeef })).toBe(`c${0xdeadbeef}`);
- // A ride the device is still recording declares a zero CRC, and a null fingerprint is
- // what keeps its half-written payload out of the durable cache.
- expect(entryFingerprint({ payloadCrc32: 0 })).toBeNull();
- });
-
- it("fingerprints an immutable ride by start time and length", () => {
- expect(entryFingerprint({ payloadCrc32: 4_242 })).toBe("c4242");
- });
-});
-
-describe("ThumbCache", () => {
- it("round-trips a track and rounds coordinates to six decimals", () => {
- const cache = new ThumbCache(recordedStorage().storage);
- const key = thumbKey(SCOPE, "route", 1n, "c1");
- cache.put(key, TRACK);
- expect(cache.get(key)).toEqual([
- [47.995, 7.842001],
- [47.996, 7.843],
- [47.997, 7.844],
- ]);
- });
-
- it("removes corrupt entries so the caller can refetch", () => {
- const { storage, map } = recordedStorage();
- const cache = new ThumbCache(storage);
- const key = thumbKey(SCOPE, "route", 1n, "c1");
- for (const junk of ["not json", "42", `{"at":"soon","track":[]}`, `{"at":1,"track":[[1]]}`]) {
- map.set(key, junk);
- expect(cache.get(key)).toBeNull();
- expect(map.has(key)).toBe(false);
- }
- });
-
- it("evicts the least recently used entry past the cap", () => {
- const { storage, map } = recordedStorage();
- const clock = ticker();
- const cache = new ThumbCache(storage, 3, clock.now);
- const keys = [1, 2, 3, 4].map((id) => thumbKey(SCOPE, "route", BigInt(id), `c${id}`));
- for (const key of keys.slice(0, 3)) {
- cache.put(key, TRACK);
- clock.tick();
- }
- cache.get(keys[0]);
- clock.tick();
- cache.put(keys[3], TRACK);
- expect(map.has(keys[0])).toBe(true);
- expect(map.has(keys[1])).toBe(false);
- expect(map.has(keys[2])).toBe(true);
- expect(map.has(keys[3])).toBe(true);
- });
-
- it("treats storage quota failures as a missing optimization", () => {
- const { storage, map } = recordedStorage();
- const cache = new ThumbCache(
- {
- ...storage,
- set: (key, value) => {
- if (map.size >= 1 && !map.has(key)) throw new DOMException("quota");
- storage.set(key, value);
- },
- },
- 1,
- );
- expect(() => cache.put(thumbKey(SCOPE, "route", 1n, "c1"), TRACK)).not.toThrow();
- expect(() => cache.put(thumbKey(SCOPE, "route", 2n, "c2"), TRACK)).not.toThrow();
- });
-});
-
-describe("DeviceThumbs", () => {
- it("fills strictly one at a time, in order, through the queue", async () => {
- const thumbs = new DeviceThumbs();
- const order: string[] = [];
- const queue = async (op: () => Promise): Promise => {
- order.push("enter");
- const result = await op();
- order.push("leave");
- return result;
- };
- const requests = [1, 2, 3].map((id) =>
- request(id, async () => {
- order.push(`load ${id}`);
- return TRACK;
- }),
- );
- await thumbs.fill(SCOPE, requests, queue, new AbortController().signal);
- expect(order).toEqual(["enter", "load 1", "leave", "enter", "load 2", "leave", "enter", "load 3", "leave"]);
- expect(thumbs.get("route", 2n)).not.toBeNull();
- });
-
- it("reuses a track within the session but refetches after a reload", async () => {
- const first = new DeviceThumbs();
- let loads = 0;
- const load = async (): Promise => {
- loads += 1;
- return TRACK;
- };
- const queue = (op: () => Promise) => op();
- const signal = new AbortController().signal;
- await first.fill(SCOPE, [request(1, load)], queue, signal);
- await first.fill(SCOPE, [request(1, load)], queue, signal);
- expect(loads).toBe(1);
-
- // A fresh store models a reload: no device-derived coordinates survive it.
- const second = new DeviceThumbs();
- await second.fill(SCOPE, [request(1, load)], queue, signal);
- expect(loads).toBe(2);
- });
-
- it("persists across a desktop restart but never across a web reload", async () => {
- const storage = memoryStorage();
- const queue = (op: () => Promise) => op();
- const signal = new AbortController().signal;
- let loads = 0;
- const load = async (): Promise => {
- loads += 1;
- return TRACK;
- };
-
- const desktopFirst = new DeviceThumbs(thumbnailStorageFor("desktop", storage));
- await desktopFirst.fill(SCOPE, [request(1, load)], queue, signal);
- const desktopRestart = new DeviceThumbs(thumbnailStorageFor("desktop", storage));
- await desktopRestart.fill(SCOPE, [request(1, load)], queue, signal);
- expect(loads).toBe(1);
-
- const webReload = new DeviceThumbs(thumbnailStorageFor("web", storage));
- await webReload.fill(SCOPE, [request(1, load)], queue, signal);
- expect(loads).toBe(2);
- });
-
- it("refetches an edited object in the same session and after restart", async () => {
- const storage = memoryStorage();
- const thumbs = new DeviceThumbs(storage);
- const queue = (op: () => Promise) => op();
- const signal = new AbortController().signal;
- let loads = 0;
- const load = async (): Promise => {
- loads += 1;
- return TRACK;
- };
-
- await thumbs.fill(SCOPE, [request(1, load)], queue, signal);
- await thumbs.fill(SCOPE, [{ ...request(1, load), fingerprint: "c-edited" }], queue, signal);
- const restarted = new DeviceThumbs(storage);
- await restarted.fill(SCOPE, [{ ...request(1, load), fingerprint: "c-edited" }], queue, signal);
- expect(loads).toBe(2);
- });
-
- it("can delete every durable preview without touching unrelated storage", async () => {
- const map = new Map();
- const storage: ThumbStorage = {
- get: (key) => map.get(key) ?? null,
- set: (key, value) => void map.set(key, value),
- remove: (key) => void map.delete(key),
- keys: () => [...map.keys()],
- };
- map.set("unrelated", "keep");
- const thumbs = new DeviceThumbs(storage);
- await thumbs.fill(
- SCOPE,
- [request(1, async () => TRACK), request(2, async () => TRACK)],
- (op) => op(),
- new AbortController().signal,
- );
- expect(thumbs.clearPersistent()).toBe(2);
- expect(map).toEqual(new Map([["unrelated", "keep"]]));
- });
-
- it("downsamples an over-long load to the preview cap", async () => {
- const thumbs = new DeviceThumbs();
- const long: Thumb = Array.from({ length: 3 * PREVIEW_POINTS }, (_, i) => [47 + i * 1e-5, 7.8]);
- await thumbs.fill(SCOPE, [request(1, async () => long)], (op) => op(), new AbortController().signal);
- expect(thumbs.get("route", 1n)!.length).toBeLessThanOrEqual(PREVIEW_POINTS);
- });
-
- it("stops the walk on abort, and skips a failed load", async () => {
- const thumbs = new DeviceThumbs();
- const controller = new AbortController();
- const loaded: number[] = [];
- const requests = [
- request(1, async () => {
- throw new Error("cable hiccup");
- }),
- request(2, async () => {
- loaded.push(2);
- return TRACK;
- }),
- request(3, async () => {
- controller.abort();
- throw new Error("unplugged");
- }),
- request(4, async () => {
- loaded.push(4);
- return TRACK;
- }),
- ];
- await thumbs.fill(SCOPE, requests, (op) => op(), controller.signal);
- expect(loaded).toEqual([2]);
- expect(thumbs.get("route", 1n)).toBeNull();
- expect(thumbs.get("route", 4n)).toBeNull();
- });
-
- it("drops a completion that crossed an abort and scope change", async () => {
- const thumbs = new DeviceThumbs();
- const scopeB: RideScope = { serial: "OBC-0042", storeId: "00000000000000000000000000000008" };
- let resolveA: ((track: Thumb) => void) | undefined;
- const pendingA = new Promise((resolve) => (resolveA = resolve));
- const aborter = new AbortController();
-
- const fillA = thumbs.fill(SCOPE, [request(1, () => pendingA)], (op) => op(), aborter.signal);
- aborter.abort();
- thumbs.ensureScope(scopeB);
- resolveA!(TRACK);
- await fillA;
- expect(thumbs.get("route", 1n)).toBeNull();
-
- let loadsB = 0;
- await thumbs.fill(
- scopeB,
- [
- request(1, async () => {
- loadsB += 1;
- return TRACK;
- }),
- ],
- (op) => op(),
- new AbortController().signal,
- );
- expect(loadsB).toBe(1);
- expect(thumbs.get("route", 1n)).not.toBeNull();
- });
-
- it("drops a completion that crossed a plain abort", async () => {
- const thumbs = new DeviceThumbs();
- const aborter = new AbortController();
- let resolveLoad: ((track: Thumb) => void) | undefined;
- const pending = new Promise((resolve) => (resolveLoad = resolve));
- const fill = thumbs.fill(SCOPE, [request(1, () => pending)], (op) => op(), aborter.signal);
- aborter.abort();
- resolveLoad!(TRACK);
- await fill;
- expect(thumbs.get("route", 1n)).toBeNull();
- });
-
- it("forgets the in-memory map on a scope change", async () => {
- const thumbs = new DeviceThumbs();
- await thumbs.fill(SCOPE, [request(1, async () => TRACK)], (op) => op(), new AbortController().signal);
- expect(thumbs.get("route", 1n)).not.toBeNull();
- thumbs.ensureScope({ serial: "OBC-0042", storeId: "00000000000000000000000000000008" });
- expect(thumbs.get("route", 1n)).toBeNull();
- });
-});
diff --git a/builder/web/src/lib/device/tripDelete.test.ts b/builder/web/src/lib/device/tripDelete.test.ts
deleted file mode 100644
index 9b3017a27e..0000000000
--- a/builder/web/src/lib/device/tripDelete.test.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-/**
- * The delete-trip offer's rules (`tripDelete.ts`), held still: shared stages are protected,
- * unreadable stage lists degrade the offer, duplicates and dangling ids never inflate the counts.
- */
-
-import { describe, expect, it } from "vitest";
-
-import { planTripDelete, type TripStages } from "./tripDelete";
-
-const trip = (objectId: number, name: string, stages: readonly number[] | null): TripStages => ({
- objectId: BigInt(objectId),
- name,
- detail: stages === null ? null : { days: stages.map((id) => ({ route: BigInt(id) })) },
-});
-
-const routes = (...ids: number[]) => new Set(ids.map(BigInt));
-const ids = (...values: number[]) => values.map(BigInt);
-
-describe("planTripDelete", () => {
- it("offers both options with every unshared existing route deletable", () => {
- const t = trip(1, "Traverse", [2, 3, 4]);
- const plan = planTripDelete(t, [t], routes(2, 3, 4));
- expect(plan).toEqual({ offer: "both", deletable: ids(2, 3, 4), routeCount: 3, note: null });
- });
-
- it("protects a route that is also a stage of another trip, and says so", () => {
- const t = trip(1, "Traverse", [2, 3, 4, 5]);
- const other = trip(9, "Other trip", [3, 5, 77]);
- const plan = planTripDelete(t, [t, other], routes(2, 3, 4, 5, 77));
- expect(plan).toEqual({
- offer: "both",
- deletable: ids(2, 4),
- routeCount: 4,
- note: "2 of its 4 routes are also in “Other trip” and will stay.",
- });
- });
-
- it("names every trip a shared route belongs to", () => {
- const t = trip(1, "Traverse", [2, 3]);
- const a = trip(8, "Alps", [2]);
- const b = trip(9, "Baltic", [3]);
- const plan = planTripDelete(t, [t, a, b], routes(2, 3));
- expect(plan).toMatchObject({
- offer: "trip-only",
- reason: "All of its routes are also in other trips and would stay anyway.",
- });
- // With one route of three still deletable, both names appear in the note.
- const t2 = trip(1, "Traverse", [2, 3, 4]);
- const plan2 = planTripDelete(t2, [t2, a, b], routes(2, 3, 4));
- expect(plan2).toMatchObject({
- deletable: ids(4),
- note: "2 of its 3 routes are also in “Alps” and “Baltic” and will stay.",
- });
- });
-
- it("counts a duplicated stage id once", () => {
- const t = trip(1, "Loop twice", [2, 2, 3]);
- const plan = planTripDelete(t, [t], routes(2, 3));
- expect(plan).toEqual({ offer: "both", deletable: ids(2, 3), routeCount: 2, note: null });
- });
-
- it("ignores dangling stage ids — they are not routes", () => {
- const t = trip(1, "Traverse", [2, 3, 99]);
- const plan = planTripDelete(t, [t], routes(2, 3));
- expect(plan).toEqual({ offer: "both", deletable: ids(2, 3), routeCount: 2, note: null });
- });
-
- it("degrades to trip-only when another trip's stage list is unreadable", () => {
- const t = trip(1, "Traverse", [2, 3]);
- const broken = trip(9, "Mystery", null);
- expect(planTripDelete(t, [t, broken], routes(2, 3))).toEqual({
- offer: "trip-only",
- reason: "Another trip's stage list could not be read, so no routes are deleted with this one.",
- });
- });
-
- it("degrades to trip-only when this trip's own stage list is unreadable", () => {
- const t = trip(1, "Traverse", null);
- expect(planTripDelete(t, [t], routes(2, 3))).toEqual({
- offer: "trip-only",
- reason: "This trip's own stage list could not be read.",
- });
- });
-
- it("offers trip-only (no reason line) when nothing it lists is still on the device", () => {
- const t = trip(1, "Ghost tour", [98, 99]);
- expect(planTripDelete(t, [t], routes(2, 3))).toEqual({ offer: "trip-only", reason: null });
- });
-
- it("uses the singular for one protected route of one", () => {
- const t = trip(1, "Solo", [2]);
- const other = trip(9, "Other trip", [2, 3]);
- expect(planTripDelete(t, [t, other], routes(2, 3))).toMatchObject({
- offer: "trip-only",
- reason: "All of its routes are also in other trips and would stay anyway.",
- });
- const t2 = trip(1, "Pair", [2, 4]);
- expect(planTripDelete(t2, [t2, other], routes(2, 3, 4))).toMatchObject({
- note: "1 of its 2 routes is also in “Other trip” and will stay.",
- });
- });
-});
diff --git a/builder/web/src/lib/device/tripDelete.ts b/builder/web/src/lib/device/tripDelete.ts
deleted file mode 100644
index be50ad3b25..0000000000
--- a/builder/web/src/lib/device/tripDelete.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-/**
- * What deleting a trip *with its routes* may actually delete — computed up front, so the
- * confirmation can say the truth before anything happens.
- *
- * Pure bookkeeping over the dashboard's trip views, separated from the page because the rules are
- * easy to state and easy to get subtly wrong.
- *
- * The rules:
- *
- * 1. A route that is **also a stage of another trip** is never deleted with this one — the other
- * trip still points at it. Shared stages are excluded and named in the dialog's note.
- * 2. **Unreadable stage lists poison the whole offer.** If any *other* trip's `detail` is null,
- * nothing can prove a route of this trip is not shared with it, so the offer degrades to
- * "delete the trip only", with the reason. Same when this trip's own list is unreadable.
- * 3. Duplicate stage ids within the trip count once, and ids that no longer resolve to a route on
- * the device are not "routes" at all.
- */
-
-/** The slice of a `TripView` this module reads — structural, so tests need no protocol types. */
-export interface TripStages {
- readonly objectId: bigint;
- readonly name: string;
- /** The trip's days, or null when the trip object could not be read. */
- readonly detail: { readonly days: readonly { readonly route: bigint }[] } | null;
-}
-
-export type TripDeletePlan =
- | {
- /** Only "delete the trip only" is offered; `reason` (when set) says why in one line. */
- readonly offer: "trip-only";
- readonly reason: string | null;
- }
- | {
- readonly offer: "both";
- /** The route ids deleted by the second option — deduped, existing, not shared. */
- readonly deletable: readonly bigint[];
- /** The trip's unique stage ids that exist as routes — the dialog's "its N routes". */
- readonly routeCount: number;
- /** "2 of its 4 routes are also in “Other trip” and will stay" — null when none are. */
- readonly note: string | null;
- };
-
-/**
- * Decide what the delete-trip confirmation may offer for `trip`, given every trip on the card
- * (`allTrips` includes `trip` itself) and the ids of the routes that actually exist.
- */
-function routesOf(trip: TripStages): bigint[] {
- return trip.detail?.days.map((day) => day.route) ?? [];
-}
-
-export function planTripDelete(
- trip: TripStages,
- allTrips: readonly TripStages[],
- existingRouteIds: ReadonlySet,
-): TripDeletePlan {
- if (trip.detail === null) {
- return { offer: "trip-only", reason: "This trip's own stage list could not be read." };
- }
- const others = allTrips.filter((t) => t.objectId !== trip.objectId);
- if (others.some((t) => t.detail === null)) {
- return {
- offer: "trip-only",
- reason: "Another trip's stage list could not be read, so no routes are deleted with this one.",
- };
- }
-
- // Unique stage ids that are still routes on the device, in stage order.
- const routes = [...new Set(routesOf(trip))].filter((id) => existingRouteIds.has(id));
- if (routes.length === 0) return { offer: "trip-only", reason: null };
-
- // A route is shared when any other trip lists it too; remember who, for the note.
- const sharedIn = new Map();
- for (const other of others) {
- for (const id of new Set(routesOf(other))) {
- if (routes.includes(id)) sharedIn.set(id, [...(sharedIn.get(id) ?? []), other]);
- }
- }
- const deletable = routes.filter((id) => !sharedIn.has(id));
- if (deletable.length === 0) {
- return { offer: "trip-only", reason: "All of its routes are also in other trips and would stay anyway." };
- }
-
- return { offer: "both", deletable, routeCount: routes.length, note: sharedNote(routes.length, sharedIn) };
-}
-
-/**
- * The dialog's up-front sentence about the routes that stay: how many, and with whom. Only reached
- * from the "both" offer, where at least one route is shared and at least one is not.
- */
-function sharedNote(routeCount: number, sharedIn: ReadonlyMap): string | null {
- if (sharedIn.size === 0) return null;
- const names = [...new Set([...sharedIn.values()].flat().map((t) => t.name || `Trip ${t.objectId}`))];
- const listed =
- names.length === 1
- ? `“${names[0]}”`
- : `${names
- .slice(0, -1)
- .map((n) => `“${n}”`)
- .join(", ")} and “${names[names.length - 1]}”`;
- const verb = sharedIn.size === 1 ? "is" : "are";
- return `${sharedIn.size} of its ${routeCount} routes ${verb} also in ${listed} and will stay.`;
-}
diff --git a/builder/web/src/lib/firmware/release.test.ts b/builder/web/src/lib/firmware/release.test.ts
index 4a6dfdeee9..171e2b3795 100644
--- a/builder/web/src/lib/firmware/release.test.ts
+++ b/builder/web/src/lib/firmware/release.test.ts
@@ -59,8 +59,8 @@ describe("fetchFirmwareRelease", () => {
it("asks the mirror rather than GitHub", async () => {
// Not a style preference: a GitHub release asset 302s to storage that sends no CORS
- // header, so this fetch fails in a browser and in the desktop webview — the two hosts that
- // have a browser in them. The manifest is mirrored to R2 for exactly that reason.
+ // header, so this fetch fails in a browser. The manifest is mirrored to R2 for exactly that
+ // reason.
expect(FIRMWARE_MANIFEST_URL).toBe("https://updates.openbikecomputer.com/fw/manifest.json");
expect(FIRMWARE_MANIFEST_URL).not.toContain("github");
diff --git a/builder/web/src/lib/format.ts b/builder/web/src/lib/format.ts
index bfd89d05ad..ed1d5ec186 100644
--- a/builder/web/src/lib/format.ts
+++ b/builder/web/src/lib/format.ts
@@ -2,6 +2,7 @@
* size on every tier, and importing it from the dev host's job tracker would
* drag SSE polling into bundles that have no server to poll. */
export function formatBytes(n: number): string {
+ if (n >= 1 << 30) return (n / (1 << 30)).toFixed(1) + " GB";
if (n >= 1 << 20) return (n / (1 << 20)).toFixed(1) + " MB";
if (n >= 1 << 10) return (n / (1 << 10)).toFixed(1) + " KB";
return n + " B";
diff --git a/builder/web/src/lib/library/backup.test.ts b/builder/web/src/lib/library/backup.test.ts
new file mode 100644
index 0000000000..38699a1666
--- /dev/null
+++ b/builder/web/src/lib/library/backup.test.ts
@@ -0,0 +1,64 @@
+import { IDBFactory } from 'fake-indexeddb';
+import { describe, expect, it } from 'vitest';
+import { loadBackup, saveBackup } from './backup';
+import type { RideRecord, RouteRecord, RouteSummary } from './records';
+import { Library } from './store';
+import { summarize } from './summary';
+import { unzip, zip } from './zip';
+
+const route: RouteRecord = { id: 'r1', revision: 0, name: 'Alps', updatedAt: 5, open: 'v1',
+ summary: summarize([[8, 47, 400], [8.1, 47.1, 900]], { lengthM: 13_000, climbM: 500, seconds: 3600, days: 1, bike: 'touring' }),
+ trip: { points: [], routeOrder: [], days: 1 } };
+
+const ride = (key: string): RideRecord => ({ key, name: key, source: 'device', format: 'obcride', maxHr: 182, ftp: 250, device: `7:${key.slice(6, 8)}`,
+ summary: summarize([[8, 47, null], [8.01, 47, null]], { lengthM: 760, climbM: 0, seconds: 300, movingS: 280, start: 1_785_000_000, bike: 'gravel' }) });
+
+/** A library with one route, two rides and a deleted ride. */
+async function filled(): Promise {
+ const library = new Library(new IDBFactory());
+ await library.saveRoute(route, [{ id: 'v1', at: '2026-08-01T07:00:00.000Z', trip: route.trip }]);
+ await library.setState('active', 'r1');
+ await library.setState('nextMap', { regions: ['europe/switzerland'], boxes: [{ minLat: 46_000_000, minLon: 8_000_000, maxLat: 46_500_000, maxLon: 9_000_000 }], light: 'default', dark: 'dusk', bytes: 870_000_000 });
+ for (const key of ['20260801T070000Z', '20260802T070000Z', '20260803T070000Z']) await library.addRide(ride(key), new Blob([`bytes of ${key}`]));
+ await library.removeRide('20260803T070000Z');
+ return library;
+}
+
+/** The backup with `library.json` replaced by `edit` of it. */
+async function edited(backup: Blob, edit: (json: Record) => unknown): Promise {
+ const entries = await unzip(backup), json = JSON.parse(await entries.get('library.json')!.text());
+ return zip([...entries].map(([name, data]) => ({ name, data: name === 'library.json' ? new Blob([JSON.stringify(edit(json))]) : data })));
+}
+
+describe('library backup', () => {
+ it('loads into an empty library with equal records and the settings, and a second load adds nothing', async () => {
+ const source = await filled(), backup = await saveBackup(source, { units: 'km' });
+ const target = new Library(new IDBFactory());
+ expect(await loadBackup(target, backup)).toEqual({ routes: 1, rides: 2, settings: { units: 'km' } });
+ expect(await target.contents()).toEqual(await source.contents());
+ expect(await (await target.rideFile('20260802T070000Z'))!.text()).toBe('bytes of 20260802T070000Z');
+ expect(await loadBackup(target, backup)).toEqual({ routes: 0, rides: 0 });
+ expect((await target.routes())[0].revision).toBe(1);
+ });
+
+ it('changes nothing for a damaged file or a file of another version', async () => {
+ const backup = await saveBackup(await filled(), {}), target = new Library(new IDBFactory());
+ const bytes = new Uint8Array(await backup.arrayBuffer());
+ bytes[45] ^= 0xff;
+ const files = [new Blob([bytes]), backup.slice(0, backup.size / 2), await edited(backup, json => ({ ...json, version: 2 })),
+ await edited(backup, json => ({ ...json, rides: [...json.rides as RideRecord[], ride('20260809T070000Z')] })),
+ await edited(backup, json => ({ ...json, state: { nextMap: { regions: [], boxes: [{ minLat: 46.5 }], light: 'default', dark: 'dusk', bytes: 1 } } })),
+ // A box with no height.
+ await edited(backup, json => ({ ...json, state: { nextMap: { regions: [], boxes: [{ minLat: 46_000_000, minLon: 8_000_000, maxLat: 46_000_000, maxLon: 9_000_000 }], light: 'default', dark: 'dusk', bytes: 1 } } }))];
+ for (const file of files) await expect(loadBackup(target, file)).rejects.toThrow();
+ expect(await target.contents()).toEqual({ routes: [], versions: {}, rides: [], files: new Map(), state: {} });
+ });
+
+ it('does not bring back a ride that the rider deleted', async () => {
+ const backup = await saveBackup(await filled(), {}), target = new Library(new IDBFactory());
+ await target.addRide(ride('20260801T070000Z'), new Blob(['kept']));
+ await target.removeRide('20260801T070000Z');
+ expect(await loadBackup(target, backup)).toEqual({ routes: 1, rides: 1 });
+ expect((await target.rides()).map(r => r.key)).toEqual(['20260802T070000Z']);
+ });
+});
diff --git a/builder/web/src/lib/library/backup.ts b/builder/web/src/lib/library/backup.ts
new file mode 100644
index 0000000000..0cc5d7cab6
--- /dev/null
+++ b/builder/web/src/lib/library/backup.ts
@@ -0,0 +1,52 @@
+/** Saves the library and the settings as one backup file, and adds the records of a backup file to the library. */
+import { isRideRecord, isRouteRecord, stateChecks, type LibraryState, type RideRecord } from './records';
+import type { Contents, Library } from './store';
+import { unzip, zip } from './zip';
+
+const format = 'openbikecomputer-library', version = 1;
+
+const filePath = (ride: RideRecord) => `rides/${ride.key}.${ride.format}`;
+
+/** A ZIP file of `library.json` and the source file of each ride (`specs/library-backup.md`). */
+export async function saveBackup(library: Library, settings: object): Promise {
+ const { routes, versions, rides, files, state } = await library.contents();
+ const kept = rides.filter(ride => files.has(ride.key));
+ const json = JSON.stringify({ format, version, routes, versions: Object.fromEntries(routes.flatMap(r => versions[r.id] ? [[r.id, versions[r.id]]] : [])), rides: kept, state, settings });
+ return zip([{ name: 'library.json', data: new Blob([json], { type: 'application/json' }) }, ...kept.map(ride => ({ name: filePath(ride), data: files.get(ride.key)! }))]);
+}
+
+const isObject = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value);
+
+/** The contents and the settings of a backup file. It refuses a file of another version and a damaged file. */
+async function readBackup(file: Blob): Promise<{ contents: Contents; settings: Record }> {
+ const notBackup = new Error('This file is not a library backup.');
+ const entries = await unzip(file).catch(() => { throw notBackup; });
+ const text = await entries.get('library.json')?.text();
+ let json: unknown;
+ try { json = JSON.parse(text ?? ''); } catch { throw notBackup; }
+ if (!isObject(json) || json.format !== format) throw notBackup;
+ if (json.version !== version) throw new Error('This backup is from another version of the app. Update the app and try again.');
+ const { routes, versions, rides, state, settings } = json;
+ const damaged = new Error('This backup is damaged. Nothing was loaded.');
+ if (!Array.isArray(routes) || !routes.every(isRouteRecord) || new Set(routes.map(r => r.id)).size !== routes.length) throw damaged;
+ if (!Array.isArray(rides) || !rides.every(isRideRecord) || new Set(rides.map(r => r.key)).size !== rides.length) throw damaged;
+ const ids = new Set(routes.map(r => r.id));
+ if (!isObject(versions) || !Object.entries(versions).every(([id, list]) => ids.has(id) && Array.isArray(list))) throw damaged;
+ if (!isObject(state) || !Object.entries(state).every(([key, value]) => Object.hasOwn(stateChecks, key) && stateChecks[key as keyof LibraryState](value))) throw damaged;
+ if (!isObject(settings)) throw damaged;
+ const files = new Map();
+ for (const ride of rides) {
+ const data = entries.get(filePath(ride));
+ if (!data) throw damaged;
+ files.set(ride.key, data);
+ }
+ return { contents: { routes, versions: versions as Record, rides, files, state: state as Partial }, settings };
+}
+
+/** Adds the new records of a backup file, all or none. A route is new when its id is not stored; a ride when its key is
+ * neither stored nor deleted. The settings come back only when the library was empty. */
+export async function loadBackup(library: Library, file: Blob): Promise<{ routes: number; rides: number; settings?: Record }> {
+ const { contents, settings } = await readBackup(file);
+ const { routes, rides, empty } = await library.merge(contents);
+ return { routes, rides, ...empty && { settings } };
+}
diff --git a/builder/web/src/lib/library/groups.test.ts b/builder/web/src/lib/library/groups.test.ts
new file mode 100644
index 0000000000..919c8d9960
--- /dev/null
+++ b/builder/web/src/lib/library/groups.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from 'vitest';
+import { groups, sameRoute } from './groups';
+import { rideKeyAt } from './import';
+import type { RideRecord, RouteRecord } from './records';
+import { rideSummary } from './summary';
+
+const METRES_PER_DEGREE = 6_371_008.8 * Math.PI / 180, COS = Math.cos(47 * Math.PI / 180);
+
+/** A wiggly loop of about 30 km around 8° E, 47° N, as points in metres every 5 m, from `from` (0 to 1) of the way round. */
+function loop(from = 0, backwards = false, shift = 0): [number, number][] {
+ const n = 6000;
+ return Array.from({ length: n + 1 }, (_, i) => {
+ const angle = 2 * Math.PI * (from + (backwards ? -i : i) / n), radius = 4600 + 300 * Math.sin(7 * angle);
+ return [radius * Math.cos(angle), radius * Math.sin(angle) + shift];
+ });
+}
+
+/** GPS noise of up to 15 m that drifts over a few hundred metres, as a receiver's error does. */
+const noisy = (points: [number, number][], seed: number): [number, number][] =>
+ points.map(([x, y], i) => [x + 15 * Math.sin(i / (17 + seed) + seed), y + 15 * Math.cos(i / (23 + seed) + 2 * seed)]);
+
+function ride(points: [number, number][], start: number): RideRecord {
+ const summary = rideSummary(points.map(([x, y], i) => ({
+ timeS: start + i, lon: Math.round((8 + x / METRES_PER_DEGREE / COS) * 1e6), lat: Math.round((47 + y / METRES_PER_DEGREE) * 1e6),
+ elevationM: null, segmentStart: i === 0,
+ })), 'gravel');
+ return { key: rideKeyAt(start), name: `Ride ${start}`, source: 'file', format: 'gpx', summary, maxHr: null, ftp: null };
+}
+
+const route = (id: string, updatedAt: number, from: RideRecord): RouteRecord =>
+ ({ id, revision: 0, name: id, updatedAt, summary: { ...from.summary, days: 1 }, trip: {} });
+
+describe('sameRoute', () => {
+ const a = ride(noisy(loop(), 1), 1000).summary;
+
+ it('joins two noisy rides of one road, from another start and the other way', () => {
+ expect(a.line.length / 2).toBeLessThanOrEqual(1000);
+ expect(sameRoute(a, ride(noisy(loop(), 2), 2000).summary)).toBe(true);
+ expect(sameRoute(a, ride(noisy(loop(0.4, true), 3), 3000).summary)).toBe(true);
+ });
+
+ it('keeps apart a ride 12 % longer, a road 150 m away and a ride that is 15 % elsewhere', () => {
+ const longer = loop();
+ expect(sameRoute(a, ride([...longer, ...loop().slice(0, 720)], 2000).summary)).toBe(false);
+ expect(sameRoute(a, ride(loop(0, false, 150), 3000).summary)).toBe(false);
+ // 15 % of the loop moves 400 m out; the length changes by less than 10 %.
+ const elsewhere = loop().map(([x, y], i): [number, number] => i < 900 ? [x * (1 + 400 / 4600), y * (1 + 400 / 4600)] : [x, y]);
+ const other = ride(elsewhere, 4000).summary;
+ expect(Math.abs(other.lengthM - a.lengthM) / a.lengthM).toBeLessThan(0.1);
+ expect(sameRoute(a, other)).toBe(false);
+ });
+});
+
+describe('groups', () => {
+ const [first, second, third] = [1, 2, 3].map(seed => ride(noisy(loop(seed / 10), seed), seed * 86_400));
+ const other = ride(loop(0, false, 5000), 4 * 86_400);
+
+ it('puts the rides of one road in the newest route that they follow, else in the group of the first ride', async () => {
+ const routes = [route('old', 1, first), route('new', 2, second), route('far', 3, other)];
+ expect(await groups([third, second, first, other], routes)).toEqual(new Map([
+ [first.key, 'new'], [second.key, 'new'], [third.key, 'new'], [other.key, 'far']]));
+ expect(await groups([third, second, first, other], [])).toEqual(new Map([
+ [first.key, first.key], [second.key, first.key], [third.key, first.key], [other.key, other.key]]));
+ });
+
+ it('leaves out a ride taken apart, and gives the group to the next ride when the first is deleted', async () => {
+ expect(await groups([first, second, third], [], [second.key])).toEqual(new Map([[first.key, first.key], [third.key, first.key]]));
+ expect(await groups([second, third], [])).toEqual(new Map([[second.key, second.key], [third.key, second.key]]));
+ });
+});
diff --git a/builder/web/src/lib/library/groups.ts b/builder/web/src/lib/library/groups.ts
new file mode 100644
index 0000000000..ffa2695187
--- /dev/null
+++ b/builder/web/src/lib/library/groups.ts
@@ -0,0 +1,165 @@
+/** Groups the rides that follow one road: a ride joins the planned route or the first ride of a group whose line it follows. */
+import type { RideRecord, RouteRecord, Summary } from './records';
+import { lastToleranceM, metresPerDegree } from './summary';
+
+// Two lines are on one road when their lengths differ by 10 % or less and 90 % of each is within 50 m of the other. A
+// summary line is within 40 m of its points, so its vertices test at 90 m.
+const LENGTH_SHARE = 0.1, MISS_SHARE = 0.1, NEAR_M = 50 + lastToleranceM;
+// A task of the event loop ends after this much work, so a full test that starts just before it ends under 50 ms.
+const WORK_MS = 30;
+
+/** A summary line on a flat projection at its first point, in metres, its segments by grid cell, and the weight of each
+ * vertex: half of its two segments. */
+interface Prepared {
+ lon0: number;
+ lat0: number;
+ k: number;
+ xy: Float64Array;
+ grid: Map;
+ weights: Float64Array;
+ total: number;
+}
+
+function prepare({ line }: Summary): Prepared {
+ const lon0 = line[0], lat0 = line[1], k = Math.cos(lat0 * Math.PI / 180) * metresPerDegree;
+ const xy = Float64Array.from(line, (value, i) => i % 2 ? (value - lat0) * metresPerDegree : (value - lon0) * k);
+ const n = xy.length / 2, weights = new Float64Array(n);
+ let total = 0;
+ for (let i = 0; i + 1 < n; i++) {
+ const step = Math.hypot(xy[2 * i + 2] - xy[2 * i], xy[2 * i + 3] - xy[2 * i + 1]);
+ weights[i] += step / 2;
+ weights[i + 1] += step / 2;
+ total += step;
+ }
+ return { lon0, lat0, k, xy, grid: cells(xy), weights, total };
+}
+
+const middles = new WeakMap();
+
+/** The mean point of a summary line, each segment weighted by its length, in degrees. */
+function middle(summary: Summary): [number, number] {
+ let point = middles.get(summary);
+ if (point) return point;
+ const { line } = summary, k = Math.cos(line[1] * Math.PI / 180);
+ let x = 0, y = 0, total = 0;
+ for (let i = 2; i < line.length; i += 2) {
+ const length = Math.hypot((line[i] - line[i - 2]) * k, line[i + 1] - line[i - 1]);
+ [x, y, total] = [x + (line[i] + line[i - 2]) / 2 * length, y + (line[i + 1] + line[i - 1]) / 2 * length, total + length];
+ }
+ middles.set(summary, point = total ? [x / total, y / total] : [line[0], line[1]]);
+ return point;
+}
+
+/** The lengths are within 10 %, and each bounds edge and the mean point move by at most a tenth of the length, the
+ * tolerance, and the 40 m by which the bounds of the points can pass the summary line. A tenth of a line elsewhere, at
+ * most half a length away, moves the mean point by a twentieth of the length; the other line can move it as far. */
+function near(a: Summary, b: Summary): boolean {
+ const longer = Math.max(a.lengthM, b.lengthM);
+ if (a.line.length < 4 || b.line.length < 4 || Math.abs(a.lengthM - b.lengthM) > LENGTH_SHARE * longer) return false;
+ const k = Math.cos((a.bounds[1] + a.bounds[3]) / 2 * Math.PI / 180), edge = (LENGTH_SHARE * longer + NEAR_M + lastToleranceM) / metresPerDegree;
+ if (!a.bounds.every((value, i) => Math.abs(value - b.bounds[i]) * (i % 2 ? 1 : k) <= edge)) return false;
+ const [ma, mb] = [middle(a), middle(b)];
+ return Math.hypot((ma[0] - mb[0]) * k, ma[1] - mb[1]) <= edge;
+}
+
+/** Two summaries are of one road. The start point and the direction do not matter. */
+export function sameRoute(a: Summary, b: Summary): boolean {
+ return near(a, b) && full(a, b, prepare(a), prepare(b));
+}
+
+const full = (a: Summary, b: Summary, pa: Prepared, pb: Prepared) => covered(a.line, pa, pb) && covered(b.line, pb, pa);
+
+/** At most a tenth of `line`, by the weights of its vertices, is farther than `NEAR_M` from `other`. */
+function covered(line: number[], { weights, total }: Prepared, other: Prepared): boolean {
+ let missed = 0;
+ for (let i = 0; i < weights.length; i++) {
+ const weight = weights[i];
+ // The vertex in the projection of the other line.
+ const x = (line[2 * i] - other.lon0) * other.k, y = (line[2 * i + 1] - other.lat0) * metresPerDegree;
+ if (!weight || within(x, y, other)) continue;
+ missed += weight;
+ if (missed > MISS_SHARE * total) return false;
+ }
+ return true;
+}
+
+const cellOf = (value: number) => Math.floor(value / NEAR_M);
+const cellKey = (x: number, y: number) => x * 0x100000 + y;
+
+/** The segments of a line by the cells of `NEAR_M` that their points, one each `NEAR_M` along them, fall in. */
+function cells(line: Float64Array): Map {
+ const grid = new Map();
+ for (let s = 0; s + 3 < line.length; s += 2) {
+ const [ax, ay, bx, by] = [line[s], line[s + 1], line[s + 2], line[s + 3]];
+ const steps = Math.ceil(Math.hypot(bx - ax, by - ay) / NEAR_M);
+ let last = NaN;
+ for (let j = 0; j <= steps; j++) {
+ const t = steps ? j / steps : 0, key = cellKey(cellOf(ax + t * (bx - ax)), cellOf(ay + t * (by - ay)));
+ if (key === last) continue;
+ last = key;
+ const list = grid.get(key);
+ if (!list) grid.set(key, [s]);
+ else if (list.at(-1) !== s) list.push(s);
+ }
+ }
+ return grid;
+}
+
+/** The point is within `NEAR_M` of a segment. The nearest point of a segment is within half a cell of one of its cell
+ * points, so the segment is in a cell at most two away. */
+function within(x: number, y: number, { xy, grid }: Prepared): boolean {
+ const cx = cellOf(x), cy = cellOf(y);
+ for (let dx = -2; dx <= 2; dx++) {
+ for (let dy = -2; dy <= 2; dy++) {
+ for (const s of grid.get(cellKey(cx + dx, cy + dy)) ?? []) {
+ const ax = xy[s], ay = xy[s + 1], ex = xy[s + 2] - ax, ey = xy[s + 3] - ay, length = ex * ex + ey * ey;
+ const t = length ? Math.max(0, Math.min(1, ((x - ax) * ex + (y - ay) * ey) / length)) : 0;
+ if (Math.hypot(x - ax - t * ex, y - ay - t * ey) <= NEAR_M) return true;
+ }
+ }
+ }
+ return false;
+}
+
+/** The results of the full test for this session, by ride key and route id with its time of change. Only pairs that pass
+ * the cheap test reach it. */
+const known = new Map();
+
+/**
+ * The group of each ride that `apart` does not hold, by ride key: the id of a route, or the key of the first ride of the
+ * group. In start order, a ride joins the first route it follows, newest first, else the group of the first ride it
+ * follows, else it starts a group. A group holds the ride that started it, so a group of one ride has its key.
+ */
+export async function groups(rides: RideRecord[], routes: RouteRecord[], apart: string[] = []): Promise> {
+ const out = new Map(), skip = new Set(apart), firsts: { id: string; pair: string; summary: Summary }[] = [];
+ const anchors = routes.filter(route => route.summary).sort((a, b) => b.updatedAt - a.updatedAt)
+ .map(route => ({ id: route.id, pair: `${route.id}@${route.updatedAt}`, summary: route.summary! }));
+ // The projections of this run; a run frees them, so only the results stay.
+ const prepared = new Map(), of = (summary: Summary) => prepared.get(summary) ?? prepared.set(summary, prepare(summary)).get(summary)!;
+ let since = performance.now();
+ const same = async (ride: RideRecord, pair: string, summary: Summary) => {
+ const key = `${ride.key}|${pair}`;
+ let result = known.get(key);
+ if (result === undefined) {
+ if (performance.now() - since > WORK_MS) {
+ await new Promise(resolve => setTimeout(resolve));
+ since = performance.now();
+ }
+ known.set(key, result = full(ride.summary, summary, of(ride.summary), of(summary)));
+ }
+ return result;
+ };
+ for (const ride of [...rides].sort((a, b) => a.summary.start - b.summary.start)) {
+ if (skip.has(ride.key)) continue;
+ let group: string | undefined;
+ for (const { id, pair, summary } of [...anchors, ...firsts]) {
+ if (near(ride.summary, summary) && await same(ride, pair, summary)) {
+ group = id;
+ break;
+ }
+ }
+ if (!group) firsts.push({ id: ride.key, pair: ride.key, summary: ride.summary });
+ out.set(ride.key, group ?? ride.key);
+ }
+ return out;
+}
diff --git a/builder/web/src/lib/library/import.test.ts b/builder/web/src/lib/library/import.test.ts
new file mode 100644
index 0000000000..b351d85cb5
--- /dev/null
+++ b/builder/web/src/lib/library/import.test.ts
@@ -0,0 +1,209 @@
+import { IDBFactory } from 'fake-indexeddb';
+import { crc32, deflateRawSync, gzipSync } from 'node:zlib';
+import { describe, expect, it } from 'vitest';
+import { readFiles, reasons, type Found, type Item, type Readers } from './import';
+import { Library } from './store';
+
+const encode = (value: unknown) => new TextEncoder().encode(typeof value === 'string' ? value : JSON.stringify(value));
+
+/** Fake readers: a GPX file is the JSON of a track, a FIT file the JSON of a ride or of `{ code }`. */
+const readers: Readers = {
+ gpx: text => {
+ try { return JSON.parse(text); } catch { throw Object.assign(new Error('no points'), { name: 'GpxError' }); }
+ },
+ fit: bytes => {
+ const value = JSON.parse(new TextDecoder().decode(bytes));
+ if (value.code) throw Object.assign(new Error(value.code), { name: 'FitError', code: value.code });
+ return value;
+ },
+};
+
+/** `size` is the declared size of the content. */
+interface Part { name: string | Uint8Array; data: Uint8Array; method?: number; crc?: number; size?: number }
+
+/** A ZIP file. A name in bytes has no UTF-8 flag. With `zip64`, the sizes and offsets are in ZIP64 records. */
+function zipOf(parts: Part[], zip64 = false): Uint8Array {
+ const files: Buffer[] = [], central: Buffer[] = [];
+ let offset = 0;
+ for (const { name, data, method = 8, crc = crc32(data), size = data.length } of parts) {
+ const path = Buffer.from(name), packed = method === 8 ? deflateRawSync(data) : Buffer.from(data), flags = typeof name === 'string' ? 0x0800 : 0;
+ const local = Buffer.alloc(30), header = Buffer.alloc(46), extra = Buffer.alloc(zip64 ? 28 : 0);
+ local.writeUInt32LE(0x04034b50, 0);
+ header.writeUInt32LE(0x02014b50, 0);
+ for (const [buffer, at] of [[local, 4], [header, 6]] as const) {
+ buffer.writeUInt16LE(flags, at + 2);
+ buffer.writeUInt16LE(method, at + 4);
+ buffer.writeUInt32LE(crc, at + 10);
+ buffer.writeUInt32LE(zip64 ? 0xffffffff : packed.length, at + 14);
+ buffer.writeUInt32LE(zip64 ? 0xffffffff : size, at + 18);
+ buffer.writeUInt16LE(path.length, at + 22);
+ }
+ header.writeUInt16LE(extra.length, 30);
+ header.writeUInt32LE(zip64 ? 0xffffffff : offset, 42);
+ if (zip64) [1, 24].forEach((v, i) => extra.writeUInt16LE(v, i * 2));
+ if (zip64) [size, packed.length, offset].forEach((v, i) => extra.writeBigUInt64LE(BigInt(v), 4 + i * 8));
+ files.push(local, path, packed);
+ central.push(header, path, extra);
+ offset += 30 + path.length + packed.length;
+ }
+ const directory = Buffer.concat(central), end = Buffer.alloc(22), tail: Buffer[] = [];
+ end.writeUInt32LE(0x06054b50, 0);
+ if (zip64) {
+ const record = Buffer.alloc(56), locator = Buffer.alloc(20);
+ record.writeUInt32LE(0x06064b50, 0);
+ [[4, 44], [24, parts.length], [32, parts.length], [40, directory.length], [48, offset]].forEach(([at, v]) => record.writeBigUInt64LE(BigInt(v), at));
+ locator.writeUInt32LE(0x07064b50, 0);
+ locator.writeBigUInt64LE(BigInt(offset + directory.length), 8);
+ tail.push(record, locator);
+ end.fill(0xff, 8, 20);
+ } else {
+ [[8, 2], [10, 2], [12, 4], [16, 4]].forEach(([at, size], i) => end.writeUIntLE([parts.length, parts.length, directory.length, offset][i], at, size));
+ }
+ return new Uint8Array(Buffer.concat([...files, directory, ...tail, end]));
+}
+
+const t = Date.UTC(2026, 7, 1, 7) / 1000;
+const samples = (start: number, east = 0) => [0, 1, 2].map(i => ({ timeS: start + i * 60, lat: 47e6, lon: 8e6 + east + i * 1000, segmentStart: !i }));
+const points = (start?: number, east = 0) => samples(start ?? 0, east).map(({ timeS, lat, lon }) => ({ lat, lon, ...start !== undefined && { time: timeS } }));
+const file = (name: string, value: unknown) => new File([value instanceof Uint8Array ? value as Uint8Array : encode(value)], name);
+const gz = (value: unknown) => new Uint8Array(gzipSync(encode(value)));
+
+const evening = file('evening.gpx', { name: 'Evening', points: points(t), waypoints: [], kind: 'mountain_biking' });
+const jura = file('jura.gpx', { name: 'Jura', points: points(undefined, 2000), waypoints: [] });
+const morning = file('1.fit.gz', gz({ sport: 'bike', samples: samples(t + 3600) }));
+
+/** A dropped folder with `files`, as `FileSystemDirectoryEntry` gives it. */
+function folder(name: string, files: File[], onRead = () => {}): FileSystemEntry {
+ const entry = (file: File) => ({ isFile: true, isDirectory: false, name: file.name, fullPath: `/${name}/${file.name}`, file: (ok: (f: File) => void) => ok(file) });
+ let read = false;
+ return { isFile: false, isDirectory: true, name, fullPath: `/${name}`,
+ createReader: () => ({ readEntries: (ok: (entries: unknown[]) => void) => { onRead(); ok(read ? [] : (read = true, files.map(entry))); } }) } as unknown as FileSystemEntry;
+}
+
+async function collect(items: Item[], library: Library): Promise {
+ const found: Found[] = [];
+ for await (const item of readFiles(items, library, readers, new AbortController().signal)) found.push(item);
+ return found;
+}
+
+const row = (found: Found) => [found.file, found.kind, found.name,
+ ...found.kind === 'ride' ? [found.ride.summary.bike] : found.kind === 'route' ? [found.bike] : found.kind === 'unreadable' ? [found.reason] : []];
+
+describe('readFiles', () => {
+ it('reads a folder, deflated entries, a CP437 name, a ZIP in a ZIP, ZIP64 records and .gz files, with the names of a Strava CSV', async () => {
+ const library = new Library(new IDBFactory());
+ // A name in quotes with a comma, a quote and a line break; the CSV comes after the files of the ZIP.
+ const csv = 'Activity ID,Activity Date,Activity Name,Activity Type,Filename\n1,"Aug 1, 2026","Loop, ""short""\nversion",Gravel Ride,activities/1.fit.gz\r\n';
+ const exported = file('export.zip', zipOf([
+ { name: 'activities/1.fit.gz', data: new Uint8Array(await morning.arrayBuffer()), method: 0 },
+ { name: Uint8Array.from([...encode('Z'), 0x81, ...encode('rich.gpx')]), data: encode({ name: 'Zürich', points: points(undefined, 5000), waypoints: [] }) },
+ // The macOS Finder writes UTF-8 names with no flag.
+ { name: encode('Genève.gpx'), data: encode({ name: 'Genève', points: points(undefined, 9000), waypoints: [] }) },
+ { name: 'DI_CONNECT/part.zip', data: zipOf([{ name: 'UploadedFiles/2.fit', data: encode({ sport: 'foot', samples: samples(t + 7200) }) }]) },
+ { name: 'notes.txt', data: encode('not counted') },
+ { name: 'activities.csv', data: encode(csv) },
+ ]));
+ const old = file('old.zip', zipOf([{ name: 'other.fit', data: encode({ sport: 'road', samples: samples(t + 10800) }) }], true));
+ expect((await collect([folder('rides', [evening, jura]), exported, old], library)).map(row)).toEqual([
+ ['rides/evening.gpx', 'ride', 'Evening', 'mtb'],
+ ['rides/jura.gpx', 'route', 'Jura', 'touring'],
+ ['export.zip/activities/1.fit.gz', 'ride', 'Loop, "short"\nversion', 'gravel'],
+ ['export.zip/Zürich.gpx', 'route', 'Zürich', 'touring'],
+ ['export.zip/Genève.gpx', 'route', 'Genève', 'touring'],
+ ['export.zip/DI_CONNECT/part.zip/UploadedFiles/2.fit', 'ride', 'Hike, 1 Aug 2026', 'hiking'],
+ ['old.zip/other.fit', 'ride', 'other', 'road'],
+ ]);
+ await library.close();
+ });
+
+ it('counts a ride as known when its key is stored, deleted or came before, and a route when its id is stored', async () => {
+ const library = new Library(new IDBFactory());
+ const first = await collect([evening, morning, jura, file('copy.gpx', await evening.text())], library);
+ expect(first.map(found => found.kind)).toEqual(['ride', 'ride', 'route', 'known']);
+ const [ride, other, route] = first as [Found & { kind: 'ride' }, Found & { kind: 'ride' }, Found & { kind: 'route' }];
+ expect([ride.ride.key, ride.ride.summary.start]).toEqual(['20260801T070000Z', t]);
+ expect(await (await other.open()).text()).toBe(JSON.stringify({ sport: 'bike', samples: samples(t + 3600) }));
+ expect((await route.open()).name).toBe('Jura');
+ expect(route.id).toMatch(/^file-[0-9a-f]{32}$/);
+ await library.addRide(ride.ride, await ride.open());
+ await library.addRide(other.ride, await other.open());
+ await library.removeRide(other.ride.key);
+ await library.addRoute({ id: route.id, revision: 0, name: route.name, updatedAt: 0, summary: null, trip: {} });
+ expect((await collect([evening, morning, jura], library)).map(found => found.kind)).toEqual(['known', 'known', 'known']);
+ await library.close();
+ });
+
+ it('gives the reason for each file that it cannot read, and counts no other file', async () => {
+ const library = new Library(new IDBFactory());
+ const packed = file('packed.zip', zipOf([
+ { name: 'bzip2.fit', data: encode({ sport: 'bike', samples: samples(t) }), method: 12 },
+ { name: 'crc.fit', data: encode({ sport: 'bike', samples: samples(t) }), crc: 1 },
+ { name: 'photo.jpg', data: encode('not counted') },
+ // 1 MB of zeros that declares 1 KB.
+ { name: 'bomb.fit', data: new Uint8Array(1 << 20), size: 1024 },
+ ]));
+ const found = await collect([
+ file('a.tcx', ' '), file('b.tcx.gz', gz(' ')),
+ file('swim.fit', { sport: 'other', samples: samples(t) }), file('cut.fit', { code: 'fit-damaged' }),
+ file('empty.fit', { code: 'fit-no-positions' }), file('page.gpx', ' '), file('broken.fit.gz', 'not gzip'),
+ file('bad.zip', 'not a zip'), packed, file('readme.md', 'not counted'),
+ ], library);
+ expect(found.map(f => [f.name, f.kind === 'unreadable' && f.reason])).toEqual([
+ ['bad.zip', reasons.damaged], ['a.tcx', reasons.tcx], ['b.tcx.gz', reasons.tcx], ['swim.fit', reasons.sport],
+ ['cut.fit', reasons.damaged], ['empty.fit', reasons.track], ['page.gpx', reasons.track], ['broken.fit.gz', reasons.damaged],
+ ['bzip2.fit', reasons.packing], ['crc.fit', reasons.damaged], ['bomb.fit', reasons.damaged],
+ ]);
+ await library.close();
+ });
+
+ it('takes a specific bike of Strava or else of the file, refuses a sport that is not by bike or on foot, and names a ride with no name by its date', async () => {
+ const library = new Library(new IDBFactory());
+ const csv = (header: string) => `${header}\n${[['1.fit', 'Ride'], ['2.gpx', 'Swim'], ['3.fit', 'Alpine Ski'], ['4.fit', 'Ride']]
+ .map(([file, type], i) => `${i},"Aug 1, 2026",${i === 3 ? '' : `Name ${i}`},${type},,,,,,,,,activities/${file}`).join('\n')}\n`;
+ const files = [
+ file('1.fit', { sport: 'road', samples: samples(t) }),
+ file('2.gpx', { name: 'Lake', points: points(t + 3600), waypoints: [] }),
+ file('3.fit', { sport: 'bike', samples: samples(t + 7200) }),
+ file('4.fit', { sport: 'bike', samples: samples(t + 10800) }),
+ file('12345.fit', { sport: 'foot', samples: samples(t + 14400) }),
+ file('me@example.org.gpx', { name: 'me@example.org', points: points(undefined, 7000), waypoints: [] }),
+ ];
+ const english = 'Activity ID,Activity Date,Activity Name,Activity Type,Activity Description,Elapsed Time,Distance,Max Heart Rate,Relative Effort,Commute,Activity Private Note,Activity Gear,Filename';
+ expect((await collect([...files, file('activities.csv', csv(english))], library)).map(row)).toEqual([
+ ['1.fit', 'ride', 'Name 0', 'road'],
+ ['2.gpx', 'unreadable', '2.gpx', reasons.sport],
+ ['3.fit', 'unreadable', '3.fit', reasons.sport],
+ ['4.fit', 'ride', 'Ride, 1 Aug 2026', 'touring'],
+ ['12345.fit', 'ride', 'Hike, 1 Aug 2026', 'hiking'],
+ ['me@example.org.gpx', 'route', 'Planned route', 'touring'],
+ ]);
+ // German headers: the names come from the place of the columns; a type that names no bike leaves the sport of the file.
+ const german = (await collect([...files.slice(0, 3), file('activities.csv', csv(english.replace('Activity Name', 'Name der Aktivität').replace('Activity Type', 'Aktivitätsart').replace('Filename', 'Dateiname')))], library)).map(row);
+ expect(german).toEqual([['1.fit', 'ride', 'Name 0', 'road'], ['2.gpx', 'ride', 'Name 1', 'touring'], ['3.fit', 'ride', 'Name 2', 'touring']]);
+ await library.close();
+ });
+
+ it('stops when the signal aborts, also while it lists, and opens no later ZIP', async () => {
+ const controller = new AbortController();
+ let reads = 0;
+ const later = new (class extends File { slice(...args: Parameters) { reads++; return super.slice(...args); } })(
+ [zipOf([{ name: 'a.fit', data: encode({ sport: 'bike', samples: samples(t) }) }])], 'later.zip');
+ const run = readFiles([folder('rides', [evening], () => controller.abort()), later], new Library(new IDBFactory()), readers, controller.signal);
+ await expect(run.next()).rejects.toThrow(/abort/i);
+ expect(reads).toBe(0);
+ });
+
+ it('finds a GPX file with times as a ride that can become a route, as a route when it starts later than now, and as known in either form once stored', async () => {
+ const library = new Library(new IDBFactory());
+ const tour = file('tour.gpx', { name: 'Tour', points: points(Date.now() / 1000 + 86400, 3000), waypoints: [] });
+ const [ride, planned] = await collect([evening, tour], library) as [Found & { kind: 'ride' }, Found & { kind: 'route' }];
+ expect([ride.kind, ride.other?.kind, planned.kind, planned.other?.kind]).toEqual(['ride', 'route', 'route', 'ride']);
+ const route = ride.other as Found & { kind: 'route' }, recorded = planned.other as Found & { kind: 'ride' };
+ expect(route).toMatchObject({ name: 'Evening', bike: 'mtb', lengthM: ride.ride.summary.lengthM });
+ expect((await route.open()).points.map(p => p.time)).toEqual(points(t).map(p => p.time));
+ await library.addRoute({ id: route.id, revision: 0, name: route.name, updatedAt: 0, summary: null, trip: {} });
+ await library.addRide(recorded.ride, await recorded.open());
+ expect((await collect([evening, tour], library)).map(found => found.kind)).toEqual(['known', 'known']);
+ await library.close();
+ });
+});
diff --git a/builder/web/src/lib/library/import.ts b/builder/web/src/lib/library/import.ts
new file mode 100644
index 0000000000..f80d5011c8
--- /dev/null
+++ b/builder/web/src/lib/library/import.ts
@@ -0,0 +1,247 @@
+/** Finds the rides and the planned routes in GPX and FIT files, in folders and in the ZIP exports of services. */
+import { settings } from '../settings/settings.svelte';
+import type { Bike, RideRecord } from './records';
+import type { Library } from './store';
+import { rideSummary, type RideSample } from './summary';
+import { entries, open, UnsupportedPacking } from './zip';
+
+/** A point in microdegrees, with the time in Unix seconds. */
+export interface TrackPoint { lat: number; lon: number; ele?: number; time?: number; segmentStart?: true }
+/** A GPX file or a FIT course, as the readers give it. */
+export interface Track {
+ name: string;
+ points: TrackPoint[];
+ waypoints: { lat: number; lon: number; name?: string; note?: string }[];
+ kind?: string;
+}
+export interface Recording { sport: string; samples: RideSample[] }
+
+/** The file readers of `lib/core`, which the caller gives so that the library depends on no other system. They throw
+ * an error with the name `GpxError`, or with the name `FitError` and a `code`. */
+export interface Readers {
+ gpx(text: string, fallback: string): Track;
+ fit(bytes: Uint8Array, fallback: string): Recording | Track;
+}
+
+/** A dropped or chosen file, or a dropped folder. */
+export type Item = File | FileSystemEntry;
+
+/** One file that was read. `name` is the name of the record, or else the name of the file. `open` reads the file
+ * again: a ride gives its source file, a route its track. A GPX file with times can be a ride or a route, as a planned
+ * tour of Komoot has times too: each of its two forms holds the other in `other`. */
+export type Found = { file: string; name: string } & (
+ | { kind: 'ride'; ride: RideRecord; open: () => Promise; other?: Found }
+ | { kind: 'route'; id: string; lengthM: number; bike: Bike; open: () => Promise; other?: Found }
+ | { kind: 'known' }
+ | { kind: 'unreadable'; reason: string });
+
+export const reasons = {
+ tcx: 'TCX files cannot be read',
+ track: 'the file has no track',
+ sport: 'not a ride by bike or on foot',
+ packing: 'this packing is not supported',
+ damaged: 'the file is damaged',
+};
+
+interface Source { path: string; get: () => Promise }
+
+const baseName = (path: string) => path.slice(path.lastIndexOf('/') + 1);
+const counted = /\.(gpx|fit|tcx)(\.gz)?$/i;
+
+/** An error whose message is the reason that the rider sees. */
+class Unreadable extends Error {}
+
+/** The reason of an error while a file, a ZIP entry or a `.gz` file opens: such an error means a damaged file. */
+const reasonOf = (error: unknown) => error instanceof Unreadable ? error.message : error instanceof UnsupportedPacking ? reasons.packing : reasons.damaged;
+const failure = (path: string, error: unknown): Found => ({ file: path, name: baseName(path), kind: 'unreadable', reason: reasonOf(error) });
+
+const gunzip = (blob: Blob) => new Response(blob.stream().pipeThrough(new DecompressionStream('gzip'))).blob();
+
+// A macOS copy keeps the attributes of each file in a file whose name starts with `._`.
+const wanted = (name: string) => !name.startsWith('._') && (counted.test(name) || /\.(csv|zip)$/i.test(name));
+const isZip = (name: string) => /\.zip$/i.test(name);
+
+/** Lists the files to read and the CSV files of `item`. It inflates each ZIP in a ZIP, one level deep, and keeps it. */
+async function list(item: Item | Blob, path: string, sources: Source[], failed: Found[], signal: AbortSignal, inZip = false): Promise {
+ signal.throwIfAborted();
+ const name = baseName(path);
+ if (!(item instanceof Blob) && item.isDirectory) {
+ const reader = (item as FileSystemDirectoryEntry).createReader();
+ for (let batch; (batch = await new Promise((resolve, reject) => reader.readEntries(resolve, reject))).length;) {
+ for (const child of batch) await list(child, `${path}/${child.name}`, sources, failed, signal);
+ }
+ return;
+ }
+ if (!wanted(name)) return;
+ const file = () => item instanceof Blob ? Promise.resolve(item) : new Promise((resolve, reject) => (item as FileSystemFileEntry).file(resolve, reject));
+ if (!isZip(name)) return void sources.push({ path, get: file });
+ let zipped;
+ try { zipped = await entries(await file()); } catch (error) { return void failed.push(failure(path, error)); }
+ for (const entry of zipped) {
+ const inner = `${path}/${entry.name}`;
+ if (entry.name.endsWith('/') || !wanted(baseName(entry.name))) continue;
+ if (!isZip(entry.name)) sources.push({ path: inner, get: () => open(entry) });
+ else if (!inZip) {
+ signal.throwIfAborted();
+ let content;
+ try { content = await open(entry); } catch (error) { failed.push(failure(inner, error)); continue; }
+ await list(content, inner, sources, failed, signal, true);
+ }
+ }
+}
+
+/** The rows of a CSV text: fields in quotes can hold commas, quotes as `""`, and line breaks. */
+export function csvRows(text: string): string[][] {
+ const rows: string[][] = [];
+ let row: string[] = [], field = '', quoted = false;
+ for (let i = text.charCodeAt(0) === 0xfeff ? 1 : 0; i < text.length; i++) {
+ const c = text[i];
+ if (quoted) {
+ if (c !== '"') field += c;
+ else if (text[i + 1] === '"') { field += '"'; i++; }
+ else quoted = false;
+ } else if (c === '"') quoted = true;
+ else if (c === ',') { row.push(field); field = ''; }
+ else if (c === '\n' || c === '\r') {
+ if (c === '\r' && text[i + 1] === '\n') i++;
+ rows.push([...row, field]);
+ row = []; field = '';
+ } else field += c;
+ }
+ if (field || row.length) rows.push([...row, field]);
+ return rows;
+}
+
+// The columns of Strava's export in English. Another language has the same order with other headers.
+const stravaColumns = { name: 2, type: 3, file: 12 };
+
+/** Strava's `activities.csv`: the name and the type of each activity, by the base name of its file. With no English
+ * headers, it finds the file column by its values, and uses the CSV only when that column is where the English one is.
+ * Then it keeps only a type that names a bike or a walk, so that a type in another language refuses no file. */
+async function strava(source: Source, into: Map): Promise {
+ const [header = [], ...rows] = csvRows(await (await source.get()).text());
+ let [name, type, file] = ['Activity Name', 'Activity Type', 'Filename'].map(column => header.indexOf(column));
+ const english = file >= 0;
+ if (!english) {
+ file = header.findIndex((_, i) => rows.some(row => row[i]?.startsWith('activities/')));
+ if (file !== stravaColumns.file) return;
+ ({ name, type } = stravaColumns);
+ }
+ for (const row of rows) {
+ const kind = row[type] ?? '';
+ if (row[file]) into.set(baseName(row[file]), { name: row[name] ?? '', type: english || bikeOf(kind) ? kind : '' });
+ }
+}
+
+/** The bike of an activity type of a file or of Strava, such as `cycling`, `Gravel Ride` or `Hike`. `touring` is the
+ * match of a type that names no kind of bike. */
+function bikeOf(type = ''): Bike | undefined {
+ const t = type.toLowerCase();
+ if (/hik|walk|run|trek/.test(t)) return 'hiking';
+ if (/mountain|mtb/.test(t)) return 'mtb';
+ if (/gravel/.test(t)) return 'gravel';
+ if (/road/.test(t)) return 'road';
+ return /cycl|bik|ride/.test(t) ? 'touring' : undefined;
+}
+
+/** A specific bike of Strava, else the bike of the file, else touring. Null when Strava names a sport that is not by
+ * bike or on foot, or when the FIT file does and Strava names none. */
+function chooseBike(stravaType: string | undefined, fromFile: Bike | null | undefined): Bike | null {
+ const fromStrava = stravaType ? bikeOf(stravaType) ?? null : undefined;
+ if (fromStrava === null) return null;
+ if (fromStrava && fromStrava !== 'touring') return fromStrava;
+ if (fromFile === null) return fromStrava ?? null;
+ return fromFile ?? 'touring';
+}
+
+const fitBikes: Record = { road: 'road', gravel: 'gravel', mtb: 'mtb', bike: 'touring', unknown: 'touring', foot: 'hiking', other: null };
+
+/** A name that the rider knows: not a number such as `12345` or `12345_ACTIVITY`, and not a file name with an email
+ * address. */
+const usable = (name: string | undefined): name is string => !!name && !name.includes('@') && /[^\d\s_.-]/.test(name.replace(/activity/gi, ''));
+/** The name of a ride with no usable name: its activity and its date. */
+export const dateName = (start: number, bike: Bike) =>
+ `${bike === 'hiking' ? 'Hike' : 'Ride'}, ${new Date(start * 1000).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })}`;
+
+/** The key of a ride that starts at a Unix time: `YYYYMMDDTHHMMSSZ`. */
+export const rideKeyAt = (seconds: number) => new Date(Math.floor(seconds) * 1000).toISOString().replace(/[-:]|\.\d+/g, '');
+
+/** The id of a route from a file: a hash of its summary line. */
+export async function lineId(line: number[]): Promise {
+ const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(line))));
+ return `file-${Array.from(hash.slice(0, 16), b => b.toString(16).padStart(2, '0')).join('')}`;
+}
+
+/**
+ * Reads each GPX and FIT file of `items`, also inside folders, ZIP files, a ZIP in a ZIP and `.gz` files, one file at a
+ * time, and gives one `Found` for each. Other files are not counted. A GPX file with a time at each point and a FIT
+ * activity are rides, except a GPX file whose first time is later than now; another file is a route. A ride is known when
+ * its key is stored or deleted, a route when its id is stored, a timed GPX file when either is, and each when an
+ * earlier file of `items` had the same key or id. The names and types of Strava's
+ * `activities.csv` apply to its files.
+ */
+export async function* readFiles(items: Item[], library: Library, readers: Readers, signal: AbortSignal): AsyncGenerator {
+ const sources: Source[] = [], failed: Found[] = [];
+ for (const item of items) {
+ signal.throwIfAborted();
+ await list(item, item instanceof Blob ? item.name : item.fullPath.replace(/^\//, ''), sources, failed, signal);
+ }
+ yield* failed;
+ const activities = new Map();
+ for (const source of sources) if (baseName(source.path).toLowerCase() === 'activities.csv') await strava(source, activities);
+ const deleted = new Set((await library.state('deleted') ?? []).map(d => d.key)), seen = new Set();
+ for (const source of sources) {
+ signal.throwIfAborted();
+ if (!counted.test(source.path)) continue;
+ const name = baseName(source.path), found = { file: source.path, name };
+ const zipped = /\.gz$/i.test(name), plain = zipped ? name.slice(0, -3) : name, fallback = plain.replace(/\.\w+$/, '');
+ const format = plain.slice(-3).toLowerCase() as 'gpx' | 'fit' | 'tcx';
+ const strava = activities.get(name);
+ const content = () => source.get().then(blob => zipped ? gunzip(blob) : blob);
+ // Another error of a reader stops the import.
+ const read = async (): Promise => {
+ const blob = await content().catch(error => { throw new Unreadable(reasonOf(error)); });
+ try { return format === 'gpx' ? readers.gpx(await blob.text(), fallback) : readers.fit(new Uint8Array(await blob.arrayBuffer()), fallback); } catch (error) {
+ const { name, code } = error as { name?: string; code?: string };
+ if (name === 'GpxError') throw new Unreadable(reasons.track);
+ if (name === 'FitError') throw new Unreadable(code === 'fit-no-positions' || code === 'fit-unsupported' ? reasons.track : reasons.damaged);
+ throw error;
+ }
+ };
+ if (format === 'tcx') { yield { ...found, kind: 'unreadable', reason: reasons.tcx }; continue; }
+ let file;
+ try { file = await read(); } catch (error) {
+ if (!(error instanceof Unreadable)) throw error;
+ yield failure(source.path, error);
+ continue;
+ }
+ const timed = 'points' in file && file.points.every(p => p.time !== undefined);
+ const samples = 'samples' in file ? file.samples
+ : file.points.map(p => ({ timeS: p.time ?? 0, lat: p.lat, lon: p.lon, elevationM: p.ele, segmentStart: !!p.segmentStart }));
+ const bike = chooseBike(strava?.type, 'sport' in file ? fitBikes[file.sport] : bikeOf(file.kind));
+ if (bike === null) { yield { ...found, kind: 'unreadable', reason: reasons.sport }; continue; }
+ if (samples.length < 2) { yield { ...found, kind: 'unreadable', reason: reasons.track }; continue; }
+ // A route's summary here gives only its line and its length: the planner makes the stored one.
+ const summary = rideSummary(samples, bike);
+ const key = 'samples' in file || timed ? rideKeyAt(summary.start) : undefined;
+ const id = 'points' in file ? await lineId(summary.line) : undefined;
+ // A timed GPX file is known when either of its forms is stored or came before.
+ const known = (key !== undefined && (seen.has(key) || deleted.has(key) || !!await library.ride(key)))
+ || (id !== undefined && (seen.has(id) || !!await library.item(id)));
+ for (const value of [key, id]) if (value) seen.add(value);
+ if (known) { yield { ...found, kind: 'known' }; continue; }
+ let ride: (Found & { kind: 'ride' }) | undefined, route: (Found & { kind: 'route' }) | undefined;
+ if (key) {
+ const title = [strava?.name, 'name' in file ? file.name : fallback].find(usable) ?? dateName(summary.start, bike);
+ ride = { ...found, name: title, kind: 'ride', open: content, ride: { key, name: title, source: 'file', format: format as 'gpx' | 'fit',
+ summary, maxHr: settings.maxHr?.value ?? null, ftp: settings.ftp?.value ?? null } };
+ }
+ if (id) {
+ const title = usable((file as Track).name) ? (file as Track).name : 'Planned route';
+ route = { ...found, name: title, kind: 'route', id, lengthM: summary.lengthM, bike, open: async () => ({ ...await read() as Track, name: title }) };
+ }
+ if (ride && route) { ride.other = route; route.other = ride; }
+ // A timed file that starts later than now is a planned tour.
+ yield route && (!ride || summary.start > Date.now() / 1000) ? route : ride!;
+ }
+}
diff --git a/builder/web/src/lib/library/records.ts b/builder/web/src/lib/library/records.ts
new file mode 100644
index 0000000000..3f1fc45db4
--- /dev/null
+++ b/builder/web/src/lib/library/records.ts
@@ -0,0 +1,218 @@
+/** The records of the library database, and the checks that a record read from a file or the database has their fields. */
+
+export const bikes = ['road', 'gravel', 'touring', 'mtb', 'hiking'] as const;
+export type Bike = typeof bikes[number];
+
+/** The simplified line and the numbers of a route or a ride, so that a list or a map needs no other data. */
+export interface Summary {
+ /** Longitude, latitude, longitude, latitude, …, rounded to 5 decimals: the simplified line of `summarize`. */
+ line: number[];
+ /** The height in metres of each point of `line`, or null where it is not known. */
+ heights: (number | null)[];
+ /** West, south, east, north of the whole line, before it was simplified. */
+ bounds: [number, number, number, number];
+ lengthM: number;
+ climbM: number;
+ /** The highest point of the whole line, or null when no height is known. */
+ highestM: number | null;
+ seconds: number;
+ bike: Bike;
+}
+
+/** `seconds` is the riding time that the routing gives. */
+export interface RouteSummary extends Summary {
+ days: number;
+}
+
+/** `seconds` is the whole time from the first point to the last. */
+export interface RideSummary extends Summary {
+ /** Unix seconds of the first point. */
+ start: number;
+ movingS: number;
+}
+
+export interface RouteRecord {
+ id: string;
+ revision: number;
+ name: string;
+ updatedAt: number;
+ /** The id of the saved version that `trip` belongs to. */
+ open?: string;
+ /** Null only while the plan never had a calculated line. */
+ summary: RouteSummary | null;
+ /** The planner checks a plan when it opens it. */
+ trip: unknown;
+}
+
+export interface RideRecord {
+ /** The UTC time of the first point, `YYYYMMDDTHHMMSSZ`. Two files with the same key are the same ride. */
+ key: string;
+ name: string;
+ source: 'device' | 'file';
+ format: 'obcride' | 'fit' | 'gpx';
+ summary: RideSummary;
+ maxHr: number | null;
+ ftp: number | null;
+ /** The trip of the device that the ride belongs to. */
+ trip?: RideTrip;
+ /** `storeId:objectId` of the ride on the device: a card gets a new `StoreId` when it is initialized, and it never
+ * gives an `ObjectId` again. */
+ device?: string;
+}
+
+/** `key` is the trip key of the device in decimal; `day` counts from 1. */
+export interface RideTrip {
+ key: string;
+ day: number;
+ name: string;
+}
+
+/**
+ * The place of each point of the summary line in a cover image, 9 bytes for each point (`pack` of `lib/covers/line.ts`).
+ * `x` and `y` are pixels of the image; a point beside the eye can be millions of pixels outside it. In `eye`, the low
+ * 7 bits code the distance from the eye, 0 where the point has no place (behind the eye, or terrain with no data), and
+ * the high bit is set where the point is visible.
+ */
+export interface CoverPoints { x: Float32Array; y: Float32Array; eye: Uint8Array }
+
+/**
+ * The cover of a route or a ride. `state` and `tries` belong to `lineKey`, the `coverKey` of the route or the ride when
+ * the cover job last worked on it. `waiting`: the job renders it again; `none`: no cover is possible for this line, as no
+ * view holds it or TrailView has no data there; `failed`: three tries failed. With `waiting` and `failed`, `image` and
+ * `points` can be the cover of an earlier line.
+ */
+export interface CoverRecord {
+ /** The id of the route or the key of the ride. */
+ id: string;
+ lineKey: string;
+ state: 'waiting' | 'done' | 'failed' | 'none';
+ image?: Blob;
+ points?: CoverPoints;
+ /** The credits of the data in `image`, as `still` gives them. A cover made before they were kept has none. */
+ credits?: string[];
+ tries: number;
+ /** The picture of the map for a card whose record gets no cover. */
+ map?: MapPicture;
+}
+
+/**
+ * A still picture of the planner map around the summary line, with no labels, in each theme. `tries` belongs to
+ * `lineKey`, as in a cover; `none`: the line is outside the map data. Both images share `points` and `credits`.
+ */
+export interface MapPicture {
+ lineKey: string;
+ tries: number;
+ none?: true;
+ points?: CoverPoints;
+ credits?: string[];
+ light?: Blob;
+ dark?: Blob;
+}
+
+export interface DeletedRide {
+ key: string;
+ device?: string;
+}
+
+/** A route on a device: `storeId:objectId` of its object, as the `device` of a ride, and the `sentKey` of the route when it
+ * was sent. */
+export interface SentRoute {
+ device: string;
+ key: string;
+}
+
+/** A box of a map area, in whole microdegrees. */
+export interface MapBox { minLat: number; minLon: number; maxLat: number; maxLon: number }
+
+/** The area and the colours of the map that the rider chose for the device and that is not sent yet. */
+export interface NextMap {
+ /** Ids of regions of the map catalog. */
+ regions: string[];
+ boxes: MapBox[];
+ /** The ids of the map styles for the day and for the night. */
+ light: string;
+ dark: string;
+ /** The size of the download of the whole map. */
+ bytes: number;
+}
+
+/** The values of the `state` store. */
+export interface LibraryState {
+ /** The route that the planner opens. */
+ active: string | null;
+ /** Routes that wait to go to the device. */
+ waiting: string[];
+ /** Routes to remove from the device. */
+ leaving: string[];
+ /** The routes sent to a device, by route id. */
+ sent: Record;
+ /** Rides that the rider deleted; no import adds them again. */
+ deleted: DeletedRide[];
+ /** Rides that the rider took out of their group; no ride joins them. */
+ apart: string[];
+ nextMap: NextMap | null;
+}
+
+export const rideKey = /^\d{8}T\d{6}Z$/;
+
+const isNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);
+const isString = (value: unknown): value is string => typeof value === 'string';
+const optional = (value: unknown, check: (value: unknown) => boolean) => value === undefined || check(value);
+const isRecord = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value);
+const isStrings = (value: unknown): value is string[] => Array.isArray(value) && value.every(isString);
+
+function isSummary(value: unknown): value is Summary {
+ if (!isRecord(value)) return false;
+ const { line, heights, bounds } = value;
+ return Array.isArray(line) && line.length % 2 === 0 && line.every(isNumber)
+ && Array.isArray(heights) && heights.length * 2 === line.length && heights.every(h => h === null || isNumber(h))
+ && Array.isArray(bounds) && bounds.length === 4 && bounds.every(isNumber)
+ && [value.lengthM, value.climbM, value.seconds].every(isNumber) && (value.highestM === null || isNumber(value.highestM))
+ && bikes.includes(value.bike as Bike);
+}
+
+export const isRouteSummary = (value: unknown): value is RouteSummary =>
+ isSummary(value) && Number.isInteger((value as RouteSummary).days) && (value as RouteSummary).days >= 1;
+
+export const isRideSummary = (value: unknown): value is RideSummary =>
+ isSummary(value) && isNumber((value as RideSummary).start) && isNumber((value as RideSummary).movingS);
+
+export function isRouteRecord(value: unknown): value is RouteRecord {
+ return isRecord(value) && isString(value.id) && !!value.id && Number.isInteger(value.revision) && (value.revision as number) >= 0
+ && isString(value.name) && isNumber(value.updatedAt) && optional(value.open, isString)
+ && (value.summary === null || isRouteSummary(value.summary)) && value.trip !== undefined;
+}
+
+export function isRideRecord(value: unknown): value is RideRecord {
+ return isRecord(value) && isString(value.key) && rideKey.test(value.key) && isString(value.name)
+ && ['device', 'file'].includes(value.source as string) && ['obcride', 'fit', 'gpx'].includes(value.format as string)
+ && isRideSummary(value.summary) && (value.maxHr === null || isNumber(value.maxHr)) && (value.ftp === null || isNumber(value.ftp))
+ && optional(value.trip, isTrip) && optional(value.device, isString);
+}
+
+const isTrip = (value: unknown): value is RideTrip => isRecord(value) && isString(value.key) && /^[1-9]\d*$/.test(value.key)
+ && Number.isInteger(value.day) && (value.day as number) >= 1 && isString(value.name);
+
+const isSent = (value: unknown): value is Record => isRecord(value)
+ && Object.values(value).every(route => isRecord(route) && isString(route.device) && isString(route.key));
+
+const isDeleted = (value: unknown): value is DeletedRide =>
+ isRecord(value) && isString(value.key) && rideKey.test(value.key) && optional(value.device, isString);
+
+const isBox = (value: unknown): value is MapBox =>
+ isRecord(value) && [value.minLat, value.minLon, value.maxLat, value.maxLon].every(Number.isInteger)
+ && (value.minLat as number) < (value.maxLat as number) && (value.minLon as number) < (value.maxLon as number);
+
+const isNextMap = (value: unknown): value is NextMap => isRecord(value) && isStrings(value.regions)
+ && Array.isArray(value.boxes) && value.boxes.every(isBox) && isString(value.light) && isString(value.dark) && isNumber(value.bytes);
+
+/** The check of each value of the `state` store. */
+export const stateChecks: { [K in keyof LibraryState]: (value: unknown) => value is LibraryState[K] } = {
+ active: (value): value is string | null => value === null || isString(value),
+ waiting: isStrings,
+ leaving: isStrings,
+ sent: isSent,
+ deleted: (value): value is DeletedRide[] => Array.isArray(value) && value.every(isDeleted),
+ apart: isStrings,
+ nextMap: (value): value is NextMap | null => value === null || isNextMap(value),
+};
diff --git a/builder/web/src/lib/library/statistics.test.ts b/builder/web/src/lib/library/statistics.test.ts
new file mode 100644
index 0000000000..9fa0cf8e28
--- /dev/null
+++ b/builder/web/src/lib/library/statistics.test.ts
@@ -0,0 +1,14 @@
+import { describe, expect, it } from 'vitest';
+import type { Bike, RideRecord } from './records';
+import { yearTotals } from './statistics';
+
+const ride = (start: Date, lengthM: number, bike: Bike = 'road') => ({ summary: { start: start.getTime() / 1000, lengthM, bike } }) as RideRecord;
+
+describe('yearTotals', () => {
+ it('counts each ride in the year of its local start, and a hike apart', () => {
+ const rides = [ride(new Date(2025, 11, 31, 23, 30), 40_000), ride(new Date(2026, 0, 1, 0, 30), 30_000),
+ ride(new Date(2026, 5, 1), 12_000, 'hiking'), ride(new Date(2026, 11, 31, 23, 59), 50_000)];
+ expect(yearTotals(rides, 2025)).toEqual({ lengthM: 40_000, rides: 1, hikes: 0 });
+ expect(yearTotals(rides, 2026)).toEqual({ lengthM: 92_000, rides: 2, hikes: 1 });
+ });
+});
diff --git a/builder/web/src/lib/library/statistics.ts b/builder/web/src/lib/library/statistics.ts
new file mode 100644
index 0000000000..1b4db74137
--- /dev/null
+++ b/builder/web/src/lib/library/statistics.ts
@@ -0,0 +1,23 @@
+/** The totals of the rides over a time. */
+import type { RideRecord } from './records';
+
+export interface Totals {
+ /** The length of the rides and the hikes. */
+ lengthM: number;
+ /** The count by bike. */
+ rides: number;
+ /** The count on foot. */
+ hikes: number;
+}
+
+/** The totals of the rides that start in `year`, local time. */
+export function yearTotals(rides: RideRecord[], year: number): Totals {
+ const totals: Totals = { lengthM: 0, rides: 0, hikes: 0 };
+ for (const { summary } of rides) {
+ if (new Date(summary.start * 1000).getFullYear() !== year) continue;
+ totals.lengthM += summary.lengthM;
+ if (summary.bike === 'hiking') totals.hikes++;
+ else totals.rides++;
+ }
+ return totals;
+}
diff --git a/builder/web/src/lib/library/store.test.ts b/builder/web/src/lib/library/store.test.ts
new file mode 100644
index 0000000000..ffdf47508b
--- /dev/null
+++ b/builder/web/src/lib/library/store.test.ts
@@ -0,0 +1,113 @@
+import { IDBFactory } from 'fake-indexeddb';
+import { describe, expect, it } from 'vitest';
+import type { RideRecord, RouteRecord } from './records';
+import { Library } from './store';
+import { summarize } from './summary';
+
+const route = (id: string): RouteRecord => ({ id, revision: 0, name: id, updatedAt: 1, summary: null, trip: { points: [] } });
+
+const ride = (key: string, device?: string): RideRecord => ({
+ key, name: key, source: device ? 'device' : 'file', format: 'gpx', maxHr: 180, ftp: null, ...device && { device },
+ summary: summarize([[8, 47, 400], [8.01, 47, 420]], { lengthM: 760, climbM: 20, seconds: 300, movingS: 280, start: 1_700_000_000, bike: 'gravel' }),
+});
+
+describe('library store', () => {
+ it('saves routes in order, refuses an unseen edit from another tab, and removes the versions and the active pointer', async () => {
+ const factory = new IDBFactory(), first = new Library(factory), second = new Library(factory);
+ const saved = await first.saveRoute(route('a'), [{ id: 'v' }]);
+ await first.setState('active', saved.id);
+ const stale = (await second.route('a'))!;
+ await Promise.all([first.saveRoute({ ...saved, updatedAt: 2 }), first.saveRoute({ ...saved, updatedAt: 3 })]);
+ expect((await first.routes())[0]).toMatchObject({ updatedAt: 3, revision: 3 });
+ expect(await first.versions('a')).toEqual([{ id: 'v' }]);
+ await expect(second.saveRoute({ ...stale, name: 'Unseen' })).rejects.toThrow('another tab');
+ await expect(second.removeRoute('a', stale.revision)).rejects.toThrow('changed');
+ await second.removeRoute('a', (await second.route('a'))!.revision);
+ expect([await first.routes(), await first.versions('a'), await first.state('active')]).toEqual([[], [], null]);
+ await first.close(); await second.close();
+ });
+
+ it('adds a route only when its id is not stored', async () => {
+ const library = new Library(new IDBFactory());
+ expect(await library.addRoute(route('file-a'))).toBe(true);
+ expect(await library.addRoute({ ...route('file-a'), name: 'Other' })).toBe(false);
+ expect((await library.routes()).map(r => r.name)).toEqual(['file-a']);
+ await library.close();
+ });
+
+ it('keeps a rename over a save that was queued before it', async () => {
+ const library = new Library(new IDBFactory()), saved = await library.saveRoute(route('a'));
+ const [renamed, later] = await Promise.all([library.renameRoute('a', 'Lake loop'), library.saveRoute({ ...saved, updatedAt: 5 })]);
+ expect(renamed).toMatchObject({ name: 'Lake loop', revision: 2 });
+ expect(later).toMatchObject({ name: 'Lake loop', revision: 3, updatedAt: 5 });
+ expect(await library.route('a')).toMatchObject({ name: 'Lake loop', revision: 3 });
+ await expect(library.renameRoute('gone', 'x')).rejects.toThrow('not in the library');
+ await library.renameRoute('a', 'Lake round');
+ // The copy of the route still has revision 1: the tab knows the revisions of its own save and rename.
+ await library.removeRoute('a', saved.revision);
+ expect(await library.route('a')).toBeUndefined();
+ await library.close();
+ });
+
+ it('does not hide a save of another tab behind a rename', async () => {
+ const factory = new IDBFactory(), stale = new Library(factory), other = new Library(factory);
+ const saved = await stale.saveRoute(route('a'));
+ await other.saveRoute({ ...(await other.route('a'))!, trip: { points: [], edited: true } });
+ expect(await stale.renameRoute('a', 'Lake loop')).toMatchObject({ name: 'Lake loop', revision: 3 });
+ await expect(stale.saveRoute({ ...saved, updatedAt: 2 })).rejects.toThrow('another tab');
+ await expect(stale.removeRoute('a', saved.revision)).rejects.toThrow('changed');
+ expect(await other.route('a')).toMatchObject({ name: 'Lake loop', trip: { edited: true } });
+ await stale.close(); await other.close();
+ });
+
+ it('changes a state value in one transaction, and a removed route stops waiting and leaves the device', async () => {
+ const library = new Library(new IDBFactory()), heard: string[] = [];
+ library.onChange((store, key) => heard.push(`${store}:${key}`));
+ await library.saveRoute(route('a'));
+ const add = (id: string) => library.changeState('waiting', ids => [...ids ?? [], id]);
+ await Promise.all([add('a'), add('b')]);
+ expect(await library.state('waiting')).toEqual(['a', 'b']);
+ await library.removeRoute('a');
+ expect(await library.state('waiting')).toEqual(['b']);
+ expect(heard).toEqual(['routes:a', 'state:waiting', 'state:waiting', 'routes:a', 'state:waiting']);
+ // Only a route on the device has to leave it.
+ expect(await library.state('leaving')).toBeUndefined();
+ await library.saveRoute(route('c'));
+ await library.setState('sent', { c: { device: '1:7', key: 'k' } });
+ await library.removeRoute('c');
+ expect(await library.state('leaving')).toEqual(['c']);
+ await library.close();
+ });
+
+ it('adds a ride once, and refuses a stored or a deleted key but keeps its device id', async () => {
+ const library = new Library(new IDBFactory()), file = new Blob(['ride']);
+ expect(await library.addRide(ride('20260801T070000Z'), file)).toBe(true);
+ expect(await library.addRide(ride('20260801T070000Z', '1:5'), new Blob(['other']))).toBe(false);
+ expect(await (await library.rideFile('20260801T070000Z'))!.text()).toBe('ride');
+ expect((await library.ride('20260801T070000Z'))!.device).toBe('1:5');
+
+ expect(await library.addRide(ride('20260802T070000Z'), file)).toBe(true);
+ await library.removeRide('20260802T070000Z');
+ expect(await library.addRide(ride('20260802T070000Z', '1:6'), file)).toBe(false);
+ expect(await library.ride('20260802T070000Z')).toBeUndefined();
+ expect(await library.state('deleted')).toEqual([{ key: '20260802T070000Z', device: '1:6' }]);
+ expect(await library.deviceRides()).toEqual(new Set(['1:5', '1:6']));
+ await library.close();
+ });
+
+ it('clears all stores after the writes before it, and then refuses each write', async () => {
+ const factory = new IDBFactory(), library = new Library(factory);
+ await library.saveRoute(route('a'), [{ id: 'v' }]);
+ await library.addRide(ride('20260801T070000Z'), new Blob(['ride']));
+ await library.saveCover({ id: 'a', lineKey: 'k', state: 'none', tries: 0 });
+ await library.setState('active', 'a');
+ const before = library.saveRoute(route('b'));
+ await library.clear();
+ await expect(before).resolves.toMatchObject({ id: 'b' });
+ await expect(library.saveRoute(route('c'))).rejects.toThrow('deleted');
+ const fresh = new Library(factory), contents = await fresh.contents();
+ expect([contents.routes, contents.versions, contents.rides, contents.files.size, contents.state, await fresh.cover('a')])
+ .toEqual([[], {}, [], 0, {}, undefined]);
+ await library.close(); await fresh.close();
+ });
+});
diff --git a/builder/web/src/lib/library/store.ts b/builder/web/src/lib/library/store.ts
new file mode 100644
index 0000000000..8f77b2d806
--- /dev/null
+++ b/builder/web/src/lib/library/store.ts
@@ -0,0 +1,402 @@
+/** Keeps the routes, the rides, their source files, the covers and the library state in the browser database `obc-library`. */
+import { isRideRecord, isRouteRecord, stateChecks, type CoverRecord, type LibraryState, type RideRecord, type RouteRecord } from './records';
+
+export type StoreName = 'routes' | 'versions' | 'rides' | 'ride-files' | 'covers' | 'state';
+
+/** All records of the library except the covers: the content of a backup. */
+export interface Contents {
+ routes: RouteRecord[];
+ /** The versions of each route, by route id. */
+ versions: Record;
+ rides: RideRecord[];
+ /** The source file of each ride, by ride key. */
+ files: Map;
+ state: Partial;
+}
+
+type Fail = (error: unknown) => void;
+
+const conflict = () => new Error('This route changed in another tab. Download your edits before reopening it.');
+const STORES: StoreName[] = ['routes', 'versions', 'rides', 'ride-files', 'covers', 'state'];
+
+/** Writes are ordered within a tab; revisions prevent a second tab from replacing unseen edits of a route. */
+export class Library {
+ private database?: Promise;
+ private pending: Promise = Promise.resolve();
+ private revisions = new Map();
+ private listeners = new Set<(store: StoreName, key: string) => void>();
+ private written = false;
+ private cleared = false;
+
+ /** Without `factory`, `open` reads `indexedDB`, so a browser that blocks storage gives a rejected promise. */
+ constructor(private factory?: IDBFactory) {}
+
+ private open(): Promise {
+ return this.database ??= new Promise((resolve, reject) => {
+ const request = (this.factory ?? indexedDB).open('obc-library', 1);
+ request.onupgradeneeded = () => {
+ const db = request.result;
+ db.createObjectStore('routes', { keyPath: 'id' });
+ db.createObjectStore('rides', { keyPath: 'key' });
+ db.createObjectStore('covers', { keyPath: 'id' });
+ for (const store of ['versions', 'ride-files', 'state']) db.createObjectStore(store);
+ };
+ request.onsuccess = () => {
+ const db = request.result;
+ db.onversionchange = () => db.close();
+ resolve(db);
+ };
+ request.onerror = () => reject(request.error);
+ request.onblocked = () => reject(new Error('Close other tabs of the app and try again.'));
+ }).catch(error => { this.database = undefined; throw error; });
+ }
+
+ /** Runs `work` in one transaction and resolves with the value of the function it returns, after the commit. */
+ private async run(stores: StoreName[], mode: IDBTransactionMode, work: (tx: IDBTransaction, fail: Fail) => () => T,
+ durability: IDBTransactionDurability = 'default'): Promise {
+ const db = await this.open();
+ return new Promise((resolve, reject) => {
+ const tx = db.transaction(stores, mode, { durability });
+ let failure: unknown, result: () => T = () => undefined as T;
+ const fail: Fail = error => { failure = error; tx.abort(); };
+ try { result = work(tx, fail); } catch (error) { fail(error); }
+ tx.oncomplete = () => resolve(result());
+ tx.onabort = () => reject(failure ?? tx.error);
+ });
+ }
+
+ private read(store: StoreName, key?: string): Promise {
+ return this.run([store], 'readonly', tx => {
+ const request = key === undefined ? tx.objectStore(store).getAll() : tx.objectStore(store).get(key);
+ return () => request.result;
+ });
+ }
+
+ /** A write in the order of this tab. `changed` names each record that it writes, for the listeners of `onChange`. */
+ private write(stores: StoreName[], work: (tx: IDBTransaction, fail: Fail, changed: (store: StoreName, key: string) => void) => () => T,
+ durability?: IDBTransactionDurability): Promise {
+ const result = this.pending.then(async () => {
+ if (this.cleared) throw new Error('The library was deleted. Reload the page.');
+ const changes: [StoreName, string][] = [];
+ const value = await this.run(stores, 'readwrite', (tx, fail) => work(tx, fail, (store, key) => changes.push([store, key])), durability);
+ for (const [store, key] of changes) for (const listener of this.listeners) listener(store, key);
+ if (!this.written) { this.written = true; void this.persist(); }
+ return value;
+ });
+ this.pending = result.catch(() => {});
+ return result;
+ }
+
+ /** Asks the browser to keep the library when the disk is full. Firefox asks the rider. */
+ async persist(): Promise {
+ try { return await navigator.storage?.persist?.() ?? false; } catch { return false; }
+ }
+
+ /** Calls `listener` after each record that this tab writes or removes. Returns the function that stops it. */
+ onChange(listener: (store: StoreName, key: string) => void): () => void {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ }
+
+ async routes(): Promise {
+ await this.pending;
+ return (await this.read('routes') as unknown[]).filter(isRouteRecord);
+ }
+
+ /** The ids of the records of `routes` that are not route records. `routes()` and a backup leave them out. */
+ async unreadableRoutes(): Promise {
+ await this.pending;
+ return this.run(['routes'], 'readonly', tx => {
+ const keys = tx.objectStore('routes').getAllKeys(), values = tx.objectStore('routes').getAll();
+ return () => keys.result.filter((_, i) => !isRouteRecord(values.result[i])) as string[];
+ });
+ }
+
+ async route(id: string): Promise {
+ const route = await this.read('routes', id);
+ if (route === undefined) return undefined;
+ if (!isRouteRecord(route)) throw new Error('This saved route cannot be read.');
+ this.revisions.set(id, route.revision);
+ return route;
+ }
+
+ /** The saved versions of a route, newest first. The planner checks them. */
+ async versions(id: string): Promise {
+ const versions = await this.read('versions', id);
+ return Array.isArray(versions) ? versions : [];
+ }
+
+ /** Saves the route with the next revision, and its versions when they are given. It refuses a route that another tab
+ * saved after this tab read it. A stored route keeps its stored name: only `renameRoute` changes it, so a save that
+ * was queued before a rename does not write the old name. */
+ saveRoute(route: R, versions?: unknown[]): Promise {
+ const snapshot = structuredClone(route), kept = versions && structuredClone(versions);
+ return this.write(kept ? ['routes', 'versions'] : ['routes'], (tx, fail, changed) => {
+ const store = tx.objectStore('routes'), request = store.get(snapshot.id);
+ const expected = Math.max(this.revisions.get(snapshot.id) ?? 0, snapshot.revision);
+ const next = { ...snapshot, revision: expected + 1 };
+ request.onsuccess = () => {
+ if ((request.result?.revision ?? 0) !== expected) return fail(conflict());
+ if (request.result) next.name = request.result.name;
+ try {
+ store.put(next);
+ if (kept) tx.objectStore('versions').put(kept, next.id);
+ changed('routes', next.id);
+ } catch (error) { fail(error); }
+ };
+ return () => { this.revisions.set(next.id, next.revision); return next; };
+ });
+ }
+
+ /** Adds a route as it is. False when its id is stored: one transaction checks and writes, so two tabs add it once. */
+ addRoute(route: RouteRecord): Promise {
+ const record = structuredClone(route);
+ return this.write(['routes'], (tx, _, changed) => {
+ const store = tx.objectStore('routes'), stored = store.getKey(record.id);
+ stored.onsuccess = () => {
+ if (stored.result !== undefined) return;
+ store.put(record);
+ changed('routes', record.id);
+ };
+ return () => stored.result === undefined;
+ });
+ }
+
+ /** Gives a stored route a new name and the next revision. This tab then knows the new revision only when it knew the
+ * stored one, so a rename does not hide a save of another tab from a later save or removal of this tab. */
+ renameRoute(id: string, name: string): Promise {
+ return this.write(['routes'], (tx, fail, changed) => {
+ const store = tx.objectStore('routes'), request = store.get(id);
+ let next: RouteRecord, current = false;
+ request.onsuccess = () => {
+ if (!isRouteRecord(request.result)) return fail(new Error('This route is not in the library.'));
+ current = this.revisions.get(id) === request.result.revision;
+ next = { ...request.result, name, revision: request.result.revision + 1, updatedAt: Date.now() };
+ store.put(next);
+ changed('routes', id);
+ };
+ return () => { if (current) this.revisions.set(id, next.revision); return next; };
+ });
+ }
+
+ /** Removes a route with its versions and its cover, and takes it out of the routes that wait for the device. A route
+ * on the device goes into `leaving`, so the next sync removes it there. With `revision`, it refuses a route that
+ * changed since then, or since the newest revision that this tab knows, as `saveRoute` does. */
+ removeRoute(id: string, revision?: number): Promise {
+ return this.write(['routes', 'versions', 'covers', 'state'], (tx, fail, changed) => {
+ const store = tx.objectStore('routes'), request = store.get(id), state = tx.objectStore('state');
+ request.onsuccess = () => {
+ if (revision !== undefined && request.result && request.result.revision !== Math.max(this.revisions.get(id) ?? 0, revision)) return fail(conflict());
+ store.delete(id);
+ tx.objectStore('versions').delete(id);
+ tx.objectStore('covers').delete(id);
+ changed('routes', id);
+ };
+ const active = state.get('active'), waiting = state.get('waiting'), sent = state.get('sent'), leaving = state.get('leaving');
+ active.onsuccess = () => { if (active.result === id) state.put(null, 'active'); };
+ waiting.onsuccess = () => {
+ if (!stateChecks.waiting(waiting.result) || !waiting.result.includes(id)) return;
+ state.put(waiting.result.filter(other => other !== id), 'waiting');
+ changed('state', 'waiting');
+ };
+ leaving.onsuccess = () => {
+ const ids = stateChecks.leaving(leaving.result) ? leaving.result : [];
+ if (!stateChecks.sent(sent.result) || !Object.hasOwn(sent.result, id) || ids.includes(id)) return;
+ state.put([...ids, id], 'leaving');
+ changed('state', 'leaving');
+ };
+ return () => {};
+ });
+ }
+
+ /** A route or a ride by its id or key. It does not record the revision as `route` does, so a reader such as the cover
+ * job does not hide the edits of another tab from the planner. */
+ async item(id: string): Promise {
+ const route = await this.read('routes', id);
+ return isRouteRecord(route) ? route : this.ride(id);
+ }
+
+ async rides(): Promise {
+ await this.pending;
+ return (await this.read('rides') as unknown[]).filter(isRideRecord);
+ }
+
+ async ride(key: string): Promise {
+ const ride = await this.read('rides', key);
+ return isRideRecord(ride) ? ride : undefined;
+ }
+
+ /** The source file of a ride, unchanged. */
+ async rideFile(key: string): Promise {
+ const file = await this.read('ride-files', key);
+ return file instanceof Blob ? file : undefined;
+ }
+
+ /** Replaces the record of a stored ride, for example after a new name. */
+ saveRide(ride: RideRecord): Promise {
+ const record = structuredClone(ride);
+ return this.write(['rides'], (tx, _, changed) => {
+ tx.objectStore('rides').put(record);
+ changed('rides', record.key);
+ return () => {};
+ });
+ }
+
+ /** Adds a ride and its source file. False when the key is stored or deleted: then it only writes the device id of
+ * `ride`, so `deviceRides` skips it. One transaction checks and writes, so two tabs add a ride once. It resolves only
+ * after the data is on disk, as the device sync marks the ride as taken on the device after it. */
+ addRide(ride: RideRecord, file: Blob): Promise {
+ const record = structuredClone(ride);
+ return this.write(['rides', 'ride-files', 'state'], (tx, _, changed) => {
+ const rides = tx.objectStore('rides'), state = tx.objectStore('state');
+ const stored = rides.get(record.key), list = state.get('deleted');
+ let added = false;
+ list.onsuccess = () => {
+ const deleted = stateChecks.deleted(list.result) ? list.result : [];
+ const gone = deleted.find(d => d.key === record.key), device = record.device;
+ if (stored.result) {
+ if (device && stored.result.device !== device) rides.put({ ...stored.result, device });
+ } else if (gone) {
+ if (device && gone.device !== device) state.put(deleted.map(d => d === gone ? { ...d, device } : d), 'deleted');
+ } else {
+ rides.put(record);
+ tx.objectStore('ride-files').put(file, record.key);
+ changed('rides', record.key);
+ added = true;
+ }
+ };
+ return () => added;
+ }, 'strict');
+ }
+
+ /** Removes a ride, its file and its cover, and adds its key to the deleted rides. */
+ removeRide(key: string): Promise {
+ return this.write(['rides', 'ride-files', 'covers', 'state'], (tx, _, changed) => {
+ const state = tx.objectStore('state'), ride = tx.objectStore('rides').get(key), list = state.get('deleted');
+ list.onsuccess = () => {
+ const deleted = stateChecks.deleted(list.result) ? list.result : [];
+ const device: string | undefined = ride.result?.device;
+ if (!deleted.some(d => d.key === key)) state.put([...deleted, { key, ...device && { device } }], 'deleted');
+ tx.objectStore('rides').delete(key);
+ tx.objectStore('ride-files').delete(key);
+ tx.objectStore('covers').delete(key);
+ changed('rides', key);
+ };
+ return () => {};
+ });
+ }
+
+ /** The device ids of the stored and the deleted rides: the rides on the device to skip. */
+ async deviceRides(): Promise> {
+ const [rides, deleted] = await Promise.all([this.rides(), this.state('deleted')]);
+ return new Set([...rides, ...deleted ?? []].flatMap(ride => ride.device ? [ride.device] : []));
+ }
+
+ async cover(id: string): Promise {
+ return await this.read('covers', id) as CoverRecord | undefined;
+ }
+
+ /** Saves a cover only while its route or ride exists: a cover that renders while the rider deletes its record is dropped. */
+ saveCover(cover: CoverRecord): Promise {
+ return this.write(['covers', 'routes', 'rides'], (tx, _, changed) => {
+ const route = tx.objectStore('routes').getKey(cover.id), ride = tx.objectStore('rides').getKey(cover.id);
+ ride.onsuccess = () => {
+ if (route.result === undefined && ride.result === undefined) return;
+ tx.objectStore('covers').put(cover);
+ changed('covers', cover.id);
+ };
+ return () => {};
+ });
+ }
+
+ async state(key: K): Promise {
+ const value = await this.read('state', key);
+ return stateChecks[key](value) ? value as LibraryState[K] : undefined;
+ }
+
+ setState(key: K, value: LibraryState[K]): Promise {
+ return this.write(['state'], (tx, _, changed) => {
+ tx.objectStore('state').put(value, key);
+ changed('state', key);
+ return () => {};
+ });
+ }
+
+ /** Reads a state value and writes `change` of it, in one transaction, so two changes of one tab or of two tabs do not
+ * lose each other. */
+ changeState(key: K, change: (value: LibraryState[K] | undefined) => LibraryState[K]): Promise {
+ return this.write(['state'], (tx, fail, changed) => {
+ const store = tx.objectStore('state'), request = store.get(key);
+ let next: LibraryState[K];
+ request.onsuccess = () => {
+ try {
+ next = change(stateChecks[key](request.result) ? request.result as LibraryState[K] : undefined);
+ store.put(next, key);
+ changed('state', key);
+ } catch (error) { fail(error); }
+ };
+ return () => next;
+ });
+ }
+
+ /** All records except the covers, read in one transaction. */
+ contents(): Promise {
+ return this.run(['routes', 'versions', 'rides', 'ride-files', 'state'], 'readonly', tx => {
+ const all = (store: StoreName) => ({ keys: tx.objectStore(store).getAllKeys(), values: tx.objectStore(store).getAll() });
+ const routes = tx.objectStore('routes').getAll(), rides = tx.objectStore('rides').getAll();
+ const versions = all('versions'), files = all('ride-files'), state = all('state');
+ const pairs = ({ keys, values }: ReturnType) => keys.result.map((key, i) => [key as string, values.result[i]] as const);
+ return () => ({
+ routes: routes.result.filter(isRouteRecord),
+ versions: Object.fromEntries(pairs(versions).filter(([, value]) => Array.isArray(value))) as Record,
+ rides: rides.result.filter(isRideRecord),
+ files: new Map(pairs(files).filter((pair): pair is readonly [string, Blob] => pair[1] instanceof Blob)),
+ state: Object.fromEntries(pairs(state).filter(([key, value]) => Object.hasOwn(stateChecks, key) && stateChecks[key as keyof LibraryState](value))),
+ });
+ });
+ }
+
+ /** Adds in one transaction each route whose id is new, and each ride whose key is neither stored nor deleted. It takes
+ * the state of `contents` only when the library is empty: no route, no ride and no deleted ride. */
+ merge(contents: Contents): Promise<{ routes: number; rides: number; empty: boolean }> {
+ // Strict, as in `addRide`: the device sync can mark a restored device ride as taken after this commit.
+ return this.write(['routes', 'versions', 'rides', 'ride-files', 'state'], (tx, _, changed) => {
+ const routes = tx.objectStore('routes'), rides = tx.objectStore('rides'), state = tx.objectStore('state');
+ const routeIds = routes.getAllKeys(), rideKeys = rides.getAllKeys(), list = state.get('deleted');
+ const result = { routes: 0, rides: 0, empty: false };
+ list.onsuccess = () => {
+ const local = stateChecks.deleted(list.result) ? list.result : [];
+ result.empty = !routeIds.result.length && !rideKeys.result.length && !local.length;
+ if (result.empty) for (const [key, value] of Object.entries(contents.state)) state.put(value, key);
+ const deleted = result.empty ? contents.state.deleted ?? [] : local;
+ const skip = new Set([...rideKeys.result, ...deleted.map(d => d.key)]), known = new Set(routeIds.result);
+ for (const route of contents.routes) {
+ if (known.has(route.id)) continue;
+ routes.put(route);
+ if (contents.versions[route.id]) tx.objectStore('versions').put(contents.versions[route.id], route.id);
+ changed('routes', route.id);
+ result.routes++;
+ }
+ for (const ride of contents.rides) {
+ if (skip.has(ride.key)) continue;
+ rides.put(ride);
+ tx.objectStore('ride-files').put(contents.files.get(ride.key), ride.key);
+ changed('rides', ride.key);
+ result.rides++;
+ }
+ };
+ return () => result;
+ }, 'strict');
+ }
+
+ /** Empties all stores after the writes before it. After it commits, this object refuses each write, so a later save
+ * of a page brings nothing back: the page reloads. */
+ clear(): Promise {
+ return this.write(STORES, tx => {
+ for (const store of STORES) tx.objectStore(store).clear();
+ return () => { this.cleared = true; };
+ });
+ }
+
+ async close(): Promise { (await this.database)?.close(); }
+}
diff --git a/builder/web/src/lib/library/summary.test.ts b/builder/web/src/lib/library/summary.test.ts
new file mode 100644
index 0000000000..c7c76a0f5a
--- /dev/null
+++ b/builder/web/src/lib/library/summary.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest';
+import type { RouteSummary } from './records';
+import { rideSummary, summarize, type Point } from './summary';
+
+const metresPerDegree = 6_371_008.8 * Math.PI / 180;
+const numbers = { lengthM: 0, climbM: 0, seconds: 0, days: 1, bike: 'road' } as const;
+
+/** Metres from `p` to the nearest segment of `line`, in a flat frame at the latitude of `p`. */
+function offset(p: Point, line: number[]): number {
+ const k = Math.cos(p[1] * Math.PI / 180) * metresPerDegree;
+ let best = Infinity;
+ for (let i = 2; i < line.length; i += 2) {
+ const ax = (line[i - 2] - p[0]) * k, ay = (line[i - 1] - p[1]) * metresPerDegree;
+ const bx = (line[i] - p[0]) * k - ax, by = (line[i + 1] - p[1]) * metresPerDegree - ay;
+ const t = Math.max(0, Math.min(1, -(ax * bx + ay * by) / (bx * bx + by * by || 1)));
+ best = Math.min(best, Math.hypot(ax + t * bx, ay + t * by));
+ }
+ return best;
+}
+
+describe('summary', () => {
+ it('keeps a bend of 15 m, and simplifies a long winding line to 1,000 points within 40 m', () => {
+ const bend = summarize([[8, 47, 500], [8.001, 47 + 15 / metresPerDegree, 510.4], [8.002, 47, null]], numbers);
+ expect([bend.heights, bend.highestM, bend.bounds[3]]).toEqual([[500, 510, null], 510, 47 + 15 / metresPerDegree]);
+
+ // 100 km to the east, a point every 20 m, with a sideways wave of 25 m.
+ const winding: Point[] = Array.from({ length: 5000 }, (_, i) => [8 + i * 20 / (metresPerDegree * Math.cos(47 * Math.PI / 180)),
+ 47 + 25 * Math.sin(i * 20 * 2 * Math.PI / 400) / metresPerDegree, null]);
+ const { line } = summarize(winding, numbers);
+ expect(line.length / 2).toBeLessThanOrEqual(1000);
+ expect(Math.max(...winding.map(p => offset(p, line)))).toBeLessThan(41);
+ });
+
+ it('measures a ride with a stop and a pause: no length to the segment start, no moving time while it stands', () => {
+ // Points every 500 m to the east; the pause starts 1 km farther.
+ const at = (metres: number) => 8e6 + Math.round(metres / (metresPerDegree * Math.cos(47 * Math.PI / 180)) * 1e6);
+ const t = 1_785_571_200;
+ const steps: [number, number, number, boolean?][] = [[0, 0, 400], [60, 500, 403], [120, 1000, 406], [720, 1000, 406],
+ [1000, 2000, 404, true], [1060, 2500, 408], [1120, 3000, 410]];
+ const ride = rideSummary(steps.map(([s, m, h, pause]) => ({ timeS: t + s + .4, lat: 47e6, lon: at(m), elevationM: h, segmentStart: !s || !!pause })), 'gravel');
+ expect(ride).toMatchObject({ lengthM: 2000, climbM: 12, seconds: 1120, movingS: 240, start: t, bike: 'gravel', highestM: 410 });
+ });
+});
diff --git a/builder/web/src/lib/library/summary.ts b/builder/web/src/lib/library/summary.ts
new file mode 100644
index 0000000000..21eb104f74
--- /dev/null
+++ b/builder/web/src/lib/library/summary.ts
@@ -0,0 +1,137 @@
+/** Makes the summary of a route or a ride: its line simplified to about 1,000 points, its bounds and its numbers. */
+import type { Bike, RideRecord, RideSummary, RouteRecord, Summary } from './records';
+
+/** One recorded point of a ride: Unix seconds and microdegrees. `segmentStart` marks the first point and the first
+ * point after a pause. */
+export interface RideSample {
+ timeS: number;
+ lat: number;
+ lon: number;
+ elevationM?: number | null;
+ segmentStart: boolean;
+}
+
+/** FNV-1a of `text`, as hex. */
+function hash(text: string): string {
+ let value = 0x811c9dc5;
+ for (let i = 0; i < text.length; i++) value = Math.imul(value ^ text.charCodeAt(i), 0x01000193);
+ return (value >>> 0).toString(16).padStart(8, '0');
+}
+
+/** A hash of the summary line, and for a ride of its start time, as hex. A new name keeps it. */
+export const lineKey = (item: RouteRecord | RideRecord) => hash(`${item.summary?.line.join(',')}@${'key' in item ? item.summary.start : ''}`);
+
+/** A hash of what the device file of a route is made from: its name and its plan (`trip`), which give the line, the
+ * waypoints, the days and the bike. A route whose key differs from the key in `sent` changed since it was sent. */
+export const sentKey = (route: RouteRecord) => hash(JSON.stringify([route.name, route.trip]));
+
+/** The points of the summary line as [longitude, latitude]. */
+export function lineCoordinates({ line }: Summary): [number, number][] {
+ return Array.from({ length: line.length / 2 }, (_, i) => [line[2 * i], line[2 * i + 1]]);
+}
+
+/** Longitude, latitude, and the height in metres or null. */
+export type Point = readonly [number, number, (number | null)?];
+/** The numbers that the caller knows; `summarize` finds the others from the points. */
+export type Numbers = Omit;
+
+const maxPoints = 1000;
+// The group rule of rides allows 50 m between two lines, so a simplified line stays within 40 m of its points.
+const firstToleranceM = 10;
+/** A summary line is within this many metres of the points it simplifies. */
+export const lastToleranceM = 40;
+export const metresPerDegree = 6_371_008.8 * Math.PI / 180;
+
+// Start values, to test on real rides.
+const climbStepM = 5, movingMps = 2 / 3.6;
+
+const round = (value: number, scale: number) => Math.round(value * scale) / scale;
+
+/** The great-circle distance between two points in degrees. */
+export function distanceM(lon1: number, lat1: number, lon2: number, lat2: number): number {
+ const rad = Math.PI / 180, h = Math.sin((lat2 - lat1) * rad / 2) ** 2
+ + Math.cos(lat1 * rad) * Math.cos(lat2 * rad) * Math.sin((lon2 - lon1) * rad / 2) ** 2;
+ return 2 * metresPerDegree / rad * Math.asin(Math.min(1, Math.sqrt(h)));
+}
+
+/** The great-circle distance between two samples. */
+export const metres = (a: RideSample, b: RideSample) => distanceM(a.lon / 1e6, a.lat / 1e6, b.lon / 1e6, b.lat / 1e6);
+
+/** For each sample, the seconds of the step that ends at it when that step moves: at 2 km/h or more, and not to a
+ * segment start. Else 0. The moving time of a ride is their sum. */
+export function movingSteps(samples: RideSample[]): number[] {
+ return samples.map((sample, i) => {
+ if (!i || sample.segmentStart) return 0;
+ const seconds = sample.timeS - samples[i - 1].timeS;
+ return seconds > 0 && metres(samples[i - 1], sample) / seconds >= movingMps ? seconds : 0;
+ });
+}
+
+/** The length, the climb and the moving time of a recorded ride. The length skips the step to a segment start. The
+ * climb counts a rise when the height is 5 m above the last low. The moving time is the sum of `movingSteps`. */
+export function rideTotals(samples: RideSample[]): { lengthM: number; climbM: number; movingS: number } {
+ let lengthM = 0, climbM = 0, low: number | null = null;
+ samples.forEach((sample, i) => {
+ const height = sample.elevationM;
+ if (height != null) {
+ if (low === null || height < low) low = height;
+ else if (height - low >= climbStepM) { climbM += height - low; low = height; }
+ }
+ if (i && !sample.segmentStart) lengthM += metres(samples[i - 1], sample);
+ });
+ return { lengthM, climbM, movingS: movingSteps(samples).reduce((sum, seconds) => sum + seconds, 0) };
+}
+
+/** The summary of a recorded ride, with the numbers of `rideTotals`. `samples` holds at least one sample. */
+export function rideSummary(samples: RideSample[], bike: Bike): RideSummary {
+ const start = samples[0].timeS, { lengthM, climbM, movingS } = rideTotals(samples);
+ return summarize(samples.map(s => [s.lon / 1e6, s.lat / 1e6, s.elevationM]), {
+ lengthM: Math.round(lengthM), climbM: Math.round(climbM), seconds: Math.round(samples.at(-1)!.timeS - start),
+ movingS: Math.round(movingS), start: Math.floor(start), bike,
+ });
+}
+
+/** Douglas–Peucker at 10 m. While more than 1,000 points remain, the tolerance doubles, to 40 m at most; at 40 m the
+ * line keeps its points. `points` holds at least one point. */
+export function summarize(points: readonly Point[], numbers: Numbers): S {
+ if (!points.length) throw new Error('A summary needs at least one point.');
+ const n = points.length, lon = new Float64Array(n), lat = new Float64Array(n), cos = new Float64Array(n);
+ let west = Infinity, south = Infinity, east = -Infinity, north = -Infinity, highestM: number | null = null;
+ points.forEach(([x, y, height], i) => {
+ lon[i] = x; lat[i] = y; cos[i] = Math.cos(y * Math.PI / 180);
+ west = Math.min(west, x); east = Math.max(east, x); south = Math.min(south, y); north = Math.max(north, y);
+ if (height != null && (highestM === null || height > highestM)) highestM = height;
+ });
+ let tolerance = firstToleranceM, kept = simplify(lon, lat, cos, tolerance);
+ while (kept.length > maxPoints && tolerance < lastToleranceM) kept = simplify(lon, lat, cos, tolerance = Math.min(2 * tolerance, lastToleranceM));
+ return {
+ ...numbers,
+ line: kept.flatMap(i => [round(lon[i], 1e5), round(lat[i], 1e5)]),
+ heights: kept.map(i => points[i][2] == null ? null : Math.round(points[i][2]!)),
+ bounds: [west, south, east, north],
+ highestM: highestM === null ? null : Math.round(highestM),
+ } as S;
+}
+
+/** The indices of the points that Douglas–Peucker keeps. A point's distance from a segment is measured in degrees of
+ * latitude, with the longitude scaled at the latitude of the segment's first point. */
+function simplify(lon: Float64Array, lat: Float64Array, cos: Float64Array, toleranceM: number): number[] {
+ const n = lon.length, keep = new Uint8Array(n), limit = (toleranceM / metresPerDegree) ** 2;
+ keep[0] = keep[n - 1] = 1;
+ const stack = n > 2 ? [0, n - 1] : [];
+ while (stack.length) {
+ const last = stack.pop()!, first = stack.pop()!, k = cos[first];
+ const bx = (lon[last] - lon[first]) * k, by = lat[last] - lat[first], length = bx * bx + by * by;
+ let far = -1, farthest = limit;
+ for (let i = first + 1; i < last; i++) {
+ const px = (lon[i] - lon[first]) * k, py = lat[i] - lat[first];
+ const t = length ? Math.max(0, Math.min(1, (px * bx + py * by) / length)) : 0;
+ const d = (px - t * bx) ** 2 + (py - t * by) ** 2;
+ if (d > farthest) { far = i; farthest = d; }
+ }
+ if (far >= 0) { keep[far] = 1; stack.push(first, far, far, last); }
+ }
+ const kept: number[] = [];
+ for (let i = 0; i < n; i++) if (keep[i]) kept.push(i);
+ return kept;
+}
diff --git a/builder/web/src/lib/library/trips.test.ts b/builder/web/src/lib/library/trips.test.ts
new file mode 100644
index 0000000000..3636fb3170
--- /dev/null
+++ b/builder/web/src/lib/library/trips.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from 'vitest';
+import { rideKeyAt } from './import';
+import type { RideRecord, RideTrip } from './records';
+import { rideSummary } from './summary';
+import { trips } from './trips';
+
+const KM_PER_DEGREE = 6_371.0088 * Math.PI / 180, COS = Math.cos(47 * Math.PI / 180);
+
+/** A straight ride of 3 hours from `from` to `to`, in km east and north of 8° E, 47° N, that starts at `start`, local time. */
+function ride(start: Date, from: [number, number], to: [number, number], trip?: RideTrip): RideRecord {
+ const s = start.getTime() / 1000;
+ const summary = rideSummary([0, 0.5, 1].map((t, i) => ({
+ timeS: s + i * 5400, lon: Math.round((8 + (from[0] + t * (to[0] - from[0])) / KM_PER_DEGREE / COS) * 1e6),
+ lat: Math.round((47 + (from[1] + t * (to[1] - from[1])) / KM_PER_DEGREE) * 1e6), elevationM: null, segmentStart: i === 0,
+ })), 'touring');
+ return { key: rideKeyAt(s), name: `${start.getDate()}.`, source: trip ? 'device' : 'file', format: 'gpx', summary, maxHr: null, ftp: null, ...trip && { trip } };
+}
+
+const at = (day: number, hour = 9) => new Date(2026, 6, day, hour);
+const shape = (list: RideRecord[]) => trips(list).map(trip => ({ id: trip.id, name: trip.name, rides: trip.rides.length, days: trip.days }));
+
+describe('trips', () => {
+ it('keeps a trip of the device across a train day, with its name, and the first ride names one with no name', () => {
+ const alps = { key: '9223372036854775813', name: 'Alps' };
+ const list = [ride(at(1), [0, 0], [80, 0], { ...alps, day: 1 }), ride(at(3), [300, 0], [380, 0], { ...alps, day: 3 }),
+ ride(at(10), [0, 0], [80, 0], { key: '5', name: '', day: 1 }), ride(at(11), [80, 0], [160, 0], { key: '5', name: '', day: 2 })];
+ expect(shape(list)).toEqual([
+ { id: alps.key, name: 'Alps', rides: 2, days: [1, 3] },
+ { id: '5', name: '10.', rides: 2, days: [1, 2] },
+ ]);
+ });
+
+ it('joins the rides that go on from the end of the ride before, across a rest day, and not across a train day', () => {
+ const list = [ride(at(1), [0, 0], [90, 0]), ride(at(1, 15), [91, 0], [120, 0]), ride(at(2), [120, 2], [200, 0]),
+ ride(at(4), [203, 0], [280, 0]), ride(at(5), [600, 0], [680, 0])];
+ expect(shape(list)).toEqual([{ id: list[0].key, name: '1.', rides: 4, days: [1, 1, 2, 4] }]);
+ });
+
+ it('makes no trip of a commute week or of loops from one base', () => {
+ const commute = [1, 2, 3, 4, 5].flatMap(day => [ride(at(day, 7), [0, 0], [12, 0]), ride(at(day, 17), [12, 0], [0, 0])]);
+ expect(trips(commute)).toEqual([]);
+ const base = [6, 7, 8].map(day => ride(at(day), [500, 0], [500.5, 0]));
+ expect(trips(base)).toEqual([]);
+ // A loop that ends after midnight, and a loop from home the next morning.
+ expect(trips([ride(at(10, 22), [0, 0], [0.5, 0]), ride(at(11), [0, 0], [0.5, 0])])).toEqual([]);
+ // A commute of 25 km with the first morning ride missing: every night is at home, 25 km from the first point.
+ const long = [12, 13, 14].flatMap(day => [ride(at(day, 7), [0, 0], [25, 0]), ride(at(day, 17), [25, 0], [0, 0])]);
+ expect(trips(long.slice(1))).toEqual([]);
+ });
+});
diff --git a/builder/web/src/lib/library/trips.ts b/builder/web/src/lib/library/trips.ts
new file mode 100644
index 0000000000..1e98e3763e
--- /dev/null
+++ b/builder/web/src/lib/library/trips.ts
@@ -0,0 +1,61 @@
+/** Finds the trips of the rides: the rides of one trip on the device, and the rides that go on from where the ride before ended. */
+import type { RideRecord } from './records';
+import { distanceM } from './summary';
+
+/** The rides of a trip in start order, and the day of each, from 1. A trip has rides on 2 days or more. */
+export interface Trip {
+ /** The trip key of the device, else the key of the first ride. */
+ id: string;
+ name: string;
+ rides: RideRecord[];
+ days: number[];
+}
+
+const JOIN_M = 5000, HOME_M = 20_000, BASE_M = 5000, GAP_DAYS = 2;
+
+/** The local day of a Unix time in seconds, as a count of days. */
+export function localDay(seconds: number): number {
+ const date = new Date(seconds * 1000);
+ return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / 86_400_000;
+}
+
+const first = (ride: RideRecord) => ride.summary.line.slice(0, 2);
+const last = (ride: RideRecord) => ride.summary.line.slice(-2);
+const metres = ([lon1, lat1]: number[], [lon2, lat2]: number[]) => distanceM(lon1, lat1, lon2, lat2);
+
+/**
+ * A device ride with a trip belongs to that trip, on its day. Each other ride joins the trip of the ride before when it
+ * starts within 5 km of that ride's end, on the same local day as its start or at most 2 days later, and when each night
+ * of the trip is more than 20 km from the trip's first point: a commute, loops from one base and a train day make no
+ * trip. A run of 3 days or more whose nights are all within 5 km of one place is a commute or a base, and no trip.
+ */
+export function trips(rides: RideRecord[]): Trip[] {
+ const sorted = [...rides].sort((a, b) => a.summary.start - b.summary.start);
+ const out: Trip[] = [], device = new Map();
+ let chain: RideRecord[] = [];
+ const close = () => {
+ const day0 = chain.length ? localDay(chain[0].summary.start) : 0, days = chain.map(ride => localDay(ride.summary.start) - day0 + 1);
+ const nights = chain.filter((_, i) => days[i + 1] > days[i]).map(last);
+ const base = days.at(-1)! > 2 && nights.every(night => metres(night, nights[0]) <= BASE_M);
+ if (days.at(-1)! > 1 && !base) out.push({ id: chain[0].key, name: chain[0].name, rides: chain, days });
+ chain = [];
+ };
+ for (const ride of sorted) {
+ if (ride.trip) {
+ const trip = device.get(ride.trip.key) ?? { id: ride.trip.key, name: ride.trip.name || ride.name, rides: [], days: [] };
+ device.set(trip.id, trip);
+ trip.rides.push(ride);
+ trip.days.push(ride.trip.day);
+ continue;
+ }
+ const before = chain.at(-1);
+ const later = before ? localDay(ride.summary.start) - localDay(before.summary.start) : 0;
+ const joins = before && later >= 0 && later <= GAP_DAYS && metres(last(before), first(ride)) <= JOIN_M
+ && (!later || metres(last(before), first(chain[0])) > HOME_M);
+ if (!joins) close();
+ chain.push(ride);
+ }
+ close();
+ for (const trip of device.values()) if (new Set(trip.days).size > 1) out.push(trip);
+ return out.sort((a, b) => a.rides[0].summary.start - b.rides[0].summary.start);
+}
diff --git a/builder/web/src/lib/library/zip.ts b/builder/web/src/lib/library/zip.ts
new file mode 100644
index 0000000000..12fe2dd520
--- /dev/null
+++ b/builder/web/src/lib/library/zip.ts
@@ -0,0 +1,191 @@
+/** Writes ZIP files whose entries are stored with no compression, and reads ZIP files of stored or deflated entries. */
+
+export interface Entry {
+ name: string;
+ data: Blob;
+}
+
+/** An entry of a ZIP file, as its central directory gives it. `open` gives its content. */
+export interface ZipEntry {
+ name: string;
+ /** The ZIP file. */
+ file: Blob;
+ method: number;
+ encrypted: boolean;
+ crc: number;
+ packed: number;
+ size: number;
+ /** The offset of the local header in `file`. */
+ at: number;
+}
+
+/** An entry that is encrypted, or packed with a method other than stored or deflated. */
+export class UnsupportedPacking extends Error {}
+
+const crcTable = Uint32Array.from({ length: 256 }, (_, i) => {
+ let c = i;
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ return c >>> 0;
+});
+
+// Chunks become one Blob part at this size, so the browser can move a large entry to disk while it inflates.
+const partBytes = 4 << 20;
+
+/** The CRC-32 and the length of a stream, and with `keep` its content. It stops with an error past `limit` bytes, so a
+ * small entry that inflates to gigabytes cannot fill the memory. */
+async function measure(stream: ReadableStream>, limit = Infinity, keep = false): Promise<{ crc: number; length: number; content: Blob }> {
+ const reader = stream.getReader(), parts: Blob[] = [];
+ let c = 0xffffffff, length = 0, chunks: Uint8Array[] = [], held = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) return { crc: (c ^ 0xffffffff) >>> 0, length, content: new Blob([...parts, ...chunks]) };
+ length += value.length;
+ if (length > limit) {
+ await reader.cancel();
+ throw damaged();
+ }
+ for (let i = 0; i < value.length; i++) c = crcTable[(c ^ value[i]) & 0xff] ^ (c >>> 8);
+ if (!keep) continue;
+ chunks.push(value);
+ held += value.length;
+ if (held >= partBytes) { parts.push(new Blob(chunks)); chunks = []; held = 0; }
+ }
+}
+
+const utf8 = 0x0800, stored = 0, deflated = 8, needed = 10, max32 = 0xffffffff;
+// 1980-01-01 00:00, the first date that a ZIP file can hold.
+const dosTime = 0, dosDate = (1 << 5) | 1;
+const tooLarge = () => new Error('The library is too large for one backup file.');
+
+/** The fields from "version needed" to "extra length", which the local and the central header share. */
+function shared(view: DataView, at: number, crc: number, size: number, nameLength: number): void {
+ [needed, utf8, stored, dosTime, dosDate].forEach((value, i) => view.setUint16(at + i * 2, value, true));
+ view.setUint32(at + 10, crc, true);
+ view.setUint32(at + 14, size, true);
+ view.setUint32(at + 18, size, true);
+ view.setUint16(at + 22, nameLength, true);
+ view.setUint16(at + 24, 0, true);
+}
+
+/** Reads each entry one time for its CRC-32. The result holds the entry blobs, not copies of their bytes. */
+export async function zip(entries: Entry[]): Promise {
+ if (entries.length > 0xffff) throw tooLarge();
+ const parts: BlobPart[] = [], central: Uint8Array[] = [];
+ let offset = 0;
+ for (const { name, data } of entries) {
+ const path = new TextEncoder().encode(name), { crc } = await measure(data.stream());
+ if (offset + 30 + path.length + data.size > max32) throw tooLarge();
+ const local = new Uint8Array(30 + path.length), view = new DataView(local.buffer);
+ view.setUint32(0, 0x04034b50, true);
+ shared(view, 4, crc, data.size, path.length);
+ local.set(path, 30);
+ const header = new Uint8Array(46 + path.length), entry = new DataView(header.buffer);
+ entry.setUint32(0, 0x02014b50, true);
+ entry.setUint16(4, 20, true);
+ shared(entry, 6, crc, data.size, path.length);
+ entry.setUint32(42, offset, true);
+ header.set(path, 46);
+ parts.push(local, data);
+ central.push(header);
+ offset += local.length + data.size;
+ }
+ const size = central.reduce((sum, header) => sum + header.length, 0);
+ if (offset + size > max32) throw tooLarge();
+ const end = new DataView(new ArrayBuffer(22));
+ end.setUint32(0, 0x06054b50, true);
+ end.setUint16(8, entries.length, true);
+ end.setUint16(10, entries.length, true);
+ end.setUint32(12, size, true);
+ end.setUint32(16, offset, true);
+ return new Blob([...parts, ...central, end], { type: 'application/zip' });
+}
+
+const damaged = () => new Error('The file is damaged or is not a ZIP file.');
+
+async function view(file: Blob, at: number, length: number): Promise {
+ const bytes = await file.slice(at, at + length).arrayBuffer();
+ if (bytes.byteLength !== length) throw damaged();
+ return new DataView(bytes);
+}
+
+function uint64(view: DataView, at: number): number {
+ const value = Number(view.getBigUint64(at, true));
+ if (!Number.isSafeInteger(value)) throw damaged();
+ return value;
+}
+
+// The characters 128 to 255 of code page 437, the encoding of a name without the UTF-8 flag.
+const cp437 = 'ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ';
+
+const strict = new TextDecoder('utf-8', { fatal: true }), lenient = new TextDecoder();
+
+/** A name with no UTF-8 flag is CP437, unless it is valid UTF-8: the macOS Finder writes UTF-8 with no flag. */
+function decodeName(bytes: Uint8Array, flagged: boolean): string {
+ if (flagged) return lenient.decode(bytes);
+ try { return strict.decode(bytes); } catch { return Array.from(bytes, c => c < 128 ? String.fromCharCode(c) : cp437[c - 128]).join(''); }
+}
+
+/** The entries of a ZIP file. It reads only the central directory, also of a ZIP64 file. */
+export async function entries(file: Blob): Promise {
+ const tailStart = Math.max(0, file.size - 22 - 0xffff);
+ const tail = new DataView(await file.slice(tailStart).arrayBuffer());
+ let end = tail.byteLength - 22;
+ while (end >= 0 && tail.getUint32(end, true) !== 0x06054b50) end--;
+ if (end < 0) throw damaged();
+ let count = tail.getUint16(end + 10, true), size = tail.getUint32(end + 12, true), start = tail.getUint32(end + 16, true);
+ // The ZIP64 locator comes just before the end record and points to the ZIP64 end record.
+ if (end >= 20 && tail.getUint32(end - 20, true) === 0x07064b50) {
+ const record = await view(file, uint64(tail, end - 12), 56);
+ if (record.getUint32(0, true) !== 0x06064b50) throw damaged();
+ [count, size, start] = [32, 40, 48].map(at => uint64(record, at));
+ }
+ const directory = await view(file, start, size);
+ const list: ZipEntry[] = [];
+ let at = 0;
+ for (let i = 0; i < count; i++) {
+ if (at + 46 > size || directory.getUint32(at, true) !== 0x02014b50) throw damaged();
+ const flags = directory.getUint16(at + 8, true), method = directory.getUint16(at + 10, true), crc = directory.getUint32(at + 16, true);
+ const nameLength = directory.getUint16(at + 28, true), extraAt = at + 46 + nameLength, extraEnd = extraAt + directory.getUint16(at + 30, true);
+ const next = extraEnd + directory.getUint16(at + 32, true);
+ if (next > size) throw damaged();
+ let packed = directory.getUint32(at + 20, true), unpacked = directory.getUint32(at + 24, true), offset = directory.getUint32(at + 42, true);
+ // The ZIP64 field holds 8 bytes for each of these three values that is 0xffffffff, in this order.
+ for (let x = extraAt; x + 4 <= extraEnd; x += 4 + directory.getUint16(x + 2, true)) {
+ if (directory.getUint16(x, true) !== 1) continue;
+ let y = x + 4;
+ const take = () => { if (y + 8 > extraEnd) throw damaged(); y += 8; return uint64(directory, y - 8); };
+ if (unpacked === max32) unpacked = take();
+ if (packed === max32) packed = take();
+ if (offset === max32) offset = take();
+ }
+ list.push({ name: decodeName(new Uint8Array(directory.buffer, at + 46, nameLength), !!(flags & utf8)),
+ file, method, encrypted: !!(flags & 1), crc, packed, size: unpacked, at: offset });
+ at = next;
+ }
+ return list;
+}
+
+/** The content of an entry, after a check of its CRC-32. A stored entry is a slice of the ZIP file; a deflated one
+ * is a new Blob, which the browser can keep on disk. */
+export async function open(entry: ZipEntry): Promise {
+ if (entry.encrypted || (entry.method !== stored && entry.method !== deflated)) throw new UnsupportedPacking('This packing is not supported.');
+ const local = await view(entry.file, entry.at, 30);
+ if (local.getUint32(0, true) !== 0x04034b50) throw damaged();
+ const dataAt = entry.at + 30 + local.getUint16(26, true) + local.getUint16(28, true);
+ if (dataAt + entry.packed > entry.file.size) throw damaged();
+ const data = entry.file.slice(dataAt, dataAt + entry.packed), inflate = entry.method === deflated;
+ const stream = inflate ? data.stream().pipeThrough(new DecompressionStream('deflate-raw')) : data.stream();
+ const { crc, length, content } = await measure(stream, entry.size, inflate).catch(() => { throw damaged(); });
+ if (crc !== entry.crc || length !== entry.size) throw damaged();
+ return inflate ? content : data;
+}
+
+/** Each entry of a ZIP file by name, after a check of its CRC-32. */
+export async function unzip(file: Blob): Promise> {
+ const contents = new Map();
+ for (const entry of await entries(file)) {
+ if (contents.has(entry.name)) throw damaged();
+ contents.set(entry.name, await open(entry));
+ }
+ return contents;
+}
diff --git a/builder/web/src/lib/map/coverage-map.css b/builder/web/src/lib/map/coverage-map.css
new file mode 100644
index 0000000000..d183e3714e
--- /dev/null
+++ b/builder/web/src/lib/map/coverage-map.css
@@ -0,0 +1,65 @@
+/* The rules of the coverage map on Leaflet. `lib/map/coverageMap.ts` loads them, so the map builder and a page of the
+ shell show the same map. */
+.basemap-warning {
+ padding: 6px 10px;
+ background: var(--panel);
+ color: var(--ink);
+}
+
+.leaflet-bar a,
+.leaflet-control-attribution {
+ background: var(--panel) !important;
+ color: var(--ink) !important;
+}
+.leaflet-bar a:hover { background: var(--parchment-2) !important; }
+.leaflet-control-attribution a { color: var(--forest); }
+
+.leaflet-container {
+ font-family: var(--sans);
+ background: var(--parchment-2);
+}
+
+.leaflet-popup-content-wrapper,
+.leaflet-tooltip {
+ background: var(--panel);
+ color: var(--ink);
+ border: 1px solid var(--parchment-3);
+ border-radius: 10px;
+ box-shadow: 0 6px 18px rgba(36, 51, 28, 0.18);
+}
+
+.leaflet-popup-tip {
+ background: var(--panel);
+}
+
+.bbox-cursor {
+ cursor: crosshair !important;
+}
+
+/* The coverage map's not-baked hatch. Leaflet's SVG renderer sets fill
+ as a presentation attribute; CSS wins over attributes, which is how these
+ rectangles pick up the injected (coverageMap.ts owns the defs). */
+.coverage-hatch {
+ fill: url(#obc-unbaked-hatch);
+ fill-opacity: 0.5;
+}
+
+.coverage-hatch.faintly {
+ fill-opacity: 0.3;
+}
+
+/* The ground outside the area of a map, under the outlines: its colour goes, its lines and names keep their contrast,
+ and a light veil of the page ground sets it back. The blend is on the pane, because an SVG blends only inside itself. */
+.leaflet-grey-pane {
+ mix-blend-mode: saturation;
+}
+
+.coverage-grey {
+ fill: #808080;
+ fill-opacity: 0.85;
+}
+
+.coverage-pale {
+ fill: var(--parchment);
+ fill-opacity: 0.2;
+}
diff --git a/builder/web/src/lib/map/coverageMap.ts b/builder/web/src/lib/map/coverageMap.ts
index 7d1313fe1a..31026e2c32 100644
--- a/builder/web/src/lib/map/coverageMap.ts
+++ b/builder/web/src/lib/map/coverageMap.ts
@@ -1,7 +1,7 @@
// Leaflet glue for the coverage map. This paints the cell catalog's own region
// boundaries as quiet affordances, each selection part's true stair-edged outline,
-// hatched not-baked patches inside the selection, and the corridor panel's dashed
-// preview. No grid is ever drawn, and this file simply has no code that could.
+// and hatched not-baked patches inside the selection. No grid is ever drawn, and this
+// file simply has no code that could.
//
// All Leaflet state lives on the instance; the Svelte component owns *what* to draw
// and pushes it through the `set*` methods below, so this class stays framework-free
@@ -14,6 +14,8 @@
// armed hover and click do point-in-rings over every region.
import L from "leaflet";
+import "leaflet/dist/leaflet.css";
+import "./coverage-map.css";
import { addBasemap } from "./basemap";
/** [lat, lon] degrees — Leaflet's own order. */
@@ -22,11 +24,9 @@ export type DegPoint = [number, number];
/** One selection part, reduced to what the map draws. */
export interface RenderedPart {
id: string;
- kind: "region" | "box" | "corridor" | "lasso";
+ kind: "region" | "box";
/** Stair-edged coverage rings, outer + holes, from `coverageRings`. */
rings: DegPoint[][];
- /** The route itself, for corridor parts. */
- route?: DegPoint[];
highlighted: boolean;
}
@@ -37,12 +37,6 @@ export interface RenderedWarning {
kind: "hole" | "partial";
}
-/** The corridor panel's uncommitted routes. */
-export interface RenderedPreview {
- rings: DegPoint[][];
- routes: DegPoint[][];
-}
-
export interface CoverageMapCallbacks {
/** An armed click found exactly one region under the point. */
onRegionPick(regionId: string): void;
@@ -56,10 +50,6 @@ export interface CoverageMapCallbacks {
onBoxDrawn(south: number, west: number, north: number, east: number): void;
/** The in-flight box changed; return the pricing chip's text ("" hides). */
boxDragLabel(south: number, west: number, north: number, east: number): string;
- /** A lasso ring was drawn, as [lat, lon] degree points, unclosed. */
- onLassoDrawn(points: DegPoint[]): void;
- /** The in-flight lasso changed; return the pricing chip's text ("" hides). */
- lassoDragLabel(points: DegPoint[]): string;
/** Drawing was cancelled or finished — the component disarms its tool. */
onDrawEnd(): void;
/** A hatched warning patch was clicked — zoom is the component's call. */
@@ -85,16 +75,25 @@ const PART_STYLE: L.PathOptions = {
interactive: false,
};
const PART_HIGHLIGHT_STYLE: L.PathOptions = { ...PART_STYLE, weight: 4, fillOpacity: 0.2 };
-const ROUTE_STYLE: L.PathOptions = { color: "var(--route)", weight: 2.5, interactive: false };
-const PREVIEW_RING_STYLE: L.PathOptions = {
- color: "var(--coral)",
- weight: 2,
- dashArray: "7 5",
- fillColor: "var(--amber)",
- fillOpacity: 0.08,
- interactive: false,
-};
-const PREVIEW_ROUTE_STYLE: L.PathOptions = { ...ROUTE_STYLE, dashArray: "4 4" };
+/** A region over pale ground: a dashed line with no fill, so the area keeps the full colour of the map. */
+const REGION_PALE_STYLE: L.PathOptions = { ...REGION_STYLE, weight: 1.2, opacity: 0.6, fill: false, dashArray: "5 4" };
+/** The line around the area where the ground outside it is pale: the full colour of the map shows the area, so it has no fill. */
+const AREA_STYLE: L.PathOptions = { color: "var(--ink)", weight: 1.5, opacity: 0.7, fill: false, interactive: false };
+const AREA_HIGHLIGHT_STYLE: L.PathOptions = { ...AREA_STYLE, weight: 3, opacity: 1 };
+// Leaflet draws the paths of one pane in the order of their arrival, so the pale ground and the routes have panes of
+// their own: under and over the pane of the regions, the parts and the warnings.
+const PALE_STYLE: L.PathOptions = { stroke: false, className: "coverage-pale", interactive: false, pane: "pale" };
+/** Takes the colour out of the ground under it; `coverage-map.css` has the blend of its pane. */
+const GREY_STYLE: L.PathOptions = { stroke: false, className: "coverage-grey", interactive: false, pane: "grey" };
+/** The lines of the map cells. They show why an area grows to whole cells, and are otherwise not noticed. */
+const GRID_STYLE: L.PolylineOptions = { color: "var(--ink)", weight: 1, opacity: 0.13, interactive: false, pane: "grid" };
+/** The cells that a box takes while the rider draws it. */
+const SNAP_STYLE: L.PathOptions = { color: "var(--ink)", weight: 1.5, opacity: 0.6, fill: false, interactive: false };
+/** A cell narrower than this on the screen gets no lines: they would be a texture. */
+const GRID_MIN_PX = 36;
+const ROUTE_STYLE: L.PolylineOptions = { color: "var(--route)", weight: 3, interactive: false, pane: "routes" };
+/** A ring around the whole map; the rings of the area are its holes. */
+const WORLD: DegPoint[] = [[-89, -540], [-89, 540], [89, 540], [89, -540]];
const WARNING_STYLE: Record<"hole" | "partial", L.PathOptions> = {
hole: { color: "var(--coral)", weight: 1.6, className: "coverage-hatch" },
partial: { color: "var(--coral)", weight: 1, opacity: 0.6, dashArray: "3 3", className: "coverage-hatch faintly" },
@@ -106,7 +105,6 @@ const BOX_DRAW_STYLE: L.PathOptions = {
fillColor: "var(--amber)",
fillOpacity: 0.18,
};
-const LASSO_DRAW_STYLE: L.PathOptions = { ...BOX_DRAW_STYLE, dashArray: "5 4" };
/** Even-odd containment in a region's drawable rings, degrees — the same rule the
* even-odd fill draws them with, so what hovers is what is painted. */
@@ -133,10 +131,6 @@ interface ShelfRegion {
span: number;
}
-/** Minimum pointer movement, px, before a lasso takes another vertex. Keeps a slow
- * gesture from minting thousands of points the pricing then walks. */
-const LASSO_STEP_PX = 4;
-
export class CoverageMapView {
private map: L.Map;
private cb: CoverageMapCallbacks;
@@ -148,9 +142,15 @@ export class CoverageMapView {
private emphasized: string | null = null;
private hoverTip: L.Tooltip;
+ private paleLayer: L.LayerGroup = L.layerGroup();
+ private pale = false;
+ private gridLayer: L.LayerGroup = L.layerGroup();
+ /** The side of a map cell and a line of the grid, in degrees; null with no cell lines. */
+ private grid: { step: number; origin: number } | null = null;
+ private snapRect: L.Rectangle | null = null;
private partLayer: L.LayerGroup = L.layerGroup();
+ private routeLayer: L.LayerGroup = L.layerGroup();
private warnLayer: L.LayerGroup = L.layerGroup();
- private previewLayer: L.LayerGroup = L.layerGroup();
private cellLayer: L.LayerGroup = L.layerGroup();
private drawArmed = false;
@@ -159,12 +159,6 @@ export class CoverageMapView {
private drawRect: L.Rectangle | null = null;
private drawTip: L.Tooltip;
- private lassoArmed = false;
- private lassoing = false;
- private lassoPoints: L.LatLng[] = [];
- private lassoLastPx: L.Point | null = null;
- private lassoPoly: L.Polygon | null = null;
-
private resizeObs: ResizeObserver;
/** The shelf's bounds. The pane's size settles over several layout passes (0-wide
* at mount, a strip, then the real grid track), and a fit computed against any of
@@ -181,30 +175,30 @@ export class CoverageMapView {
this.map = L.map(el, { worldCopyJump: true, boxZoom: false, maxZoom: 18 }).setView([49, 9], 5);
void background(this.map);
- // Draw order bottom-up: shelf, selection, warnings on top of the
- // selection they annotate, preview above everything settled.
+ // Draw order bottom-up: the pale ground, shelf, selection, warnings on top of the
+ // selection they annotate, and the routes above all.
+ this.map.createPane("grey").style.zIndex = "340";
+ this.map.createPane("pale").style.zIndex = "350";
+ this.map.createPane("grid").style.zIndex = "360";
+ this.map.createPane("routes").style.zIndex = "450";
+ this.paleLayer.addTo(this.map);
+ this.gridLayer.addTo(this.map);
+ this.map.on("moveend", () => this.drawGrid());
this.regionLayer.addTo(this.map);
this.cellLayer.addTo(this.map);
this.partLayer.addTo(this.map);
this.warnLayer.addTo(this.map);
- this.previewLayer.addTo(this.map);
+ this.routeLayer.addTo(this.map);
this.drawTip = L.tooltip({ className: "preview-tip", direction: "top", offset: [0, -8] });
this.hoverTip = L.tooltip({ className: "preview-tip", direction: "top", offset: [0, -12] });
- this.map.on("mousedown", (e) => {
- this.onDrawStart(e);
- this.onLassoStart(e);
- });
+ this.map.on("mousedown", (e) => this.onDrawStart(e));
this.map.on("mousemove", (e) => {
this.onDrawMove(e);
- this.onLassoMove(e);
this.onRegionHover(e);
});
- this.map.on("mouseup", () => {
- this.onDrawFinish();
- this.onLassoFinish();
- });
+ this.map.on("mouseup", () => this.onDrawFinish());
this.map.on("click", (e) => this.onRegionClick(e));
this.map.on("mouseout", () => this.clearRegionHover());
// Leaflet only hears a mouseup inside its container: a drag released over the
@@ -230,7 +224,6 @@ export class CoverageMapView {
private readonly onDocPointerUp = (): void => {
if (this.drawing) this.onDrawFinish();
- if (this.lassoing) this.onLassoFinish();
};
private readonly onVisibility = (): void => {
@@ -291,7 +284,7 @@ export class CoverageMapView {
if (armed === this.regionArmed) return;
this.regionArmed = armed;
if (!armed) this.clearRegionHover();
- this.setCursor(armed || this.drawArmed || this.lassoArmed);
+ this.setCursor(armed || this.drawArmed);
}
/** Every region whose boundary contains the point, smallest first. */
@@ -320,7 +313,7 @@ export class CoverageMapView {
}
private onRegionHover(e: L.LeafletMouseEvent): void {
- if (!this.regionArmed || this.drawing || this.lassoing) return;
+ if (!this.regionArmed || this.drawing) return;
const chain = this.chainAt(e.latlng);
if (chain.length === 0) {
this.clearRegionHover();
@@ -343,13 +336,13 @@ export class CoverageMapView {
* restores quiet. */
emphasizeRegion(regionId: string | null): void {
if (regionId === this.emphasized) return;
- if (this.emphasized) this.regionPolys.get(this.emphasized)?.setStyle(REGION_STYLE);
+ if (this.emphasized) this.regionPolys.get(this.emphasized)?.setStyle(this.pale ? REGION_PALE_STYLE : REGION_STYLE);
this.emphasized = regionId;
if (regionId) this.regionPolys.get(regionId)?.setStyle(REGION_HOVER_STYLE);
}
private onRegionClick(e: L.LeafletMouseEvent): void {
- if (!this.regionArmed || this.drawArmed || this.lassoArmed) return;
+ if (!this.regionArmed || this.drawArmed) return;
const chain = this.chainAt(e.latlng);
if (chain.length === 0) return;
if (chain.length === 1) {
@@ -384,15 +377,53 @@ export class CoverageMapView {
setParts(parts: RenderedPart[]): void {
this.partLayer.clearLayers();
for (const part of parts) {
- if (part.rings.length) {
- L.polygon(part.rings, part.highlighted ? PART_HIGHLIGHT_STYLE : PART_STYLE).addTo(this.partLayer);
- }
- if (part.route && part.route.length > 1) {
- L.polyline(part.route, ROUTE_STYLE).addTo(this.partLayer);
- }
+ if (!part.rings.length) continue;
+ if (!this.pale) L.polygon(part.rings, part.highlighted ? PART_HIGHLIGHT_STYLE : PART_STYLE).addTo(this.partLayer);
+ else if (part.highlighted) L.polygon(part.rings, AREA_HIGHLIGHT_STYLE).addTo(this.partLayer);
}
}
+ /**
+ * Makes the ground outside `rings` grey and a little pale, so the area shows in the full colour of the map, with
+ * one line around it. The names and the lines of the ground outside keep their contrast: the rider reads them to
+ * choose what to add. `rings` are the outer rings and the holes of one cell set, which never cross. From then on
+ * a region is a dashed line, and `setParts` draws only a highlighted part.
+ */
+ setPale(rings: DegPoint[][]): void {
+ if (!this.pale) for (const poly of this.regionPolys.values()) poly.setStyle(REGION_PALE_STYLE);
+ this.pale = true;
+ this.paleLayer.clearLayers();
+ L.polygon([WORLD, ...rings], GREY_STYLE).addTo(this.paleLayer);
+ L.polygon([WORLD, ...rings], PALE_STYLE).addTo(this.paleLayer);
+ if (rings.length) L.polygon(rings, AREA_STYLE).addTo(this.paleLayer);
+ }
+
+ /** Shows the lines of the map cells, faintly: a cell has the side `step`, and one line is at `origin`, in degrees.
+ * While the rider draws a box, a line goes around the cells that the box takes. */
+ setGrid(step: number, origin: number): void {
+ this.grid = { step, origin };
+ this.drawGrid();
+ }
+
+ private drawGrid(): void {
+ this.gridLayer.clearLayers();
+ const grid = this.grid, width = this.map.getSize().x, seen = this.map.getBounds();
+ if (!grid || !width || (width * grid.step) / (seen.getEast() - seen.getWest()) < GRID_MIN_PX) return;
+ // As far past the view as the renderer draws, so the start of a pan shows lines.
+ const view = seen.pad(0.1), south = Math.max(view.getSouth(), -85), north = Math.min(view.getNorth(), 85);
+ const first = (value: number) => grid.origin + Math.ceil((value - grid.origin) / grid.step) * grid.step;
+ const lines: DegPoint[][] = [];
+ for (let lon = first(view.getWest()); lon <= view.getEast(); lon += grid.step) lines.push([[south, lon], [north, lon]]);
+ for (let lat = first(south); lat <= north; lat += grid.step) lines.push([[lat, view.getWest()], [lat, view.getEast()]]);
+ L.polyline(lines, GRID_STYLE).addTo(this.gridLayer);
+ }
+
+ /** The lines of the rider's routes, in the colour of a route, in place of those before. */
+ setRoutes(lines: DegPoint[][]): void {
+ this.routeLayer.clearLayers();
+ for (const line of lines) L.polyline(line, ROUTE_STYLE).addTo(this.routeLayer);
+ }
+
/** Squares, such as the leaves of a tiled layer, each in its colour and with its label. */
setCells(cells: { bounds: [DegPoint, DegPoint]; color: string; label: string }[]): void {
this.cellLayer.clearLayers();
@@ -416,18 +447,6 @@ export class CoverageMapView {
this.ensureHatchPattern();
}
- setPreview(preview: RenderedPreview | null): void {
- this.previewLayer.clearLayers();
- if (!preview) return;
- // One polygon holding every ring: Leaflet's default even-odd fill rule
- // renders disjoint outers filled and stair-holes empty without this code
- // having to work out which hole belongs to which patch.
- if (preview.rings.length) L.polygon(preview.rings, PREVIEW_RING_STYLE).addTo(this.previewLayer);
- for (const route of preview.routes) {
- if (route.length > 1) L.polyline(route, PREVIEW_ROUTE_STYLE).addTo(this.previewLayer);
- }
- }
-
/** Fly to a box — a warning row was clicked. */
flyTo(south: number, west: number, north: number, east: number): void {
this.userMoved = true; // deliberate navigation outranks the shelf fit
@@ -451,7 +470,7 @@ export class CoverageMapView {
this.drawing = false;
this.removeDrawRect();
this.map.dragging.enable();
- this.setCursor(this.regionArmed || this.lassoArmed);
+ this.setCursor(this.regionArmed);
}
private onDrawStart(e: L.LeafletMouseEvent): void {
@@ -466,6 +485,14 @@ export class CoverageMapView {
if (!this.drawArmed || !this.drawing || !this.drawRect || !this.drawStart) return;
const bounds = L.latLngBounds(this.drawStart, e.latlng);
this.drawRect.setBounds(bounds);
+ if (this.grid) {
+ const { step, origin } = this.grid;
+ const edge = (value: number, round: (cells: number) => number) => origin + round((value - origin) / step) * step;
+ const cells = L.latLngBounds([edge(bounds.getSouth(), Math.floor), edge(bounds.getWest(), Math.floor)],
+ [edge(bounds.getNorth(), Math.ceil), edge(bounds.getEast(), Math.ceil)]);
+ if (this.snapRect) this.snapRect.setBounds(cells);
+ else this.snapRect = L.rectangle(cells, SNAP_STYLE).addTo(this.map);
+ }
const label = this.cb.boxDragLabel(
bounds.getSouth(),
bounds.getWest(),
@@ -492,6 +519,10 @@ export class CoverageMapView {
}
private removeDrawRect(): void {
+ if (this.snapRect) {
+ this.map.removeLayer(this.snapRect);
+ this.snapRect = null;
+ }
if (this.drawRect) {
this.map.removeLayer(this.drawRect);
this.drawRect = null;
@@ -508,79 +539,6 @@ export class CoverageMapView {
}
}
- armLassoDraw(): void {
- this.lassoArmed = true;
- this.map.dragging.disable();
- this.setCursor(true);
- }
-
- cancelLassoDraw(): void {
- this.lassoArmed = false;
- this.lassoing = false;
- this.removeLassoPoly();
- this.map.dragging.enable();
- this.setCursor(this.regionArmed || this.drawArmed);
- }
-
- private onLassoStart(e: L.LeafletMouseEvent): void {
- if (!this.lassoArmed) return;
- // Clear any leftover preview FIRST: `removeLassoPoly` also resets the point
- // buffer, so calling it after seeding wipes the gesture's first point and every
- // move then bails on the null guard.
- this.removeLassoPoly();
- this.lassoing = true;
- this.lassoPoints = [e.latlng];
- this.lassoLastPx = this.map.latLngToContainerPoint(e.latlng);
- this.lassoPoly = L.polygon([e.latlng], LASSO_DRAW_STYLE).addTo(this.map);
- }
-
- private onLassoMove(e: L.LeafletMouseEvent): void {
- if (!this.lassoArmed || !this.lassoing || !this.lassoPoly || !this.lassoLastPx) return;
- const px = this.map.latLngToContainerPoint(e.latlng);
- if (px.distanceTo(this.lassoLastPx) < LASSO_STEP_PX) return;
- this.lassoLastPx = px;
- this.lassoPoints.push(e.latlng);
- this.lassoPoly.setLatLngs(this.lassoPoints);
- const label = this.cb.lassoDragLabel(this.lassoPoints.map((p): DegPoint => [p.lat, p.lng]));
- this.showDrawTip(label, e.latlng);
- }
-
- private onLassoFinish(): void {
- if (!this.lassoArmed || !this.lassoing) return;
- this.lassoing = false;
- const points = this.lassoPoints;
- this.cancelLassoDraw();
- // A stray click or a gesture with no area draws nothing — the same 5 px
- // threshold the box uses, over the ring's pixel extent.
- let minX = Infinity;
- let minY = Infinity;
- let maxX = -Infinity;
- let maxY = -Infinity;
- for (const p of points) {
- const px = this.map.latLngToContainerPoint(p);
- minX = Math.min(minX, px.x);
- minY = Math.min(minY, px.y);
- maxX = Math.max(maxX, px.x);
- maxY = Math.max(maxY, px.y);
- }
- if (points.length < 3 || maxX - minX < 5 || maxY - minY < 5) {
- this.cb.onDrawEnd();
- return;
- }
- this.cb.onLassoDrawn(points.map((p): DegPoint => [p.lat, p.lng]));
- this.cb.onDrawEnd();
- }
-
- private removeLassoPoly(): void {
- if (this.lassoPoly) {
- this.map.removeLayer(this.lassoPoly);
- this.lassoPoly = null;
- }
- this.lassoPoints = [];
- this.lassoLastPx = null;
- if (this.map.hasLayer(this.drawTip)) this.map.removeLayer(this.drawTip);
- }
-
private setCursor(crosshair: boolean): void {
this.map.getContainer().classList.toggle("bbox-cursor", crosshair);
}
diff --git a/builder/web/src/lib/planner/editor.test.ts b/builder/web/src/lib/planner/editor.test.ts
index 0578831c11..8fc50e3e79 100644
--- a/builder/web/src/lib/planner/editor.test.ts
+++ b/builder/web/src/lib/planner/editor.test.ts
@@ -192,6 +192,23 @@ describe('planning modes', () => {
expect(guessedTrip(kept, riding(kept, 25)).days).toBe(6);
expect(routeToTrip({ ...route, mode: 'route' }, riding(route, 40))).toMatchObject({ mode: 'trip', days: 6 });
});
+
+ it('rides at the pace of the plan, which moves the guessed days but no day that the rider fixed', () => {
+ const route: Trip = { ...testTrip(), daysSet: undefined };
+ const line = testLine(route), fast: Trip = { ...route, pace: 'fast' };
+ const hours = line.seconds / 3600;
+ expect(planView(route, line).summary.hours).toBe(hours);
+ expect(planView(fast, line).summary.hours).toBeCloseTo(hours * 19 / 27);
+ expect(planView({ ...route, bike: 'mtb' }, line).summary.hours).toBe(hours);
+ expect(planView({ ...route, bike: 'road' }, line).summary.hours).toBeCloseTo(hours * 19 / 25);
+ const long = { ...line, elapsed: line.elapsed.map(s => s * 25 / hours), seconds: 25 * 3600 };
+ expect([route, fast, { ...route, bike: 'road' as const }].map(trip => guessedTrip(trip, long).days)).toEqual([4, 3, 3]);
+ expect(guessedTrip(setDays(fast, 4), long).days).toBe(4);
+ const kept = pinNight({ ...route, days: 4 }, long, 1, along(.3), 'Hut'), keptLine = testLine(kept);
+ const faster = guessedTrip({ ...kept, pace: 'fast' }, { ...keptLine, elapsed: keptLine.elapsed.map(s => s * 25 / hours), seconds: 25 * 3600 });
+ expect(faster.days).toBe(3);
+ expect(faster.points.find(p => p.id === 'night-1')?.coordinate).toEqual(along(.3));
+ });
});
describe('day count', () => {
diff --git a/builder/web/src/lib/planner/editor.ts b/builder/web/src/lib/planner/editor.ts
index 2998b2bef8..8a596bed26 100644
--- a/builder/web/src/lib/planner/editor.ts
+++ b/builder/web/src/lib/planner/editor.ts
@@ -1,4 +1,4 @@
-import { movingSecondsAt, progressAtSeconds, type RoutingLine } from './routing';
+import { movingSecondsAt, pacedLine, progressAtSeconds, type RoutingLine } from './routing';
import { profileAscent, profileDescent } from './profile-data';
import { ridingProfiles } from './riding-profiles';
import { coordinateAt, cumulative, firstIndex, nearestOnLine, nearestProgress, routeSlice, segmentDistances, type Coordinate } from './geo';
@@ -56,6 +56,8 @@ export interface Trip {
startDate?: string;
bike?: import('./riding-profiles').BikeType;
preset?: string;
+ /** A stored plan can hold a pace that this reader does not know: `planPace` reads it as Moderate. */
+ pace?: import('./riding-profiles').Pace;
/** Every route point between the start and the finish, in route order. Markers are not route points. */
routeOrder: string[];
restNames?: string[];
@@ -238,7 +240,7 @@ type Stop = { point: RoutePoint; distance: number };
/** What the panel, the map and the profile show of a plan. */
export interface PlanView {
- /** The routed line of the current points, when it is calculated. */
+ /** The routed line of the current points at the pace of the plan, when it is calculated. */
line?: RoutingLine;
coordinates: Coordinate[];
/** Each route point by position, with its kilometres along `coordinates`. A loop lists its start twice. */
@@ -263,12 +265,13 @@ function freeze(...values: object[]): void {
/** The view of `trip` along `line`, which must be the line calculated for the trip's points (`routingKey`). Without a
* line, a route has no length. */
-export function planView(trip: Trip, line: RoutingLine | undefined): PlanView {
+export function planView(trip: Trip, routed: RoutingLine | undefined): PlanView {
let byLine = views.get(trip);
if (!byLine) views.set(trip, byLine = new WeakMap());
- const known = byLine.get(line ?? unrouted);
+ const known = byLine.get(routed ?? unrouted);
if (known) return known;
freeze(trip, trip.points, ...trip.points);
+ const line = routed && pacedLine(routed, trip);
const points = orderedRoutePoints(trip);
// By position: a loop lists its start twice.
const coordinates = points.length < 2 ? [] : line?.coordinates ?? [points[0].coordinate];
@@ -277,7 +280,7 @@ export function planView(trip: Trip, line: RoutingLine | undefined): PlanView {
const days = points.length < 2 ? [] : splitDays(trip, layout);
const view: PlanView = { ...layout, summary: figures(trip, layout, 0, 1), days, itinerary: itinerary(trip, days) };
freeze(view, view.stops, view.days, view.itinerary);
- byLine.set(line ?? unrouted, view);
+ byLine.set(routed ?? unrouted, view);
return view;
}
@@ -324,7 +327,7 @@ function nightCount(trip: Trip): number {
/** The stretch around the even end of day `night`, `width` of a day on either side, within the fixed nights around it. */
export function overnightWindow(trip: Trip, line: RoutingLine | undefined, night: number, width = .2): { from: number; to: number; center: number; blocked: boolean } {
- const { stops } = planView(trip, line);
+ const { stops, line: paced } = planView(trip, line);
const count = nightCount(trip);
const fixed = fixedNights(trip, stops);
fixed.delete(night);
@@ -335,7 +338,7 @@ export function overnightWindow(trip: Trip, line: RoutingLine | undefined, night
const hi = after === undefined ? 1 : fixed.get(after)!;
const daysBefore = night - (before ?? 0);
const daysAfter = (after ?? count) - night;
- const effort = effortScale(line), start = effort.at(lo);
+ const effort = effortScale(paced), start = effort.at(lo);
const dayEffort = (effort.at(hi) - start) / (daysBefore + daysAfter);
const center = Math.max(0, Math.min(1, effort.progress(start + dayEffort * daysBefore)));
if (night <= 0 || night >= count || hi <= lo) return { from: center, to: center, center, blocked: true };
@@ -393,12 +396,15 @@ function transferKm(stops: Stop[], from: number, to: number): number {
: km + Math.max(0, Math.min(to, stop.distance) - Math.max(from, stops[i].distance)), 0);
}
+/** The kinds of the points that `dayStops` lists. */
+export const stopKinds: PointKind[] = ['pass', 'waypoint', 'detour', 'marker'];
+
/** Stops inside a day in route order, with kilometres from the day start. */
export function dayStops(trip: Trip, line: RoutingLine | undefined, day: Pick): { point: RoutePoint; km: number }[] {
const layout = planView(trip, line), { stops } = layout;
const total = stops.at(-1)?.distance ?? 0;
const markers = trip.points.filter(p => p.kind === 'marker').map(point => ({ point, distance: markerKm(layout, point) }));
- return [...stops.filter(stop => ['pass', 'waypoint', 'detour'].includes(stop.point.kind)), ...markers]
+ return [...stops.filter(stop => stopKinds.includes(stop.point.kind)), ...markers]
// The first day also holds what lies at the start.
.filter(stop => (stop.distance > day.from * total || !day.from) && stop.distance <= day.to * total)
.sort((a, b) => a.distance - b.distance)
diff --git a/builder/web/src/lib/planner/gpx-import.test.ts b/builder/web/src/lib/planner/gpx-import.test.ts
index 10d2fc71c9..9aa00ca875 100644
--- a/builder/web/src/lib/planner/gpx-import.test.ts
+++ b/builder/web/src/lib/planner/gpx-import.test.ts
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { dayStops, guessDays, orderedRoutePoints, planView, type DrawnCoordinate } from './editor';
import { cumulative, kilometres, type Coordinate } from './geo';
import { profileAscent } from './profile-data';
-import { importedTrip, planOnRoads, readTracks } from './gpx-import';
+import { importedTrip, planFromFile, planOnRoads, readTracks } from './gpx-import';
import { exportPlan, importPlan, newPlan } from './library';
import { LegCache } from './route-legs';
import { calculateLine, requestShape } from './routing';
@@ -88,6 +88,17 @@ describe('GPX import', () => {
expect(dayStops(trip, line, days[1])[0].km).toBeCloseTo(kilometres(out.at(-1)!, [7.605, 47.5]), 6);
});
+ it('makes a plan of one day from a file, with its id and its summary, and no request', async () => {
+ const fetch = vi.fn();
+ vi.stubGlobal('fetch', fetch);
+ const points = track([7.6, 47.5], 50).map(([lon, lat], i) => ({ lat: Math.round(lat * 1e6), lon: Math.round(lon * 1e6), ele: 400 + i }));
+ const plan = await planFromFile({ name: 'Jura', points, waypoints: [{ lat: 47.5e6, lon: 7.61e6, name: 'Spring' }] }, 'file-1', 'hiking');
+ expect(plan).toMatchObject({ id: 'file-1', name: 'Jura', trip: { mode: 'route', bike: 'hiking' }, summary: { days: 1, bike: 'hiking', climbM: 49 } });
+ expect(orderedRoutePoints(plan.trip).map(p => p.leg)).toEqual([undefined, 'drawn']);
+ expect(plan.summary!.lengthM).toBeCloseTo(cumulative(track([7.6, 47.5], 50)).at(-1)! * 1000, -1);
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
it('rejects more files than a trip has days', () => {
const files = Array.from({ length: 15 }, (_, i) => ({ name: `${i}.gpx`, text: gpx(track([7.6, 47.5], 2)) }));
expect(() => readTracks(files)).toThrow('A trip has at most 14 days. Import 14 files or fewer.');
diff --git a/builder/web/src/lib/planner/gpx-import.ts b/builder/web/src/lib/planner/gpx-import.ts
index 84ab34d084..bd9519afd9 100644
--- a/builder/web/src/lib/planner/gpx-import.ts
+++ b/builder/web/src/lib/planner/gpx-import.ts
@@ -1,7 +1,10 @@
-import { readGpx } from '../core/gpx';
+import { readGpx, type GpxImport } from '../core/gpx';
+import type { Bike } from '../library/records';
import { emptyTrip, maxRidingDays, type DrawnCoordinate, type RoutePoint, type Trip } from './editor';
import { kilometres, nearestOnLine, simplify, type Coordinate } from './geo';
-import type { Shape } from './routing';
+import { newPlan, planSummary, type Plan } from './library';
+import { LegCache } from './route-legs';
+import { calculateLine, type Shape } from './routing';
/** One imported file: its name, its simplified line with the file's elevations, its waypoints and, when planned on roads,
* its shape. */
@@ -17,21 +20,33 @@ const toleranceKm = .003;
/** Two days whose ends are farther apart than this are joined by a transfer. */
const transferMinKm = 0.2;
+/** The line of a GPX file or a FIT course, simplified, with its waypoints. */
+export function importedLine(name: string, { points, waypoints }: Pick): ImportedLine {
+ const line = points.map((p): DrawnCoordinate => p.ele === undefined ? [p.lon / 1e6, p.lat / 1e6] : [p.lon / 1e6, p.lat / 1e6, p.ele]);
+ return { name, line: simplify(line, toleranceKm).map(i => line[i]),
+ waypoints: waypoints.map(w => ({ label: w.name ?? 'Marker', coordinate: [w.lon / 1e6, w.lat / 1e6], ...w.note ? { note: w.note } : {} })) };
+}
+
/** One day per file, in the given order. */
export function readTracks(files: { name: string; text: string }[]): ImportedLine[] {
if (files.length > maxRidingDays) throw new Error(`A trip has at most ${maxRidingDays} days. Import ${maxRidingDays} files or fewer.`);
return files.map(file => {
try {
- const { name, points, waypoints } = readGpx(file.text, file.name.replace(/\.gpx$/i, ''));
- const line = points.map((p): DrawnCoordinate => p.ele === undefined ? [p.lon / 1e6, p.lat / 1e6] : [p.lon / 1e6, p.lat / 1e6, p.ele]);
- return { name, line: simplify(line, toleranceKm).map(i => line[i]),
- waypoints: waypoints.map(w => ({ label: w.name ?? 'Marker', coordinate: [w.lon / 1e6, w.lat / 1e6], ...w.note ? { note: w.note } : {} })) };
+ const track = readGpx(file.text, file.name.replace(/\.gpx$/i, ''));
+ return importedLine(track.name, track);
} catch (error) {
throw new Error(`${file.name}: ${(error as Error).message}`);
}
});
}
+/** A plan of one day that keeps the line of the file as one drawn leg, with its calculated summary. */
+export async function planFromFile(track: Pick, id: string, bike: Bike): Promise {
+ const trip = importedTrip({ bike }, [importedLine(track.name, track)]);
+ const line = await calculateLine(trip, new AbortController().signal, new LegCache());
+ return { ...newPlan(trip, track.name), id, summary: planSummary(trip, line) };
+}
+
/** Shapes the lines one at a time, so an import never sends parallel requests. Any failure, such as a busy service, keeps
* the file's line and names the file in `failed`. */
export async function planOnRoads(lines: ImportedLine[], shape: (line: Coordinate[]) => Promise): Promise<{ lines: ImportedLine[]; failed: string[] }> {
diff --git a/builder/web/src/lib/planner/grade-data.ts b/builder/web/src/lib/planner/grade-data.ts
index c9f8dc1f05..f17608ee3e 100644
--- a/builder/web/src/lib/planner/grade-data.ts
+++ b/builder/web/src/lib/planner/grade-data.ts
@@ -45,6 +45,22 @@ export const gradeBands = [
export const gradeThresholds = [3, 6, 10, 15, 20];
+/** SVG paths of the line of a profile, one for each band of `gradeBands`, in the box of `profilePaths`. */
+export function gradePaths(samples: readonly { progress: number; height: number | null }[], grades: readonly (number | null)[], low: number, high: number): string[] {
+ const paths = gradeBands.map(() => '');
+ const y = (height: number) => 105 - (height - low) / (high - low) * 100;
+ let previous = -1;
+ for (let i = 0; i < grades.length; i++) {
+ const a = samples[i], b = samples[i + 1];
+ if (a.height === null || b.height === null) { previous = -1; continue; }
+ const band = gradeBand(grades[i]);
+ if (band !== previous) paths[band] += `M${a.progress * 1000} ${y(a.height)}`;
+ paths[band] += `L${b.progress * 1000} ${y(b.height)}`;
+ previous = band;
+ }
+ return paths;
+}
+
export function gradeBand(grade: number | null): number {
if (grade === null || !Number.isFinite(grade)) return 11;
const magnitude = Math.round(Math.abs(grade) * 10) / 10;
diff --git a/builder/web/src/lib/planner/library.test.ts b/builder/web/src/lib/planner/library.test.ts
index b3bf71592e..43e3c1fcea 100644
--- a/builder/web/src/lib/planner/library.test.ts
+++ b/builder/web/src/lib/planner/library.test.ts
@@ -1,113 +1,25 @@
-import { IDBFactory } from 'fake-indexeddb';
import { describe, expect, it } from 'vitest';
-import { emptyTrip, setEndpoint, pinNight, addRestDay, setDrawnLeg } from './editor';
-import { PlanLibrary, exportPlan, importPlan, newPlan } from './library';
+import { pinNight, addRestDay, setDrawnLeg } from './editor';
+import { exportPlan, importPlan, newPlan, planSummary } from './library';
import { newVersion } from './versions';
-import { testTrip } from '../../../test-support/planner/trip';
+import { testLine, testTrip } from '../../../test-support/planner/trip';
-/** Runs `work` on the plans store of the library database, outside `PlanLibrary`. */
-async function rawPlans(factory: IDBFactory, work: (plans: IDBObjectStore) => IDBRequest | void, version?: number): Promise {
- const db = await new Promise(resolve => {
- const request = factory.open('obc-planner-plans', version);
- request.onupgradeneeded = () => { request.result.createObjectStore('plans', { keyPath: 'id' }); request.result.createObjectStore('state'); };
- request.onsuccess = () => resolve(request.result);
- });
- const tx = db.transaction('plans', 'readwrite'), request = work(tx.objectStore('plans'));
- await new Promise(resolve => tx.oncomplete = resolve);
- db.close();
- return request?.result;
-}
-
-describe('local plan library', () => {
- it('keeps independent plans and their versions, resumes the active one and removes its pointer on deletion', async () => {
- const factory = new IDBFactory();
- const store = new PlanLibrary(factory);
- const first = await store.save(newPlan(testTrip(), 'Weekend'));
- const versioned = await store.save(first, [newVersion(first.trip, undefined, 'Valley')]);
- // An edit without versions leaves the saved versions as they are.
- await store.save({ ...versioned, name: 'Weekend edit' });
- const second = await store.save(newPlan(setEndpoint(emptyTrip(), 'start', [8, 48], 'Home'), 'Next ride'));
- await store.activate(second.id);
- await store.close();
- const reopened = new PlanLibrary(factory);
- expect((await reopened.active())?.id).toBe(second.id);
- expect((await reopened.list()).plans.map(p => p.name)).toEqual(['Next ride', 'Weekend edit']);
- expect((await reopened.versions(first.id)).map(v => v.name)).toEqual(['Valley']);
- expect(await reopened.versions(second.id)).toEqual([]);
- await reopened.remove((await reopened.get(first.id))!);
- expect(await reopened.versions(first.id)).toEqual([]);
- await reopened.remove(second);
- expect(await reopened.active()).toBeUndefined();
- expect((await reopened.list()).plans).toEqual([]);
- await reopened.close();
- });
-
- it('lists only valid plans, counts the others and deletes them on request', async () => {
- const factory = new IDBFactory();
- const store = new PlanLibrary(factory);
- const valid = await store.save(newPlan(testTrip(), 'Valid'));
- const broken = await store.save(newPlan(testTrip(), 'Broken'), [newVersion(testTrip(), undefined)]);
- await store.close();
- await rawPlans(factory, plans => { plans.put({ ...broken, trip: {} }); });
- const reopened = new PlanLibrary(factory);
- expect(await reopened.list()).toEqual({ plans: [valid], unreadable: 1 });
- await expect(reopened.get(broken.id)).rejects.toThrow('invalid');
- await reopened.removeUnreadable();
- expect(await reopened.list()).toEqual({ plans: [valid], unreadable: 0 });
- expect(await reopened.versions(broken.id)).toEqual([]);
- await reopened.close();
- });
-
- it('keeps the plans of a version 1 library and saves them without the versions they held', async () => {
- const factory = new IDBFactory();
- const old = { ...newPlan(testTrip(), 'Old'), revision: 1, versions: [newVersion(testTrip(), undefined, 'Inside')] };
- await rawPlans(factory, plans => { plans.put(old); }, 1);
- const store = new PlanLibrary(factory);
- const [listed] = (await store.list()).plans;
- expect(listed).toEqual({ id: old.id, revision: 1, name: 'Old', updatedAt: old.updatedAt, summary: old.summary, trip: old.trip });
- await store.save({ ...listed, name: 'Kept' });
- await store.close();
- expect(await rawPlans(factory, plans => plans.get(old.id))).not.toHaveProperty('versions');
- });
-
- it('orders rapid edits and refuses unseen edits or deletion from another tab', async () => {
- const factory = new IDBFactory();
- const first = new PlanLibrary(factory), second = new PlanLibrary(factory);
- const plan = await first.save(newPlan(testTrip(), 'Original'));
- await first.activate(plan.id);
- const stale = (await second.active())!;
- await Promise.all([first.save({ ...plan, name: 'First edit' }), first.save({ ...plan, name: 'Last edit' })]);
- expect((await first.list()).plans[0]).toMatchObject({ name: 'Last edit', revision: 3 });
- await expect(second.save({ ...stale, name: 'Unseen overwrite' })).rejects.toThrow('another tab');
- await expect(second.remove(stale)).rejects.toThrow('changed');
- const latest = (await second.get(plan.id))!;
- await second.save({ ...latest, name: 'After reopening' });
- expect((await first.list()).plans[0].name).toBe('After reopening');
- await first.close(); await second.close();
- });
-
- it('accepts a refreshed catalog revision while keeping stale active edits protected', async () => {
- const factory = new IDBFactory();
- const first = new PlanLibrary(factory), second = new PlanLibrary(factory);
- const original = await first.save(newPlan(testTrip(), 'Original'));
- const other = (await second.get(original.id))!;
- await second.save({ ...other, name: 'Other tab' });
- const [refreshed] = (await first.list()).plans;
- await expect(first.save({ ...original, name: 'Stale active edit' })).rejects.toThrow('another tab');
- const renamed = await first.save({ ...refreshed, name: 'Catalog rename' });
- expect(renamed).toMatchObject({ name: 'Catalog rename', revision: 3 });
- await expect(second.save({ ...other, name: 'Unseen edit' })).rejects.toThrow('another tab');
- await first.close(); await second.close();
- });
-
- it('round-trips nights, dates, rest days and drawings with its versions under a new identity', () => {
- const trip = { ...addRestDay(pinNight(testTrip(), undefined, 1, [7.2, 47.5], 'Camp'), 1), startDate: '2026-10-04' };
+describe('plan file', () => {
+ it('round-trips nights, dates, the pace, rest days and drawings with its versions under a new identity', () => {
+ const trip = { ...addRestDay(pinNight(testTrip(), undefined, 1, [7.2, 47.5], 'Camp'), 1), startDate: '2026-10-04', pace: 'easy' as const };
const drawn = setDrawnLeg(trip, 'finish', [[7, 47.5]]);
const plan = newPlan(drawn, 'Autumn tour'), versions = [newVersion(trip, undefined, 'Before the detour')];
const imported = importPlan(exportPlan(plan, versions));
expect(imported.plan.id).not.toBe(plan.id);
expect(imported.plan).toMatchObject({ revision: 0, name: plan.name, trip: JSON.parse(JSON.stringify(drawn)) });
expect(imported.versions).toMatchObject(JSON.parse(JSON.stringify(versions)));
+ expect([imported.plan.trip.pace, imported.versions[0].trip.pace]).toEqual(['easy', 'easy']);
+ });
+
+ it('writes the riding time at the pace of the plan into its summary', () => {
+ const trip = testTrip(), line = testLine(trip);
+ expect(planSummary(trip, line).seconds).toBe(Math.round(line.seconds));
+ expect(planSummary({ ...trip, pace: 'fast' }, line).seconds).toBe(Math.round(line.seconds * 19 / 27));
});
it('writes the keys the companion app needs into each plan object, and keeps an open version that the file has', () => {
diff --git a/builder/web/src/lib/planner/library.ts b/builder/web/src/lib/planner/library.ts
index 626fdfb4a5..e9623633c0 100644
--- a/builder/web/src/lib/planner/library.ts
+++ b/builder/web/src/lib/planner/library.ts
@@ -1,193 +1,39 @@
-import type { Trip } from './editor';
+import type { RouteRecord, RouteSummary } from '../library/records';
+import { summarize } from '../library/summary';
+import { planView, type Trip } from './editor';
+import type { RoutingLine } from './routing';
import { isTrip } from './trip-validation';
import { planTitle, versionSummary, type Version } from './versions';
-/** A plan record of the browser library. Its versions are a separate record, written only when they change. */
-export interface Plan {
- id: string;
- revision: number;
- name: string;
- updatedAt: number;
- summary: string;
+/** A route of the library whose trip the planner can open. Its versions are a separate record, written only when they
+ * change. */
+export interface Plan extends RouteRecord {
trip: Trip;
- /** The ID of the saved version that `trip` belongs to. */
- open?: string;
}
export function newPlan(trip: Trip, name = ''): Plan {
- return { id: crypto.randomUUID(), revision: 0, name: name.trim().slice(0, 120), updatedAt: Date.now(), summary: versionSummary(trip, undefined), trip };
+ return { id: crypto.randomUUID(), revision: 0, name: name.trim().slice(0, 120), updatedAt: Date.now(), summary: null, trip };
}
-function isPlan(value: unknown): value is Plan {
- const plan = value as Partial | null;
- return !!plan && typeof plan.id === 'string' && !!plan.id && Number.isInteger(plan.revision) && typeof plan.name === 'string'
- && Number.isFinite(plan.updatedAt) && typeof plan.summary === 'string' && isTrip(plan.trip)
- && (plan.open === undefined || typeof plan.open === 'string');
-}
-
-// Only the fields of a plan: a record of a version 1 library also holds its versions, which a save must not write back.
-function fields({ id, revision, name, updatedAt, summary, trip, open }: Plan): Plan {
- return { id, revision, name, updatedAt, summary, trip, ...open !== undefined && { open } };
-}
+export const isPlan = (route: RouteRecord): route is Plan => isTrip(route.trip);
-function isVersion(value: unknown): value is Version {
+export function isVersion(value: unknown): value is Version {
const v = value as Partial | null;
return !!v && isTrip(v.trip) && typeof v.id === 'string' && !!v.id && typeof v.at === 'string' && Number.isFinite(Date.parse(v.at))
&& new Date(v.at).toISOString() === v.at && (v.name === undefined || (typeof v.name === 'string' && v.name.length <= 120));
}
-/** Writes are ordered within a tab; revisions prevent a second tab from replacing unseen edits. */
-export class PlanLibrary {
- private database?: Promise;
- private pending: Promise = Promise.resolve();
- private revisions = new Map();
-
- constructor(private factory: IDBFactory = indexedDB) {}
-
- private open(): Promise {
- return this.database ??= new Promise((resolve, reject) => {
- const request = this.factory.open('obc-planner-plans', 2);
- request.onupgradeneeded = () => {
- const db = request.result;
- // A version 1 library keeps its plans; the versions inside their records are lost.
- if (!db.objectStoreNames.contains('plans')) db.createObjectStore('plans', { keyPath: 'id' });
- for (const store of ['versions', 'state']) if (!db.objectStoreNames.contains(store)) db.createObjectStore(store);
- };
- request.onsuccess = () => {
- const db = request.result;
- db.onversionchange = () => db.close();
- resolve(db);
- };
- request.onerror = () => reject(request.error);
- request.onblocked = () => reject(new Error('Close other planner tabs and try again.'));
- }).catch(error => { this.database = undefined; throw error; });
- }
-
- private async read(store: string, key?: string): Promise {
- const db = await this.open();
- return new Promise((resolve, reject) => {
- const tx = db.transaction(store);
- const request = key === undefined ? tx.objectStore(store).getAll() : tx.objectStore(store).get(key);
- tx.oncomplete = () => resolve(request.result);
- tx.onabort = () => reject(tx.error);
- });
- }
-
- /** The valid plans, most recently edited first, and the number of records that are not valid plans. */
- async list(): Promise<{ plans: Plan[]; unreadable: number }> {
- await this.pending;
- const records = await this.read('plans') as unknown[];
- const plans = records.filter(isPlan).map(fields).sort((a, b) => b.updatedAt - a.updatedAt);
- return { plans, unreadable: records.length - plans.length };
- }
-
- /** The valid versions of a plan, newest first. */
- async versions(id: string): Promise {
- const versions = await this.read('versions', id);
- return Array.isArray(versions) ? versions.filter(v => isVersion(v) && typeof v.summary === 'string') : [];
- }
-
- async active(): Promise {
- const id = await this.read('state', 'active');
- if (typeof id !== 'string') return undefined;
- return this.get(id);
- }
-
- async get(id: string): Promise {
- const plan = await this.read('plans', id);
- if (plan === undefined) return undefined;
- if (!isPlan(plan)) throw new Error('Saved plan is invalid. Open another plan or import a backup.');
- this.revisions.set(id, plan.revision);
- return fields(plan);
- }
-
- private enqueue(work: () => Promise): Promise {
- const result = this.pending.then(work);
- this.pending = result.catch(() => {});
- return result;
- }
-
- /** Saves the plan, and its versions when they are given. */
- save(plan: Plan, versions?: Version[]): Promise {
- const snapshot = structuredClone(plan), kept = versions && structuredClone(versions);
- return this.enqueue(async () => {
- const db = await this.open();
- return new Promise((resolve, reject) => {
- const tx = db.transaction(kept ? ['plans', 'versions'] : 'plans', 'readwrite');
- const store = tx.objectStore('plans');
- const request = store.get(snapshot.id);
- let next: Plan;
- let conflict = false;
- let failure: unknown;
- request.onsuccess = () => {
- const expected = Math.max(this.revisions.get(snapshot.id) ?? 0, snapshot.revision);
- if ((request.result?.revision ?? 0) !== expected) { conflict = true; tx.abort(); return; }
- next = { ...snapshot, revision: expected + 1 };
- try {
- store.put(next);
- if (kept) tx.objectStore('versions').put(kept, next.id);
- }
- catch (error) { failure = error; tx.abort(); }
- };
- tx.oncomplete = () => { this.revisions.set(next.id, next.revision); resolve(next); };
- tx.onabort = () => reject(conflict ? new Error('This plan changed in another tab. Download your edits before reopening it.') : failure ?? tx.error);
- });
- });
- }
-
- activate(id: string | null): Promise {
- return this.enqueue(async () => {
- const db = await this.open();
- await new Promise((resolve, reject) => {
- const tx = db.transaction('state', 'readwrite');
- tx.objectStore('state').put(id, 'active');
- tx.oncomplete = () => resolve();
- tx.onabort = () => reject(tx.error);
- });
- });
- }
-
- remove(plan: Plan): Promise {
- return this.enqueue(async () => {
- const db = await this.open();
- await new Promise((resolve, reject) => {
- const tx = db.transaction(['plans', 'versions', 'state'], 'readwrite');
- const store = tx.objectStore('plans');
- const request = store.get(plan.id);
- let conflict = false;
- request.onsuccess = () => {
- if (request.result && request.result.revision !== plan.revision) { conflict = true; tx.abort(); return; }
- store.delete(plan.id);
- tx.objectStore('versions').delete(plan.id);
- };
- const active = tx.objectStore('state').get('active');
- active.onsuccess = () => { if (active.result === plan.id) tx.objectStore('state').delete('active'); };
- tx.oncomplete = () => resolve();
- tx.onabort = () => reject(conflict ? new Error('This plan changed. Reopen My plans before deleting it.') : tx.error);
- });
- });
- }
-
- /** Deletes the records that are not valid plans, with their versions. */
- removeUnreadable(): Promise {
- return this.enqueue(async () => {
- const db = await this.open();
- await new Promise((resolve, reject) => {
- const tx = db.transaction(['plans', 'versions'], 'readwrite');
- const cursor = tx.objectStore('plans').openCursor();
- cursor.onsuccess = () => {
- const record = cursor.result;
- if (!record) return;
- if (!isPlan(record.value)) { record.delete(); tx.objectStore('versions').delete(record.primaryKey); }
- record.continue();
- };
- tx.oncomplete = () => resolve();
- tx.onabort = () => reject(tx.error);
- });
- });
- }
-
- async close(): Promise { (await this.database)?.close(); }
+// The simplified line depends only on the routed line; the numbers also follow the days and the bike of the trip.
+const shapes = new WeakMap();
+
+/** The summary of a plan with its calculated line. */
+export function planSummary(trip: Trip, line: RoutingLine): RouteSummary {
+ const view = planView(trip, line), { distance, hours, ascent } = view.summary;
+ const numbers = { lengthM: Math.round(distance * 1000), climbM: Math.round(ascent), seconds: Math.round(hours * 3600),
+ bike: trip.bike ?? 'touring', days: Math.max(1, view.itinerary.length) };
+ let shape = shapes.get(line);
+ if (!shape) shapes.set(line, shape = summarize(line.coordinates.map(([lon, lat], i) => [lon, lat, line.elevation[i]]), numbers));
+ return { ...shape, ...numbers };
}
// The companion app requires these keys; the web planner ignores them.
diff --git a/builder/web/src/lib/planner/map-setup.ts b/builder/web/src/lib/planner/map-setup.ts
new file mode 100644
index 0000000000..eab7e75672
--- /dev/null
+++ b/builder/web/src/lib/planner/map-setup.ts
@@ -0,0 +1,24 @@
+/** The style config and the MapLibre worker and protocols that each map of the app needs. */
+import * as maplibregl from 'maplibre-gl';
+import mapWorkerUrl from 'maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url';
+import { Protocol } from 'pmtiles';
+import { config } from './map-data';
+import { releaseProtocol, releaseUrl } from './release';
+
+// MapLibre loads the release objects of the style through `releaseProtocol`.
+export const styleConfig = { ...config, basemap: releaseUrl(config.basemap), glyphs: releaseUrl(config.glyphs), sprites: releaseUrl(config.sprites) };
+
+/** The credits of a view of the map: the basemap (OSM data, its land cover, Protomaps), the terrain and `layers`. */
+export const creditsWith = (layers: string[]) =>
+ [...new Set([config.attribution, config.landcover_attribution ?? '', 'Protomaps', config.terrain_attribution, ...layers].filter(Boolean))];
+
+let registered = false;
+
+/** Sets the worker of MapLibre and its protocols `pmtiles` and `release`, once for the page. */
+export function useMapProtocols(): void {
+ if (registered) return;
+ registered = true;
+ maplibregl.setWorkerUrl(mapWorkerUrl);
+ maplibregl.addProtocol('pmtiles', new Protocol().tile);
+ maplibregl.addProtocol('release', releaseProtocol);
+}
diff --git a/builder/web/src/lib/planner/plan-session.svelte.ts b/builder/web/src/lib/planner/plan-session.svelte.ts
index 52b8f78844..309dc81b76 100644
--- a/builder/web/src/lib/planner/plan-session.svelte.ts
+++ b/builder/web/src/lib/planner/plan-session.svelte.ts
@@ -2,7 +2,8 @@ import { SvelteMap } from 'svelte/reactivity';
import { anchorMarker, emptyTrip, guessedTrip, hasEndpoints, insertPoint, orderedRoutePoints, pinNight, planTitle, routeLegsAround, type RoutePoint, type Trip } from './editor';
import type { Coordinate } from './geo';
import { importedTrip, planOnRoads, readTracks, type ImportedLine } from './gpx-import';
-import { downloadPlan, importPlan, newPlan, PlanLibrary, type Plan } from './library';
+import type { Library } from '../library/store';
+import { downloadPlan, importPlan, isPlan, isVersion, newPlan, planSummary, type Plan } from './library';
import { coordinateName, townName, visitName } from './point-names';
import { presetName } from './riding-profiles';
import { optionOrder } from './route-options';
@@ -12,7 +13,7 @@ import { calculateLine, profileId, requestAlternatives, requestShape, routingKey
import { planTrip, routeBase, type RoutePlan } from './signed-route-plan';
import type { CatalogRecord } from './signed-routes';
import { isTrip } from './trip-validation';
-import { newVersion, versionSummary, writeBack, type Version } from './versions';
+import { newVersion, writeBack, type Version } from './versions';
type Routed = { trip: Trip; line?: RoutingLine };
/** An Undo step: a trip and the saved version it belongs to. */
@@ -118,13 +119,14 @@ export class PlanSession {
private versionsRequest?: AbortController;
private readonly legs = new LegCache();
- private library?: PlanLibrary;
+ private library?: Library;
// The calculation in flight, or the one that failed, so a label edit neither restarts nor clears it.
private request?: { key: string; abort: AbortController };
private lastSave: Promise = Promise.resolve();
// A line arrived while `busy`; its summary is saved afterwards, so a failed version save leaves no trace.
private unsaved = false;
private closed = false;
+ private stopFollowing = () => {};
private readonly previews = routePreview((draft: Trip, signal: AbortSignal) => this.calculate(draft, signal), (trip, line) => {
this.preview = this.last = { trip, line };
this.previewStatus = 'Route preview · release to keep';
@@ -133,13 +135,15 @@ export class PlanSession {
/** `opened` runs after another plan replaces the trip, so the page can reset its view. */
constructor(private readonly opened: (plan: Plan) => void = () => {}) {}
- /** Opens the library and the plan that was active when the planner closed. */
- async start(factory?: IDBFactory): Promise {
+ /** Opens the plan that was active when the planner closed, and follows the changes of the open plan by other pages. */
+ async start(library: Library): Promise {
+ this.library = library;
+ this.stopFollowing = library.onChange((store, key) => { if (store === 'routes' && key === this.plan.id) void this.follow(key); });
try {
- this.library = new PlanLibrary(factory);
- const plan = await this.library.active();
+ const id = await library.state('active');
+ const plan = id ? await this.get(library, id) : undefined;
if (plan) {
- const versions = await this.library.versions(plan.id);
+ const versions = await this.versionsOf(library, plan.id);
if (!this.closed) this.install(plan, versions);
}
} catch (error) { this.saveError = storageError(error); }
@@ -148,11 +152,11 @@ export class PlanSession {
close(): void {
this.closed = true;
+ this.stopFollowing();
this.cancelPreview();
this.request?.abort.abort();
this.optionsRequest?.abort.abort();
this.versionsRequest?.abort();
- void this.library?.close();
}
/** Calculates the line of any plan with the leg cache of the session, such as a route of the catalog. */
@@ -307,17 +311,17 @@ export class PlanSession {
if (!this.ready) return Promise.resolve();
const plan = this.plan = this.snapshot(versions);
if (!plan.trip.points.length && !plan.revision) return Promise.resolve();
- const library = this.library;
- this.lastSave = library ? library.save(plan, versions).then(async saved => {
- await library.activate(saved.id);
+ // `ready` is set after `start` gave the library.
+ const library = this.library!;
+ this.lastSave = library.saveRoute(plan, versions).then(async saved => {
+ await library.setState('active', saved.id);
if (this.plan.id !== saved.id) return;
this.plan = { ...this.plan, revision: saved.revision };
if (versions) this.versions = versions;
this.savedAt = saved.updatedAt;
this.saveError = '';
this.plans = this.plans.map(p => p.id === saved.id ? saved : p);
- if (saved.revision === 1) void navigator.storage?.persist?.().catch(() => {});
- }) : Promise.reject(new Error('Browser storage is unavailable. Download your plan to keep it.'));
+ });
this.lastSave.catch(error => { if (this.plan.id === plan.id) this.saveError = storageError(error); });
return this.lastSave;
}
@@ -337,7 +341,7 @@ export class PlanSession {
/** Downloads a plan of the library; the open plan with its latest edits, also when the library fails. */
async download(plan: Plan = this.plan): Promise {
if (plan.id === this.plan.id) downloadPlan(this.snapshot(), this.versions);
- else await this.act(async library => downloadPlan(plan, await library.versions(plan.id)));
+ else await this.act(async library => downloadPlan(plan, await this.versionsOf(library, plan.id)));
}
listPlans(): Promise {
@@ -347,38 +351,36 @@ export class PlanSession {
});
}
- /** Opens a plan of the library. When the open plan has unsaved edits, only `discard` lets them go. */
- open(plan: Plan, discard: () => boolean): Promise {
+ /** Opens plan `id` of the library. When the open plan has unsaved edits, only `discard` lets them go. */
+ open(id: string, discard: () => boolean): Promise {
return this.act(async library => {
try { await this.lastSave; } catch { if (!discard()) return false; }
- const latest = await library.get(plan.id);
+ const latest = await this.get(library, id);
if (!latest) throw new Error('This plan was deleted. Reopen My plans.');
- const versions = await library.versions(latest.id);
- await library.activate(latest.id);
+ const versions = await this.versionsOf(library, latest.id);
+ await library.setState('active', latest.id);
this.install(latest, versions);
});
}
+ /** `follow` gives the open plan its new name. */
rename(plan: Plan, name: string): Promise {
return this.act(async library => {
- await this.lastSave;
- const active = plan.id === this.plan.id;
- const saved = await library.save({ ...(active ? this.snapshot() : plan), name, updatedAt: Date.now() });
- if (active) this.plan = { ...this.plan, name, revision: saved.revision };
+ await library.renameRoute(plan.id, name);
await this.list(library);
});
}
duplicate(plan: Plan): Promise {
const open = plan.id === this.plan.id, source = open ? this.snapshot() : plan;
- return this.create(async library => ({ plan: newPlan(source.trip, `${source.name || planTitle(source.trip)} (copy)`),
- versions: open ? this.versions : await library.versions(plan.id) }));
+ return this.create(async library => ({ plan: { ...newPlan(source.trip, `${source.name || planTitle(source.trip)} (copy)`), summary: source.summary },
+ versions: open ? this.versions : await this.versionsOf(library, plan.id) }));
}
/** Deletes the records of the library that are not valid plans. */
removeUnreadable(): Promise {
return this.act(async library => {
- await library.removeUnreadable();
+ for (const id of await this.unreadableIds(library)) await library.removeRoute(id);
await this.list(library);
});
}
@@ -388,7 +390,7 @@ export class PlanSession {
return this.act(async library => {
await this.lastSave.catch(() => {});
const active = plan.id === this.plan.id;
- await library.remove(active ? this.plan : plan);
+ await library.removeRoute(plan.id, (active ? this.plan : plan).revision);
if (active) this.install(newPlan(emptyTrip(this.trip.mode)), []);
await this.list(library);
});
@@ -434,15 +436,27 @@ export class PlanSession {
async newPlan(): Promise {
const done = await this.act(async library => {
await this.lastSave;
- await library.activate(null);
+ await library.setState('active', null);
this.install(newPlan({ ...emptyTrip(this.trip.mode), bike: this.trip.bike, preset: this.trip.preset }), []);
});
if (!done) this.saveError = this.libraryError;
return done;
}
+ /** Takes the stored name of the open plan after a write of this tab; a removed plan gives a new empty plan, and its
+ * failed save shows no error, as the error belongs to another plan. The library keeps the revision that this tab
+ * knows. */
+ private async follow(id: string): Promise {
+ const record = await this.library!.item(id).catch(() => null);
+ if (this.closed || this.plan.id !== id || record === null) return;
+ if (!record) this.install(newPlan(emptyTrip(this.trip.mode)), []);
+ else if (record.name !== this.plan.name) this.plan = { ...this.plan, name: record.name };
+ }
+
private snapshot(versions = this.versions): Plan {
- return { ...this.plan, trip: this.trip, open: this.openIn(versions), summary: versionSummary(this.trip, this.line), updatedAt: Date.now() };
+ // A save with no calculated line keeps the last summary.
+ const summary = this.line ? planSummary(this.trip, this.line) : this.plan.summary;
+ return { ...this.plan, trip: this.trip, open: this.openIn(versions), summary, updatedAt: Date.now() };
}
private step(next: Step, line?: RoutingLine): void {
@@ -468,7 +482,7 @@ export class PlanSession {
}
/** Runs a library action; its error shows in `libraryError`. True when it completed and was not cancelled. */
- private async act(work: (library: PlanLibrary) => Promise): Promise {
+ private async act(work: (library: Library) => Promise): Promise {
this.busy = true;
this.libraryError = '';
try {
@@ -485,19 +499,38 @@ export class PlanSession {
if (this.unsaved) { this.unsaved = false; this.autosave(); }
}
- private create(make: (library: PlanLibrary) => Created | Promise): Promise {
+ private create(make: (library: Library) => Created | Promise): Promise {
return this.act(async library => {
const { plan, versions = [] } = await make(library);
await this.lastSave;
- const saved = await library.save(plan, versions);
- await library.activate(saved.id);
+ const saved = await library.saveRoute(plan, versions);
+ await library.setState('active', saved.id);
this.install(saved, versions);
await this.list(library);
});
}
- private async list(library: PlanLibrary): Promise {
- ({ plans: this.plans, unreadable: this.unreadable } = await library.list());
+ /** The routes of the library that are plans, most recently edited first, and the number of the others. */
+ private async list(library: Library): Promise {
+ const routes = await library.routes();
+ this.plans = routes.filter(isPlan).sort((a, b) => b.updatedAt - a.updatedAt);
+ this.unreadable = routes.length - this.plans.length + (await library.unreadableRoutes()).length;
+ }
+
+ /** The ids of the records that are no route, and of the routes that are no plan. */
+ private async unreadableIds(library: Library): Promise {
+ return [...await library.unreadableRoutes(), ...(await library.routes()).filter(route => !isPlan(route)).map(route => route.id)];
+ }
+
+ private async get(library: Library, id: string): Promise {
+ const route = await library.route(id);
+ if (route && !isPlan(route)) throw new Error('Saved plan is invalid. Open another plan or import a backup.');
+ return route;
+ }
+
+ /** The valid versions of a plan, newest first. */
+ private async versionsOf(library: Library, id: string): Promise {
+ return (await library.versions(id)).filter((v): v is Version => isVersion(v) && typeof v.summary === 'string');
}
private install(plan: Plan, versions: Version[]): void {
diff --git a/builder/web/src/lib/planner/plan-session.test.ts b/builder/web/src/lib/planner/plan-session.test.ts
index 790452c658..2b84943ab3 100644
--- a/builder/web/src/lib/planner/plan-session.test.ts
+++ b/builder/web/src/lib/planner/plan-session.test.ts
@@ -2,7 +2,7 @@ import { IDBFactory } from 'fake-indexeddb';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { emptyTrip, orderedRoutePoints, setDays, type RoutePoint, type Trip } from './editor';
import type { Coordinate } from './geo';
-import { PlanLibrary } from './library';
+import { Library } from '../library/store';
import { PlanSession } from './plan-session.svelte';
import { newVersion } from './versions';
import * as routing from './routing';
@@ -55,6 +55,11 @@ const choice = (session: PlanSession) => session.routeOptions.state === 'ready'
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); });
+const active = async (library: Library) => {
+ const id = await library.state('active');
+ return id ? library.route(id) : undefined;
+};
+
describe('plan session', () => {
it('shows the last routed trip while a line is calculated, no line after a failure, and undoes without a request', async () => {
const routes = service();
@@ -86,27 +91,27 @@ describe('plan session', () => {
it('keeps the alternatives through picks: a corridor is one shaping point, a profile the preset, and its legs need no request', async () => {
const via: Coordinate = [8.05, 48.02];
const routes = service([alternative('corridor', 'corridor', 'touring', [[8, 48], via, [8.1, 48]], via),
- alternative('shorter', 'shorter', 'touring/shorter', [[8, 48], [8.1, 48]])]);
+ alternative('climb', 'less_climbing', 'touring/less-climbing', [[8, 48], [8.1, 48]])]);
const session = new PlanSession();
session.commit(plan);
await vi.waitFor(() => expect(session.line).toBeDefined());
session.findAlternatives();
await vi.waitFor(() => expect(choice(session)).toBe('primary'));
- const [primary, corridor, shorter] = options(session).routes;
+ const [primary, corridor, lower] = options(session).routes;
expect(routes.bodies().map(body => [body.points, body.alternatives_only])).toEqual([[[[8, 48], [8.1, 48]], undefined], [[[8, 48], [8.1, 48]], true]]);
const pick = async (route: typeof primary) => {
expect(session.pickAlternative(route)).toBe(true);
expect(choice(session)).toBe(route.id);
await vi.waitFor(() => expect(session.line).toBeDefined());
};
- await pick(shorter);
- expect(session.trip).toMatchObject({ preset: 'Shorter', points: plan.points });
+ await pick(lower);
+ expect(session.trip).toMatchObject({ preset: 'Less climbing', points: plan.points });
expect(routes.fetch).toHaveBeenCalledTimes(2);
await pick(corridor);
expect(session.trip.preset).toBe('Balanced');
expect(orderedRoutePoints(session.trip).map(p => [p.kind, p.coordinate])).toEqual([['start', [8, 48]], ['via', via], ['finish', [8.1, 48]]]);
expect(routes.bodies().at(-1)).toMatchObject({ points: [[8, 48], via, [8.1, 48]], profile: 'touring' });
- for (const route of [shorter, corridor, primary]) await pick(route);
+ for (const route of [lower, corridor, primary]) await pick(route);
expect(session.trip).toMatchObject({ preset: 'Balanced', points: plan.points });
expect(routes.fetch).toHaveBeenCalledTimes(3);
// The checked route adds no Undo step: one Undo returns to the corridor.
@@ -115,11 +120,40 @@ describe('plan session', () => {
expect(routes.fetch).toHaveBeenCalledTimes(3);
});
+ it('takes a rename of another page over its own later save, deletes its plan after a rename, and opens an empty plan when another page removes its plan', async () => {
+ service();
+ const library = new Library(new IDBFactory()), session = new PlanSession();
+ await session.start(library);
+ session.commit(plan);
+ await vi.waitFor(() => expect(session.line).toBeDefined());
+ await session.saved();
+ const id = session.plan.id;
+ await library.renameRoute(id, 'Lake loop');
+ await vi.waitFor(() => expect(session.plan.name).toBe('Lake loop'));
+ session.commit(moved(plan, 8.2));
+ expect(await session.saved()).toBe(true);
+ expect(await library.route(id)).toMatchObject({ name: 'Lake loop', trip: { points: moved(plan, 8.2).points } });
+ await session.rename(session.plan, 'Lake round');
+ await vi.waitFor(() => expect(session.plan.name).toBe('Lake round'));
+ expect(await session.remove(session.plan)).toBe(true);
+ expect(await library.route(id)).toBeUndefined();
+
+ session.commit(plan);
+ await vi.waitFor(() => expect(session.line).toBeDefined());
+ await session.saved();
+ const second = session.plan.id;
+
+ await library.removeRoute(second);
+ await vi.waitFor(() => expect(session.plan.id).not.toBe(second));
+ expect([session.trip.points, session.saveError]).toEqual([[], '']);
+ session.close();
+ });
+
it('previews an option without an edit, applies it as one Undo step, and refuses options of an earlier plan', async () => {
const via: Coordinate = [8.05, 48.02];
const routes = service([alternative('corridor', 'corridor', 'touring', [[8, 48], via, [8.1, 48]], via)]);
const session = new PlanSession();
- await session.start(new IDBFactory());
+ await session.start(new Library(new IDBFactory()));
session.commit(plan);
await vi.waitFor(() => expect(session.line).toBeDefined());
session.findAlternatives();
@@ -200,7 +234,7 @@ describe('plan session', () => {
it('calculates each saved version once, a failed one again on retry, and opens a version with its line', async () => {
const routes = service();
const session = new PlanSession();
- await session.start(new IDBFactory());
+ await session.start(new Library(new IDBFactory()));
session.commit(plan);
await vi.waitFor(() => expect(session.line).toBeDefined());
const valley = moved(plan, 8.2), ridge = moved(plan, 8.3);
@@ -224,7 +258,7 @@ describe('plan session', () => {
it('keeps the edits of the open version when another opens, and saves a plan of no version first', async () => {
service();
const session = new PlanSession();
- await session.start(new IDBFactory());
+ await session.start(new Library(new IDBFactory()));
session.commit(plan);
await session.saveNewVersion('A');
const a = session.openId!;
@@ -255,7 +289,7 @@ describe('plan session', () => {
service();
const factory = new IDBFactory();
const session = new PlanSession();
- await session.start(factory);
+ await session.start(new Library(factory));
session.commit(plan);
await session.saveNewVersion('A');
const a = session.openId;
@@ -266,14 +300,14 @@ describe('plan session', () => {
expect(session.undo()).toBe(true);
expect([session.trip, session.openId]).toEqual([moved(plan, 8.2), b]);
await session.saved();
- expect((await new PlanLibrary(factory).active())?.open).toBe(b);
+ expect((await active(new Library(factory)))?.open).toBe(b);
session.close();
});
it('keeps the earlier steps with the version saved from them, so Undo makes no copies and no empty version', async () => {
service();
const session = new PlanSession();
- await session.start(new IDBFactory());
+ await session.start(new Library(new IDBFactory()));
session.commit(plan);
session.commit(moved(plan, 8.2));
await session.saveNewVersion('A');
@@ -300,30 +334,53 @@ describe('plan session', () => {
it('duplicates a plan that is not open with the versions saved for it', async () => {
service();
const session = new PlanSession();
- await session.start(new IDBFactory());
+ await session.start(new Library(new IDBFactory()));
session.commit(plan);
+ await vi.waitFor(() => expect(session.line).toBeDefined());
await session.saveVersions([newVersion(plan, undefined, 'Valley')]);
const first = session.plan;
expect(await session.newPlan()).toBe(true);
expect(session.versions).toEqual([]);
expect(await session.duplicate(first)).toBe(true);
expect([session.plan.id === first.id, session.versions.map(v => v.name)]).toEqual([false, ['Valley']]);
+ expect(session.plan.summary).toEqual(first.summary);
+ expect(first.summary).not.toBeNull();
session.close();
});
- it('saves the plan without its line and calculates the line again when the plan opens', async () => {
+ it('counts the saved records that are not plans, and deletes them on request', async () => {
+ service();
+ const factory = new IDBFactory(), library = new Library(factory), session = new PlanSession();
+ await session.start(library);
+ await library.saveRoute({ id: 'no-trip', revision: 0, name: '', updatedAt: 1, summary: null, trip: {} });
+ const db = await new Promise(resolve => { const request = factory.open('obc-library'); request.onsuccess = () => resolve(request.result); });
+ const tx = db.transaction('routes', 'readwrite');
+ tx.objectStore('routes').put({ id: 'no-record' });
+ await new Promise(resolve => tx.oncomplete = resolve);
+ db.close();
+ expect(await session.listPlans()).toBe(true);
+ expect(session.unreadable).toBe(2);
+ expect(await session.removeUnreadable()).toBe(true);
+ expect([session.unreadable, await library.unreadableRoutes(), await library.routes()]).toEqual([0, [], []]);
+ session.close();
+ });
+
+ it('saves the plan with the summary of its line, and calculates the line again when the plan opens', async () => {
const routes = service();
const factory = new IDBFactory();
const first = new PlanSession();
- await first.start(factory);
+ await first.start(new Library(factory));
first.commit(plan);
- const library = new PlanLibrary(factory);
- await vi.waitFor(async () => expect((await library.active())?.summary).toMatch(/^Single route · \d+\.\d km$/));
- expect((await library.active())?.trip).toEqual(plan);
+ const library = new Library(factory);
+ await vi.waitFor(async () => expect((await active(library))?.summary).toBeTruthy());
+ const saved = (await active(library))!;
+ expect(saved.trip).toEqual(plan);
+ expect(saved.summary).toMatchObject({ line: [8, 48, 8.1, 48], days: 1, bike: 'touring', bounds: [8, 48, 8.1, 48] });
+ expect(saved.summary!.lengthM).toBeCloseTo(7440, -2);
first.close();
const opened = vi.fn();
const second = new PlanSession(opened);
- await second.start(factory);
+ await second.start(new Library(factory));
expect(opened).toHaveBeenCalledOnce();
expect([second.trip, second.canUndo]).toEqual([plan, false]);
await vi.waitFor(() => expect(second.line).toBeDefined());
@@ -358,4 +415,25 @@ describe('plan session', () => {
await vi.waitFor(() => expect(session.line).toBeDefined());
expect(session.trip).toMatchObject({ days: 5, daysSet: true });
});
+
+ it('changes the pace and the guessed days in one Undo step with no route request, and starts a new plan at Moderate', async () => {
+ service();
+ const calculate = vi.spyOn(routing, 'calculateLine').mockImplementation(async trip => {
+ const line = testLine(trip), seconds = 25 * 3600;
+ return { ...line, elapsed: line.elapsed.map(s => s * seconds / line.seconds), seconds };
+ });
+ const session = new PlanSession();
+ await session.start(new Library(new IDBFactory()));
+ session.commit({ ...plan, daysSet: undefined });
+ await vi.waitFor(() => expect(session.trip.days).toBe(4));
+ session.commit({ ...session.trip, pace: 'fast' });
+ expect([session.trip.days, session.stale]).toEqual([3, false]);
+ expect(session.undo()).toBe(true);
+ expect([session.trip.pace, session.trip.days]).toEqual([undefined, 4]);
+ expect(calculate).toHaveBeenCalledOnce();
+ session.redo();
+ expect(await session.newPlan()).toBe(true);
+ expect(session.trip.pace).toBeUndefined();
+ session.close();
+ });
});
diff --git a/builder/web/src/lib/planner/profile-data.ts b/builder/web/src/lib/planner/profile-data.ts
index 605a569034..66bad7278f 100644
--- a/builder/web/src/lib/planner/profile-data.ts
+++ b/builder/web/src/lib/planner/profile-data.ts
@@ -1,3 +1,4 @@
+import { heightIn } from '../settings/format';
import type { RoutingLine } from './routing';
import { cumulative, firstIndex } from './geo';
@@ -19,13 +20,15 @@ export function profileSamples(line?: ProfileLine): readonly ProfileSample[] {
return samples;
}
-/** Whole hundreds of metres that hold every known height of the sample lists; 0 to 100 m without one. */
+/** Whole hundreds of the height unit of the rider (`heightUnit()`) that hold every known height of the sample lists, in
+ * metres; 0 to 100 of that unit without one. */
export function heightRange(...lists: (readonly ProfileSample[])[]): { low: number; high: number } {
let min = Infinity, max = -Infinity;
for (const list of lists) for (const { height } of list) if (height !== null) { min = Math.min(min, height); max = Math.max(max, height); }
- if (min === Infinity) return { low: 0, high: 100 };
- const low = Math.floor(min / 100) * 100;
- return { low, high: Math.max(low + 100, Math.ceil(max / 100) * 100) };
+ const step = 100 / heightIn(1);
+ if (min === Infinity) return { low: 0, high: step };
+ const low = Math.floor(min / step) * step;
+ return { low, high: Math.max(low + step, Math.ceil(max / step) * step) };
}
/** SVG paths of a profile in a 1000 × 105 box between the heights `low` and `high`: one line, and the area below it, for
diff --git a/builder/web/src/lib/planner/riding-profiles.ts b/builder/web/src/lib/planner/riding-profiles.ts
index 738d7e7897..bb6680f8c4 100644
--- a/builder/web/src/lib/planner/riding-profiles.ts
+++ b/builder/web/src/lib/planner/riding-profiles.ts
@@ -1,29 +1,67 @@
-/** `kmh` times a manual leg: the route engine's default pace for the activity on flat ground (`specs/route-api.md`, `cycling_pace` in route-engine `model.rs`). */
+/** `kmh` is the speed on the flat at Moderate, chosen by the owner for each activity. `engineKmh` is the speed on the
+ * flat of the route engine for the activity (`specs/route-api.md`, `cycling_pace` in route-engine `model.rs`), which times
+ * a manual leg before the pace. */
export const ridingProfiles = {
- road: { icon: 'road', label: 'Road bike', kmh: 19 },
- gravel: { icon: 'gravel', label: 'Gravel bike', kmh: 19 },
- touring: { icon: 'touring', label: 'Touring bike', kmh: 19 },
- mtb: { icon: 'mtb', label: 'Mountain bike', kmh: 15.6 },
- hiking: { icon: 'hiking', label: 'Hiking', kmh: 4.5 },
+ road: { icon: 'road', label: 'Road bike', kmh: 25, engineKmh: 19 },
+ gravel: { icon: 'gravel', label: 'Gravel bike', kmh: 21, engineKmh: 19 },
+ touring: { icon: 'touring', label: 'Touring bike', kmh: 19, engineKmh: 19 },
+ mtb: { icon: 'mtb', label: 'Mountain bike', kmh: 15.6, engineKmh: 15.6 },
+ hiking: { icon: 'hiking', label: 'Hiking', kmh: 4.5, engineKmh: 4.5 },
};
export type BikeType = keyof typeof ridingProfiles;
-/** The preset title of each profile ID suffix: `touring/shorter` is the Shorter preset of the touring bike. The routing
- * region says which profiles it serves (`GET /v1/region`). Technical (MTB) and Alpine (hiking) allow harder trails. */
-const presetTitles: Record = { '': 'Balanced', shorter: 'Shorter', 'less-climbing': 'Less climbing', technical: 'Technical', alpine: 'Alpine' };
-const skillSuffixes = ['technical', 'alpine'];
-/** Every preset title that a plan can keep. */
-export const presetNames = Object.values(presetTitles);
+/** The speed of each pace against Moderate: a touring bike rides at 15, 19, 23 or 27 km/h on the flat. */
+export const paces = {
+ easy: { label: 'Easy', speed: 15 / 19 },
+ moderate: { label: 'Moderate', speed: 1 },
+ sporty: { label: 'Sporty', speed: 23 / 19 },
+ fast: { label: 'Fast', speed: 27 / 19 },
+};
+export type Pace = keyof typeof paces;
+
+/** The pace of a plan: Moderate when the plan has none or one that this reader does not know (`specs/planner-plan.md`). */
+export function planPace(trip: { pace?: string }): Pace {
+ return trip.pace !== undefined && Object.hasOwn(paces, trip.pace) ? trip.pace as Pace : 'moderate';
+}
+
+/** The factor on the riding time of the route engine: its speed on the flat over the speed of the plan's activity at the
+ * plan's pace. */
+export function paceFactor(trip: { bike?: BikeType; pace?: string }): number {
+ const profile = ridingProfiles[trip.bike ?? 'touring'];
+ return profile.engineKmh / (profile.kmh * paces[planPace(trip)].speed);
+}
+
+/** The preset title of each profile ID suffix: `touring/less-climbing` is the Less climbing preset of the touring bike. The
+ * routing region says which profiles it serves (`GET /v1/region`). Technical (MTB) and Alpine (hiking) allow harder trails. */
+const presetTitles: Record = { '': 'Balanced', 'less-climbing': 'Less climbing', technical: 'Technical', alpine: 'Alpine' };
+/** The presets of each activity, Balanced first (`specs/planner-plan.md`). */
+const activityPresets: Record