From b6982c8aee2c64ed0474ae891d0d0357cfb3e2d9 Mon Sep 17 00:00:00 2001 From: timohueser Date: Sun, 15 Nov 2026 22:01:29 +0100 Subject: [PATCH 1/6] web: delete the old map builder page and its developer editor The web app at /plan/ is the only page. The entry of /builder/, the parts that only it used, the style and schema editor, its Python server and the task `obc web` go. The web host is the one host in every mode, so `npm run dev`, `npm run build`, `npm run check` and vitest use it. `MapRun.download()` and `sendMapFile` go: no page saves a map as a file. The three base map cases move to the area page. The suites web.builder-browser, live.builder-memory and python.builder, and the CI job builder-python, go. The deploy no longer builds /builder/, and the Maps links point at the Device page. Co-Authored-By: Claude Opus --- .cairn/baseline.json | 2 - .github/workflows/ci.yml | 86 +- .github/workflows/deploy-site.yml | 24 +- .gitignore | 7 +- builder/__init__.py | 11 - builder/palette.json | 70 -- builder/server/__init__.py | 1 - builder/server/__main__.py | 25 - builder/server/paths.py | 21 - builder/server/schema_preview.py | 386 ------ builder/server/server.py | 252 ---- builder/tests/test_routing_profiles.py | 229 ---- builder/tests/test_schema_preview.py | 307 ----- builder/tests/test_schema_source.py | 111 -- builder/web/index.html | 24 - builder/web/package.json | 5 +- builder/web/public/osm_catalog.json | 84 -- builder/web/src/App.svelte | 129 -- builder/web/src/Shell.svelte | 1 - .../web/src/components/ConfirmDialog.svelte | 102 -- builder/web/src/components/Header.svelte | 86 -- .../web/src/components/UpdatePrompt.svelte | 106 -- .../components/advanced/CategoryRail.svelte | 119 -- .../advanced/ClimbWeightCell.svelte | 117 -- .../components/advanced/ColorControl.svelte | 189 --- .../components/advanced/LodSegments.svelte | 58 - .../src/components/advanced/LodTiers.svelte | 232 ---- .../components/advanced/MultiplierCell.svelte | 160 --- .../advanced/OptionalColorControl.svelte | 99 -- .../src/components/advanced/OutputTab.svelte | 158 --- .../components/advanced/ProfilesTab.svelte | 261 ---- .../advanced/ProfilesTab.svelte.test.ts | 112 -- .../components/advanced/SchemaField.svelte | 98 -- .../src/components/advanced/SchemaLab.svelte | 383 ------ .../src/components/advanced/StyleTable.svelte | 420 ------- .../components/coverage/CoverageHome.svelte | 207 ---- .../coverage/CoverageHome.svelte.test.ts | 96 -- .../components/coverage/DownloadStep.svelte | 439 ------- .../coverage/DownloadStep.svelte.test.ts | 1077 ----------------- .../src/components/coverage/MapSummary.svelte | 152 --- .../coverage/MapSummary.svelte.test.ts | 95 -- .../src/components/coverage/PartsList.svelte | 118 -- .../src/components/device/CardFormat.svelte | 85 -- .../src/components/device/DeviceStep.svelte | 156 --- .../components/device/DeviceSurfaces.svelte | 56 - .../src/components/device/FirmwareCard.svelte | 254 ---- .../web/src/components/device/MapSend.svelte | 127 -- .../components/device/MapSend.svelte.test.ts | 134 -- .../src/components/device/RideExport.svelte | 198 --- .../src/components/device/RouteDrop.svelte | 345 ------ .../src/components/device/TransferBar.svelte | 101 -- .../device/TransferBar.svelte.test.ts | 45 - builder/web/src/lib/api/client.ts | 77 -- builder/web/src/lib/config/edit.test.ts | 178 --- builder/web/src/lib/config/edit.ts | 154 --- builder/web/src/lib/config/model.test.ts | 258 ---- builder/web/src/lib/config/model.ts | 223 ---- builder/web/src/lib/config/profiles.test.ts | 218 ---- builder/web/src/lib/config/profiles.ts | 243 ---- .../web/src/lib/config/schema_fields.test.ts | 66 - builder/web/src/lib/config/schema_fields.ts | 111 -- builder/web/src/lib/config/storage.svelte.ts | 110 -- builder/web/src/lib/constants.ts | 6 +- builder/web/src/lib/coverage/run.svelte.ts | 127 +- builder/web/src/lib/device/flows.test.ts | 42 +- builder/web/src/lib/device/job.svelte.test.ts | 154 --- builder/web/src/lib/device/job.svelte.ts | 198 --- builder/web/src/lib/device/rides.test.ts | 578 --------- builder/web/src/lib/device/rides.ts | 228 ---- builder/web/src/lib/device/write.ts | 11 +- builder/web/src/lib/palette.ts | 28 - builder/web/src/lib/platform/bundle.test.ts | 74 +- builder/web/src/lib/platform/dev.ts | 32 - builder/web/src/lib/platform/dev.wire.test.ts | 88 -- builder/web/src/lib/platform/hosts.test.ts | 23 - builder/web/src/lib/platform/index.ts | 11 +- builder/web/src/lib/platform/types.ts | 48 +- builder/web/src/lib/platform/web.ts | 4 - builder/web/src/lib/schema/lods.test.ts | 46 - builder/web/src/lib/schema/lods.ts | 30 - .../src/lib/schema/previewController.test.ts | 100 -- .../web/src/lib/schema/previewController.ts | 65 - builder/web/src/lib/schema/render.ts | 80 -- builder/web/src/lib/ui/confirm.svelte.test.ts | 54 - builder/web/src/lib/ui/confirm.svelte.ts | 59 - builder/web/src/main.ts | 11 - builder/web/src/pages/Device.svelte | 7 +- builder/web/src/routes/Advanced.svelte | 283 ----- .../web/src/routes/Advanced.svelte.test.ts | 170 --- builder/web/src/routes/Home.svelte | 55 - builder/web/src/styles/app.css | 299 ----- .../test-support/coverage/Selection.svelte | 7 - .../tests/browser/assemble-download.test.js | 138 --- builder/web/tests/browser/basemap-config.json | 7 - builder/web/tests/browser/basemap-stub.js | 25 - builder/web/tests/browser/basemap.test.js | 56 - builder/web/tests/browser/live-memory.test.ts | 232 ---- builder/web/tests/browser/package.json | 4 - .../web/tests/browser/planner/area.test.js | 59 +- .../web/tests/browser/playwright.config.js | 46 - .../tests/browser/playwright.live.config.js | 41 - builder/web/tsconfig.json | 7 +- builder/web/vite.config.ts | 61 +- docs/build_docs.py | 2 +- docs/design/README.md | 10 +- docs/design/device-map-builder.md | 12 +- docs/design/map.json | 94 +- docs/design/web-planner.md | 4 +- docs/index.html | 8 +- docs/testing.md | 18 +- pyproject.toml | 2 - tools/check_data_sources.py | 8 +- tools/fixture_catalog.py | 11 +- tools/justfile | 55 +- tools/obc.local.example | 6 - tools/test_plan.py | 2 - tools/testing/suites.toml | 79 +- tools/tests/test_data_registry.py | 2 +- tools/tests/test_selection_plan.py | 18 +- uv.lock | 357 +----- 120 files changed, 262 insertions(+), 13818 deletions(-) delete mode 100644 builder/__init__.py delete mode 100644 builder/palette.json delete mode 100644 builder/server/__init__.py delete mode 100644 builder/server/__main__.py delete mode 100644 builder/server/paths.py delete mode 100644 builder/server/schema_preview.py delete mode 100644 builder/server/server.py delete mode 100644 builder/tests/test_routing_profiles.py delete mode 100644 builder/tests/test_schema_preview.py delete mode 100644 builder/tests/test_schema_source.py delete mode 100644 builder/web/index.html delete mode 100644 builder/web/public/osm_catalog.json delete mode 100644 builder/web/src/App.svelte delete mode 100644 builder/web/src/components/ConfirmDialog.svelte delete mode 100644 builder/web/src/components/Header.svelte delete mode 100644 builder/web/src/components/UpdatePrompt.svelte delete mode 100644 builder/web/src/components/advanced/CategoryRail.svelte delete mode 100644 builder/web/src/components/advanced/ClimbWeightCell.svelte delete mode 100644 builder/web/src/components/advanced/ColorControl.svelte delete mode 100644 builder/web/src/components/advanced/LodSegments.svelte delete mode 100644 builder/web/src/components/advanced/LodTiers.svelte delete mode 100644 builder/web/src/components/advanced/MultiplierCell.svelte delete mode 100644 builder/web/src/components/advanced/OptionalColorControl.svelte delete mode 100644 builder/web/src/components/advanced/OutputTab.svelte delete mode 100644 builder/web/src/components/advanced/ProfilesTab.svelte delete mode 100644 builder/web/src/components/advanced/ProfilesTab.svelte.test.ts delete mode 100644 builder/web/src/components/advanced/SchemaField.svelte delete mode 100644 builder/web/src/components/advanced/SchemaLab.svelte delete mode 100644 builder/web/src/components/advanced/StyleTable.svelte delete mode 100644 builder/web/src/components/coverage/CoverageHome.svelte delete mode 100644 builder/web/src/components/coverage/CoverageHome.svelte.test.ts delete mode 100644 builder/web/src/components/coverage/DownloadStep.svelte delete mode 100644 builder/web/src/components/coverage/DownloadStep.svelte.test.ts delete mode 100644 builder/web/src/components/coverage/MapSummary.svelte delete mode 100644 builder/web/src/components/coverage/MapSummary.svelte.test.ts delete mode 100644 builder/web/src/components/coverage/PartsList.svelte delete mode 100644 builder/web/src/components/device/CardFormat.svelte delete mode 100644 builder/web/src/components/device/DeviceStep.svelte delete mode 100644 builder/web/src/components/device/DeviceSurfaces.svelte delete mode 100644 builder/web/src/components/device/FirmwareCard.svelte delete mode 100644 builder/web/src/components/device/MapSend.svelte delete mode 100644 builder/web/src/components/device/MapSend.svelte.test.ts delete mode 100644 builder/web/src/components/device/RideExport.svelte delete mode 100644 builder/web/src/components/device/RouteDrop.svelte delete mode 100644 builder/web/src/components/device/TransferBar.svelte delete mode 100644 builder/web/src/components/device/TransferBar.svelte.test.ts delete mode 100644 builder/web/src/lib/api/client.ts delete mode 100644 builder/web/src/lib/config/edit.test.ts delete mode 100644 builder/web/src/lib/config/edit.ts delete mode 100644 builder/web/src/lib/config/model.test.ts delete mode 100644 builder/web/src/lib/config/model.ts delete mode 100644 builder/web/src/lib/config/profiles.test.ts delete mode 100644 builder/web/src/lib/config/profiles.ts delete mode 100644 builder/web/src/lib/config/schema_fields.test.ts delete mode 100644 builder/web/src/lib/config/schema_fields.ts delete mode 100644 builder/web/src/lib/config/storage.svelte.ts delete mode 100644 builder/web/src/lib/device/job.svelte.test.ts delete mode 100644 builder/web/src/lib/device/job.svelte.ts delete mode 100644 builder/web/src/lib/device/rides.test.ts delete mode 100644 builder/web/src/lib/device/rides.ts delete mode 100644 builder/web/src/lib/palette.ts delete mode 100644 builder/web/src/lib/platform/dev.ts delete mode 100644 builder/web/src/lib/platform/dev.wire.test.ts delete mode 100644 builder/web/src/lib/platform/hosts.test.ts delete mode 100644 builder/web/src/lib/schema/lods.test.ts delete mode 100644 builder/web/src/lib/schema/lods.ts delete mode 100644 builder/web/src/lib/schema/previewController.test.ts delete mode 100644 builder/web/src/lib/schema/previewController.ts delete mode 100644 builder/web/src/lib/schema/render.ts delete mode 100644 builder/web/src/lib/ui/confirm.svelte.test.ts delete mode 100644 builder/web/src/lib/ui/confirm.svelte.ts delete mode 100644 builder/web/src/main.ts delete mode 100644 builder/web/src/routes/Advanced.svelte delete mode 100644 builder/web/src/routes/Advanced.svelte.test.ts delete mode 100644 builder/web/src/routes/Home.svelte delete mode 100644 builder/web/src/styles/app.css delete mode 100644 builder/web/test-support/coverage/Selection.svelte delete mode 100644 builder/web/tests/browser/assemble-download.test.js delete mode 100644 builder/web/tests/browser/basemap-config.json delete mode 100644 builder/web/tests/browser/basemap-stub.js delete mode 100644 builder/web/tests/browser/basemap.test.js delete mode 100644 builder/web/tests/browser/live-memory.test.ts delete mode 100644 builder/web/tests/browser/playwright.config.js delete mode 100644 builder/web/tests/browser/playwright.live.config.js diff --git a/.cairn/baseline.json b/.cairn/baseline.json index 3646b363c8..357ff19dd7 100644 --- a/.cairn/baseline.json +++ b/.cairn/baseline.json @@ -32,8 +32,6 @@ "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", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index caf936acda..db20a65bf0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -415,58 +415,6 @@ jobs: path: ${{ runner.temp }}/ui-snapshots/*.png if-no-files-found: ignore - # Routing-profile round-trips through the builder's pack path. These shell out to the real - # obc-pack binary over the tiny corpus and byte-compare the §8.6 profile table against - # independently quantized expectations — so they pin the packer's writer against the spec - # rather than against itself — plus the pure /api/schema and /api/presets endpoints via - # FastAPI's TestClient. The preflight is what stops a missing binary or corpus from turning - # the packer half of the suite into a silent skip. - builder-python: - needs: selection - if: contains(fromJSON(needs.selection.outputs.jobs), 'builder-python') - runs-on: ubuntu-24.04 - 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: . - shared-key: host-tests - save-if: false - - uses: ./.github/actions/setup-host-deps - - uses: actions/setup-python@v5 - with: - python-version-file: .python-version - - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - with: - version: *python-uv-version - - name: Prepare web-builder packer tests - run: | - uv sync --locked --group builder-test - cargo build -p obc-bake --bin obc-pack --release --locked - - name: Packer binary and corpus are present - run: | - test -x target/release/obc-pack - test -f builder/tests/corpus/data/tiny.osm.pbf - - name: web-builder packer tests (pytest) - id: python-builder - run: | - mkdir -p .artifacts/python - rm -f .artifacts/python/builder.xml - PYTHONPATH=. uv run --locked --group builder-test python -m pytest builder/tests/ -v --junitxml=.artifacts/python/builder.xml - - name: Upload builder Python test results - if: ${{ !cancelled() && (steps.python-builder.outcome == 'success' || steps.python-builder.outcome == 'failure') }} - uses: actions/upload-artifact@v4 - with: - name: python-builder-${{ github.run_attempt }} - path: .artifacts/python/builder.xml - if-no-files-found: error - embedded: needs: selection if: contains(fromJSON(needs.selection.outputs.jobs), 'embedded') @@ -1016,18 +964,14 @@ jobs: exit 1 fi - # The web builder's Svelte frontend: type-check, unit tests, production builds. - # - # 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. + # The web app's Svelte frontend: type-check and unit tests. The production build of the app is + # in vitest too: `bundle.test.ts` builds it and inspects the emitted chunks. # # The three wasm bridges come from `wasm-bridges` rather than being rebuilt here, so the # module the byte-identity tests run against is literally the one the size budget passed. It is # a hard dependency, not an optimisation, and it is why the downloads land before `npm ci`: # every step below needs them — the TS wrappers import the generated bindings, so `npm run check` - # type-checks against them, and the vitest suites and `build:all` fail without the artifacts. + # type-checks against them, and the vitest suites fail without the artifacts. # The assembly bridge's suite is also the *headless smoke* for #1034: it assembles the checked-in # cell fixture in Node and compares the result to the bytes the native CLI wrote. web: @@ -1068,8 +1012,6 @@ 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 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 id: naga @@ -1093,17 +1035,15 @@ jobs: path: ${{ runner.temp }}/web-builder-junit.xml if-no-files-found: error - # The builder's download journey in a real browser: the shipped `dist/web` build, the real - # assembly worker, real OPFS, and the checked-in bridge fixture served as a loopback catalog. + # The web app in a real browser: the planner build with the pretend device, the real assembly + # worker, real OPFS, and the checked-in bridge fixture served as a loopback catalog. # # Its own job rather than a step on `web`, because the registry routes a suite to the job whose - # step executes it: sharing `web` would make the component tier and this end-to-end journey one - # route, and neither could be selected without the other. It needs the production core and - # deliberately not the flat test device — the shipped build must not contain it, and - # `bundle.test.ts` is what says so. + # step executes it: sharing `web` would make the component tier and these end-to-end journeys one + # route, and neither could be selected without the other. # - # `npm test` builds `dist/web` itself (the package's `pretest`), so the bundle under test can - # never be stale or built against a different catalog URL. + # Each `npm run test:*` builds its page itself (the package's `pretest:*`), so the bundle under + # test can never be stale. web-browser: needs: [selection, wasm-bridges] if: contains(fromJSON(needs.selection.outputs.jobs), 'web-browser') @@ -1139,16 +1079,14 @@ jobs: run: | npm ci npx playwright install --with-deps chromium --only-shell - - name: Builder assemble and download journey + - name: Web app journeys and the planner request budget id: browser-journey - run: npm test --prefix builder/web/tests/browser + run: npm run test:planner --prefix builder/web/tests/browser - name: Require browser journey execution if: ${{ !cancelled() }} env: JOURNEY_OUTCOME: ${{ steps.browser-journey.outcome }} run: test "$JOURNEY_OUTCOME" = success - - name: Planner request budget - run: npm run test:planner --prefix builder/web/tests/browser - name: Operator page at phone width run: npm run test:data --prefix builder/web/tests/browser - name: TrailView smoke on SwiftShader @@ -1223,7 +1161,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, verification, planner-search] + needs: [selection, guards, cairn, fmt, clippy, test, ui-snapshots, 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 166cdd885d..cc8ec094fb 100644 --- a/.github/workflows/deploy-site.yml +++ b/.github/workflows/deploy-site.yml @@ -5,15 +5,14 @@ name: Deploy site # # / landing page + the live device demo trunk (obc-web-demo → wasm) # /docs/ /blog/ docs site + expedition log build_docs.py (trunk pre_build hook) -# /builder/ the static map builder vite --mode web -# /plan/ the regional route planner vite --mode planner +# /plan/ the web app vite --mode planner # # Because the demo is the firmware's own render path compiled to wasm, every push # rebuilds it — the site can never show a stale screenshot. And everything here is # static files: there is no backend on this tier. Route conversion runs as wasm # in the tab. Routing and search use the VPS. The tile Worker serves map tiles. # -# The site carries code only. The planner and the map builder read the active release from +# The site carries code only. The web app reads the active release from # `planner/catalog.json` at page load, so a data release never runs this workflow. # # ── What GitHub Pages can and cannot do (C6 #905; measured 2026-07-26) ────────────── @@ -140,7 +139,7 @@ jobs: OBC_BUILD_HARDWARE: "1" run: trunk build --release --config docs/Trunk.toml --public-url "./" - # The builder imports the shared obc-route GPX↔OBCR path (#896), the cell + # The web app imports the shared obc-route GPX↔OBCR path (#896), the cell # assembler (#1034), and the production-rendered skin preview (#1045). The shared # script is also used by CI so the lists cannot drift. # None is optional: the frontend imports the generated bindings, so a missing @@ -154,28 +153,20 @@ jobs: cache: npm cache-dependency-path: builder/web/package-lock.json - # VITE_SITE_BASE makes the builder's links to the docs and the landing relative: + # VITE_SITE_BASE makes the web app'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 (the dev # server), where the site genuinely is somewhere else. - - name: Build the static map builder + - name: Build the web app working-directory: builder/web env: VITE_SITE_BASE: "../" run: | npm ci - npm run build:web - - - name: Build the public route planner - working-directory: builder/web - env: - VITE_SITE_BASE: "../" - run: npm run build:planner + npm run build - name: Assemble the site run: | - mkdir -p docs/dist/builder - cp -R builder/web/dist/web/. docs/dist/builder/ mkdir -p docs/dist/plan cp -R builder/web/dist/planner/. docs/dist/plan/ mv docs/dist/plan/planner.html docs/dist/plan/index.html @@ -193,7 +184,7 @@ jobs: # in, and they are the one thing to hand-edit on the day the domain changes. - name: No baked-in site path run: | - if grep -rIlE "[\"'(=]/OpenBikeComputer/" docs/dist/builder docs/dist/index.html; then + if grep -rIlE "[\"'(=]/OpenBikeComputer/" docs/dist/plan docs/dist/index.html; then echo "::error::the bundle hard-codes the project-Pages sub-path — it would 404 on a custom domain" exit 1 fi @@ -235,7 +226,6 @@ jobs: [ "$n" -gt 0 ] || { echo " x no local assets referenced — check is vacuous"; fail=1; } } check "$base/" - check "$base/builder/" check "$base/docs/" check "$base/docs/hardware/bom/" for file in purchasing.csv OBC_PCB.csv USB_Baseboard.csv OBC_PCB.pdf USB_Baseboard.pdf; do diff --git a/.gitignore b/.gitignore index 05a1dc13dc..c3dbc82305 100644 --- a/.gitignore +++ b/.gitignore @@ -76,16 +76,11 @@ tools/obc.local 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 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). +# Web app frontend: dependencies + the Vite build output, which goes to builder/web/dist/MODE/. node_modules/ builder/web/dist/ planner/tiles/dist/ planner/tiles/.wrangler/ -builder/server/static/dist/ # The static tier's data files (#900): the Geofabrik index is ~1.7 MB of # generated JSON that goes stale weekly, and the catalog manifest belongs to the # bakery — both are produced at deploy time, never committed. diff --git a/builder/__init__.py b/builder/__init__.py deleted file mode 100644 index 51a0a53899..0000000000 --- a/builder/__init__.py +++ /dev/null @@ -1,11 +0,0 @@ -"""The map builder. - -`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. - -The packer was historically a Python pipeline (`pack.py` + `obcm/`); it now -lives entirely in Rust, which is why nothing under this directory parses OSM. -""" diff --git a/builder/palette.json b/builder/palette.json deleted file mode 100644 index 95bbede6dc..0000000000 --- a/builder/palette.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "_note": "The fixed display gamut of the LS021B7DD02 panel: RGB222, i.e. 4 levels (0,85,170,255) per channel = 64 colors. These are the swatches the web builder offers as the default ('device palette') colour picker; the native OS picker stays available for off-gamut custom colours (the device quantizes those at render time). Order matches obc-sim's --palette screen (8 columns, 2x2 of 4x4 red blocks). Edit this file to curate the quick-pick set; it is the colour-picker analogue of the factory config.json.", - "columns": 8, - "colors": [ - "#000000", - "#000055", - "#0000AA", - "#0000FF", - "#550000", - "#550055", - "#5500AA", - "#5500FF", - "#005500", - "#005555", - "#0055AA", - "#0055FF", - "#555500", - "#555555", - "#5555AA", - "#5555FF", - "#00AA00", - "#00AA55", - "#00AAAA", - "#00AAFF", - "#55AA00", - "#55AA55", - "#55AAAA", - "#55AAFF", - "#00FF00", - "#00FF55", - "#00FFAA", - "#00FFFF", - "#55FF00", - "#55FF55", - "#55FFAA", - "#55FFFF", - "#AA0000", - "#AA0055", - "#AA00AA", - "#AA00FF", - "#FF0000", - "#FF0055", - "#FF00AA", - "#FF00FF", - "#AA5500", - "#AA5555", - "#AA55AA", - "#AA55FF", - "#FF5500", - "#FF5555", - "#FF55AA", - "#FF55FF", - "#AAAA00", - "#AAAA55", - "#AAAAAA", - "#AAAAFF", - "#FFAA00", - "#FFAA55", - "#FFAAAA", - "#FFAAFF", - "#AAFF00", - "#AAFF55", - "#AAFFAA", - "#AAFFFF", - "#FFFF00", - "#FFFF55", - "#FFFFAA", - "#FFFFFF" - ] -} diff --git a/builder/server/__init__.py b/builder/server/__init__.py deleted file mode 100644 index 55438f9510..0000000000 --- a/builder/server/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Local-only host for the maintainer schema editor in `builder/web`.""" diff --git a/builder/server/__main__.py b/builder/server/__main__.py deleted file mode 100644 index 0ecdcefc1b..0000000000 --- a/builder/server/__main__.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Entry point: `python -m builder.server` launches the server and opens a browser.""" -import argparse -import threading -import webbrowser - -import uvicorn - - -def main(): - parser = argparse.ArgumentParser(description="OBCM Web Builder") - parser.add_argument("--host", default="127.0.0.1") - parser.add_argument("--port", type=int, default=8000) - parser.add_argument("--no-browser", action="store_true", help="Don't auto-open a browser") - args = parser.parse_args() - - url = f"http://{args.host if args.host != '0.0.0.0' else 'localhost'}:{args.port}" - if not args.no_browser: - threading.Timer(1.0, lambda: webbrowser.open(url)).start() - - print(f"OBCM Web Builder running at {url}") - uvicorn.run("builder.server.server:app", host=args.host, port=args.port, log_level="info") - - -if __name__ == "__main__": - main() diff --git a/builder/server/paths.py b/builder/server/paths.py deleted file mode 100644 index 8b41d238b6..0000000000 --- a/builder/server/paths.py +++ /dev/null @@ -1,21 +0,0 @@ -"""Repository locations used by the local maintainer schema editor.""" -import os - -BUILDER_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -REPO_ROOT = os.path.dirname(BUILDER_ROOT) - -def rust_pack_bin(): - """Locate the native `obc-pack` binary, or None if it isn't built. - - Override the path with OBC_PACK_BIN; otherwise prefer the release build - under the workspace's target/ and fall back to debug. Build it with - `cargo build --release -p obc-bake --bin obc-pack` from the repo root. - """ - override = os.environ.get("OBC_PACK_BIN") - if override: - return override if os.path.exists(override) else None - for profile in ("release", "debug"): - p = os.path.join(REPO_ROOT, "target", profile, "obc-pack") - if os.path.exists(p) and os.access(p, os.X_OK): - return p - return None diff --git a/builder/server/schema_preview.py b/builder/server/schema_preview.py deleted file mode 100644 index b33ffbcf76..0000000000 --- a/builder/server/schema_preview.py +++ /dev/null @@ -1,386 +0,0 @@ -"""Bounded native packing for the localhost maintainer schema lab. - -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. -""" - -from __future__ import annotations - -import asyncio -import base64 -from collections.abc import Awaitable, Callable -from dataclasses import dataclass -import json -import os -from pathlib import Path -import shutil -import subprocess -import tempfile -import time -import urllib.error -import urllib.request - -from . import paths - - -FULL_SOURCE_NAME = "europe_germany_baden-wuerttemberg_freiburg-regbez-latest.osm.pbf" -PREVIEW_SOURCE_NAME = "teningen-reference-complete.osm.pbf" -SOURCE_URL = ( - "https://download.geofabrik.de/europe/germany/" - "baden-wuerttemberg/freiburg-regbez-latest.osm.pbf" -) - -# The view at the coarsest authored scale is 7.2 x 9.6 km. This crop leaves a -# little more than 20% padding around that 240 x 320 frame, while remaining a -# tiny fraction of the Freiburg extract. The camera itself stays on Teningen. -TENINGEN_BBOX = "7.749,48.070,7.879,48.190" - -MAX_CONFIG_BYTES = 512 * 1024 -MAX_MAP_BYTES = 32 * 1024 * 1024 -PACK_TIMEOUT_SECONDS = 180.0 -POLL_SECONDS = 0.05 - - -class PreviewError(Exception): - """A safe, user-facing schema-preview failure.""" - - -class PreviewCancelled(Exception): - """The browser replaced or left a preview request.""" - - -@dataclass(frozen=True) -class SourceStatus: - available: bool - label: str - configured: bool - detail: str - - -@dataclass(frozen=True) -class PackResult: - body: bytes - duration_ms: int - log: str - diagnostics: tuple[str, ...] - - -def _cache_root() -> Path: - return Path(os.environ.get("OBCM_CACHE_DIR", Path.home() / ".cache" / "obcm")) - - -def _full_source() -> Path: - return _cache_root() / "schema-preview" / FULL_SOURCE_NAME - - -def _default_source() -> Path: - return _cache_root() / "schema-preview" / PREVIEW_SOURCE_NAME - - -def _source_candidate() -> tuple[Path, bool]: - configured = os.environ.get("OBC_SCHEMA_PREVIEW_PBF") - if configured: - path = Path(configured) - if not path.is_absolute(): - raise PreviewError("OBC_SCHEMA_PREVIEW_PBF must be an absolute path ending in .osm.pbf.") - return path, True - return _default_source(), False - - -def source_status() -> SourceStatus: - try: - candidate, configured = _source_candidate() - except PreviewError as error: - return SourceStatus(False, "configured preview source", True, str(error)) - - if not candidate.name.endswith(".osm.pbf"): - return SourceStatus( - False, - candidate.name or "configured preview source", - configured, - "The preview source must be an .osm.pbf file.", - ) - if not candidate.is_file(): - detail = ( - "Configured prepared source not found. Create the reference-complete Teningen PBF at that path, " - "or unset OBC_SCHEMA_PREVIEW_PBF and run `obc web preview-source`." - if configured - else "Prepared source not found. Run `obc web preview-source`, or set OBC_SCHEMA_PREVIEW_PBF to an " - "existing reference-complete Teningen .osm.pbf in tools/obc.local." - ) - return SourceStatus( - False, - candidate.name, - configured, - detail, - ) - try: - resolved = candidate.resolve(strict=True) - except OSError as error: - return SourceStatus(False, candidate.name, configured, f"Preview source cannot be opened: {error}.") - if not resolved.is_file(): - return SourceStatus(False, candidate.name, configured, "Preview source is not a regular file.") - try: - if resolved.stat().st_size < 1024: - return SourceStatus(False, candidate.name, configured, "Preview source is unexpectedly short.") - except OSError as error: - return SourceStatus(False, candidate.name, configured, f"Preview source cannot be inspected: {error}.") - return SourceStatus(True, resolved.name, configured, "Ready to pack the fixed Teningen crop.") - - -def source_path() -> Path: - status = source_status() - if not status.available: - raise PreviewError(status.detail) - candidate, _ = _source_candidate() - return candidate.resolve(strict=True) - - -def validate_config(body: bytes) -> dict[str, object]: - if len(body) > MAX_CONFIG_BYTES: - raise PreviewError(f"The schema config exceeds the {MAX_CONFIG_BYTES // 1024} KiB preview limit.") - try: - config = json.loads(body) - except (UnicodeDecodeError, json.JSONDecodeError) as error: - raise PreviewError(f"The schema config is not valid JSON: {error}.") from error - if not isinstance(config, dict): - raise PreviewError("The schema config must be one JSON object.") - if not isinstance(config.get("lods"), list) or not isinstance(config.get("features"), dict): - raise PreviewError("The schema config must contain lods and features.") - return config - - -def _pack_binary() -> Path: - binary = paths.rust_pack_bin() - if not binary: - raise PreviewError("The native packer is missing. Stop and run `obc web` again to build it.") - path = Path(binary) - try: - resolved = path.resolve(strict=True) - except OSError as error: - raise PreviewError(f"The configured native packer cannot be opened: {error}.") from error - if not resolved.is_file() or not os.access(resolved, os.X_OK): - raise PreviewError("The configured native packer is not an executable file.") - return resolved - - -async def _stop(process: subprocess.Popen[bytes]) -> None: - if process.poll() is not None: - return - process.terminate() - try: - await asyncio.to_thread(process.wait, 2.0) - except subprocess.TimeoutExpired: - process.kill() - await asyncio.to_thread(process.wait) - - -_pack_lock = asyncio.Lock() - - -def _log_tail(path: Path, limit: int = 64 * 1024) -> str: - with path.open("rb") as handle: - handle.seek(0, os.SEEK_END) - size = handle.tell() - handle.seek(max(0, size - limit)) - return handle.read(limit).decode("utf-8", errors="replace") - - -async def pack_config( - config: dict[str, object], - disconnected: Callable[[], Awaitable[bool]], - *, - timeout: float = PACK_TIMEOUT_SECONDS, -) -> PackResult: - """Pack one fixed crop, cancelling promptly when its HTTP client goes away.""" - - source = source_path() - binary = _pack_binary() - async with _pack_lock: - if await disconnected(): - raise PreviewCancelled() - started = time.monotonic() - with tempfile.TemporaryDirectory(prefix="obc-schema-preview-") as directory: - root = Path(directory) - config_path = root / "schema.json" - output_path = root / "teningen.obcm" - stdout_path = root / "stdout.log" - stderr_path = root / "stderr.log" - config_path.write_text(json.dumps(config, separators=(",", ":")), encoding="utf-8") - - # No shell, no request-controlled argv, no request-controlled cwd or - # paths. stdout/stderr go to files so a chatty failure cannot fill a - # pipe and deadlock the bounded poll loop. - with stdout_path.open("wb") as stdout, stderr_path.open("wb") as stderr: - try: - process = subprocess.Popen( - [ - os.fspath(binary), - os.fspath(source), - os.fspath(config_path), - os.fspath(output_path), - "--bbox", - TENINGEN_BBOX, - ], - cwd=paths.REPO_ROOT, - stdin=subprocess.DEVNULL, - stdout=stdout, - stderr=stderr, - shell=False, - ) - except OSError as error: - raise PreviewError(f"The native preview packer could not start: {error}.") from error - while process.poll() is None: - if await disconnected(): - await _stop(process) - raise PreviewCancelled() - if time.monotonic() - started > timeout: - await _stop(process) - raise PreviewError(f"The Teningen preview pack exceeded its {int(timeout)} s time limit.") - await asyncio.sleep(POLL_SECONDS) - - stdout_text = _log_tail(stdout_path) - stderr_text = _log_tail(stderr_path) - log = "\n".join(part.strip() for part in (stdout_text, stderr_text) if part.strip())[-4000:] - if process.returncode != 0: - detail = log or f"native packer exited with status {process.returncode}" - raise PreviewError(detail) - try: - size = output_path.stat().st_size - except OSError as error: - raise PreviewError(f"The native packer produced no preview map: {error}.") from error - if size <= 0 or size > MAX_MAP_BYTES: - raise PreviewError( - f"The preview map is {size} bytes; the allowed range is 1–{MAX_MAP_BYTES} bytes." - ) - result = output_path.read_bytes() - - diagnostics = tuple( - line.strip() - for line in log.splitlines() - if "exceeded chunk_size" in line or "ring cap" in line - )[:8] - return PackResult(result, round((time.monotonic() - started) * 1000), log, diagnostics) - - -def encode_diagnostics(lines: tuple[str, ...]) -> str: - raw = json.dumps(lines, ensure_ascii=False, separators=(",", ":")).encode("utf-8") - return base64.urlsafe_b64encode(raw).decode("ascii") - - -def _download_full_source(target: Path) -> None: - """Atomically download the fixed upstream extract when the bakery has not.""" - - if target.is_file(): - if target.stat().st_size >= 1024: - return - raise PreviewError(f"Cached Freiburg source {target} is unexpectedly short; remove it and retry.") - if target.exists(): - raise PreviewError(f"Refusing to replace non-file source cache {target}.") - target.parent.mkdir(parents=True, exist_ok=True) - fd, temporary_name = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".part", dir=target.parent) - temporary = Path(temporary_name) - try: - print(f"downloading Freiburg-regbez ({SOURCE_URL})…", file=os.sys.stderr) - request = urllib.request.Request(SOURCE_URL, headers={"User-Agent": "OpenBikeComputer schema-lab"}) - with os.fdopen(fd, "wb") as output, urllib.request.urlopen(request, timeout=60) as response: - while True: - block = response.read(1024 * 1024) - if not block: - break - output.write(block) - output.flush() - os.fsync(output.fileno()) - if temporary.stat().st_size < 1024: - raise PreviewError("The downloaded Freiburg preview source is unexpectedly short.") - os.replace(temporary, target) - except Exception: - temporary.unlink(missing_ok=True) - raise - - -def prepare_source() -> Path: - """Atomically prepare the small reference-complete source used per edit.""" - - target, configured = _source_candidate() - if not target.name.endswith(".osm.pbf"): - raise PreviewError("OBC_SCHEMA_PREVIEW_PBF must end in .osm.pbf.") - if target.exists(): - if target.is_file(): - if target.stat().st_size < 1024: - raise PreviewError(f"Prepared source {target} is unexpectedly short; remove it and retry.") - return target.resolve(strict=True) - raise PreviewError(f"Refusing to replace non-file preview source {target}.") - if configured: - raise PreviewError( - "OBC_SCHEMA_PREVIEW_PBF names a maintainer-owned prepared source and is not overwritten. " - "Create that reference-complete crop yourself, or unset it and rerun `obc web preview-source`." - ) - - osmium = shutil.which("osmium") - if not osmium: - raise PreviewError( - "Osmium is required to prepare the reference-complete Teningen source. Run `obc doctor`; " - "install osmium-tool with your system package manager, then retry." - ) - - full = _full_source() - _download_full_source(full) - target.parent.mkdir(parents=True, exist_ok=True) - fd, temporary_name = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".part", dir=target.parent) - os.close(fd) - temporary = Path(temporary_name) - try: - print("extracting the fixed reference-complete Teningen crop…", file=os.sys.stderr) - result = subprocess.run( - [ - osmium, - "extract", - "--strategy=smart", - "--bbox", - TENINGEN_BBOX, - "--overwrite", - "--output-format=pbf", - "--output", - os.fspath(temporary), - os.fspath(full), - ], - cwd=paths.REPO_ROOT, - stdin=subprocess.DEVNULL, - capture_output=True, - text=True, - timeout=600, - shell=False, - ) - if result.returncode != 0: - detail = (result.stderr or result.stdout or f"osmium exited with {result.returncode}").strip()[-2000:] - raise PreviewError(f"Osmium could not prepare the Teningen source: {detail}") - if temporary.stat().st_size < 1024: - raise PreviewError("Osmium produced an unexpectedly short Teningen source.") - os.replace(temporary, target) - return target.resolve(strict=True) - except Exception: - temporary.unlink(missing_ok=True) - raise - - -def main() -> int: - import argparse - - parser = argparse.ArgumentParser(description="Manage the fixed OBC schema-preview source") - parser.add_argument("--download-source", action="store_true") - args = parser.parse_args() - if not args.download_source: - parser.error("--download-source is required") - try: - target = prepare_source() - except (OSError, PreviewError, urllib.error.URLError) as error: - print(f"obc web preview-source: {error}", file=os.sys.stderr) - return 1 - print(f"schema-preview source: {target}") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/builder/server/server.py b/builder/server/server.py deleted file mode 100644 index 7926e4ceb3..0000000000 --- a/builder/server/server.py +++ /dev/null @@ -1,252 +0,0 @@ -"""Local maintainer host for the schema editor.""" -import json -import os -import subprocess -from urllib.error import HTTPError, URLError -from urllib.parse import unquote, urlsplit -import urllib.request - -from fastapi import FastAPI, HTTPException, Request -from fastapi.responses import HTMLResponse, JSONResponse, Response -from fastapi.staticfiles import StaticFiles - -from . import paths -from . import schema_preview - -PROJECT_ROOT = paths.BUILDER_ROOT -STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static") -# The shipped style documents: one schema.json (a complete packer config plus a _meta -# block) and a skins/ subdirectory. Only the schema can be handed to the packer, so only -# the top level is listed. -PRESETS_DIR = os.path.join(PROJECT_ROOT, "presets") -# palette.json ships with the repo: the device's 64-color gamut offered as the -# default color picker. Editable, with a generated fallback if it's missing. -PALETTE_FILE = os.path.join(PROJECT_ROOT, "palette.json") -# Generated repo copy of map-core's config schema — the fallback for /api/schema -# when the binary isn't built yet. A Rust stale-generation test pins the file's -# *contents*; test_schema_source.py pins this path, because a string-built path -# that stops resolving degrades silently (the fallback just never fires). -SCHEMA_FILE = os.path.join(paths.REPO_ROOT, "host", "obc-map-core", "schema", "config.schema.json") - -app = FastAPI(title="OBC Schema Editor") - -MAX_CATALOG_OBJECT_BYTES = 128 * 1024 * 1024 - -def _catalog_url() -> str: - value = os.environ.get( - "OBC_CATALOG_URL", - "https://maps.openbikecomputer.com/cell-catalog/catalog.json", - ) - parsed = urlsplit(value) - if ( - parsed.scheme not in ("http", "https") - or not parsed.netloc - or parsed.username - or parsed.password - or parsed.fragment - or not parsed.path.endswith("/catalog.json") - ): - raise HTTPException( - status_code=503, - detail="OBC_CATALOG_URL must be an absolute http(s) URL ending in /catalog.json, without credentials.", - ) - return value - -def _catalog_object_url(value: str) -> str: - root = urlsplit(_catalog_url()) - target = urlsplit(value) - root_dir = root.path.rsplit("/", 1)[0].rstrip("/") + "/" - decoded_path = unquote(target.path) - if ( - target.scheme != root.scheme - or target.netloc != root.netloc - or target.username - or target.password - or target.fragment - or not decoded_path.startswith(root_dir) - or any(part == ".." for part in decoded_path.split("/")) - ): - raise HTTPException(status_code=400, detail="Catalog object URL is outside the configured catalog tree.") - return value - -def _fetch_catalog_object(url: str) -> tuple[bytes, str]: - request = urllib.request.Request(url, headers={"User-Agent": "OpenBikeComputer maintainer host"}) - try: - with urllib.request.urlopen(request, timeout=30) as response: - _catalog_object_url(response.geturl()) - length = response.headers.get("Content-Length") - if length and int(length) > MAX_CATALOG_OBJECT_BYTES: - raise HTTPException(status_code=413, detail="Catalog object exceeds the local proxy limit.") - body = response.read(MAX_CATALOG_OBJECT_BYTES + 1) - if len(body) > MAX_CATALOG_OBJECT_BYTES: - raise HTTPException(status_code=413, detail="Catalog object exceeds the local proxy limit.") - return body, response.headers.get_content_type() - except HTTPException: - raise - except HTTPError as error: - raise HTTPException(status_code=error.code, detail=f"Published catalog returned HTTP {error.code}.") from error - except (OSError, URLError, ValueError) as error: - raise HTTPException(status_code=502, detail=f"Published catalog could not be read: {error}.") from error - -@app.get("/api/catalog/root") -def get_catalog_root(): - url = _catalog_url() - body, content_type = _fetch_catalog_object(url) - return Response(content=body, media_type=content_type, headers={"X-OBC-Catalog-Url": url}) - -@app.get("/api/catalog/object") -def get_catalog_object(url: str): - resolved = _catalog_object_url(url) - body, content_type = _fetch_catalog_object(resolved) - return Response(content=body, media_type=content_type) - -def _default_palette(): - """The LS021B7DD02's 64-color RGB222 gamut, laid out like obc-sim's --palette - screen (8 cols, 2x2 of 4x4 red blocks). Used when palette.json is absent.""" - levels = [0, 85, 170, 255] - colors = [] - for row in range(8): - for col in range(8): - r = levels[(row // 4) * 2 + (col // 4)] - g = levels[row % 4] - b = levels[col % 4] - colors.append(f"#{r:02X}{g:02X}{b:02X}") - return {"columns": 8, "colors": colors} - -def _read_config(path: str): - with open(path) as f: - return json.load(f) - -@app.get("/api/palette") -def get_palette(): - """Return the device color palette (palette.json), or a generated default.""" - if os.path.exists(PALETTE_FILE): - try: - return JSONResponse(_read_config(PALETTE_FILE)) - except Exception: - pass # fall through to the generated gamut - return JSONResponse(_default_palette()) - -@app.get("/api/presets") -def get_presets(): - """List the shipped, bakeable style documents: the one schema. - Each entry carries the _meta fields plus the bare packer config (directly - submittable / CLI-usable). Skins live in presets/skins/ and are deliberately - absent: a skin is presentation stamped onto already-baked bytes and carries no - LOD ladder, so it is not something this endpoint's consumer can build with.""" - presets = [] - for fn in sorted(os.listdir(PRESETS_DIR)): - if not fn.endswith(".json"): - continue - try: - data = _read_config(os.path.join(PRESETS_DIR, fn)) - except Exception: - continue # a malformed preset shouldn't take the endpoint down - meta = data.pop("_meta", {}) - presets.append({ - "id": meta.get("id", fn[:-5]), - "name": meta.get("name", fn[:-5]), - "description": meta.get("description", ""), - "version": meta.get("version", 1), - "swatch": meta.get("swatch", []), - "config": data, - }) - presets.sort(key=lambda p: p["name"]) - return JSONResponse(presets) - -# /api/schema cache, keyed on the binary's mtime so a rebuilt obc-pack is picked up -# without a server restart. -_schema_cache = {"key": None, "envelope": None} - -@app.get("/api/schema") -def get_schema(): - """The config JSON Schema envelope from the exact obc-pack binary that will - pack — the editor derives its capability from this. Falls back to the repo - schema file when the binary isn't built.""" - bin_path = paths.rust_pack_bin() - if bin_path: - key = (bin_path, os.path.getmtime(bin_path)) - if _schema_cache["key"] != key: - try: - out = subprocess.run([bin_path, "schema"], capture_output=True, text=True, timeout=10) - if out.returncode == 0: - envelope = json.loads(out.stdout) - envelope["source"] = "binary" - _schema_cache.update(key=key, envelope=envelope) - except Exception: - pass # fall through to the repo file - if _schema_cache["key"] == key: - return JSONResponse(_schema_cache["envelope"]) - if os.path.exists(SCHEMA_FILE): - return JSONResponse({ - "schema_version": 1, - "format_version": None, - "schema": _read_config(SCHEMA_FILE), - "source": "repo-file", - }) - raise HTTPException( - status_code=503, - detail="The native packer and checked-in schema are unavailable. Restart with `obc web`; " - "maintainers may alternatively set OBC_PACK_BIN to an executable path.", - ) - -@app.get("/api/schema-preview/status") -def get_schema_preview_status(): - status = schema_preview.source_status() - return JSONResponse({ - "available": status.available, - "label": status.label, - "configured": status.configured, - "detail": status.detail, - "bbox": schema_preview.TENINGEN_BBOX, - }) - -@app.post("/api/schema-preview") -async def build_schema_preview(request: Request): - # Read one byte beyond the cap so an exact-limit body is accepted without - # allowing an unbounded request to be decoded first. - body = b"" - async for chunk in request.stream(): - body += chunk - if len(body) > schema_preview.MAX_CONFIG_BYTES: - raise HTTPException(status_code=413, detail="Schema preview config is too large.") - try: - config = schema_preview.validate_config(body) - result = await schema_preview.pack_config(config, request.is_disconnected) - except schema_preview.PreviewCancelled: - return Response(status_code=499) - except schema_preview.PreviewError as error: - raise HTTPException(status_code=422, detail=str(error)) from error - return Response( - content=result.body, - media_type="application/vnd.openbikecomputer.obcm", - headers={ - "X-OBC-Pack-Duration-Ms": str(result.duration_ms), - "X-OBC-Pack-Bytes": str(len(result.body)), - "X-OBC-Pack-Diagnostics": schema_preview.encode_diagnostics(result.diagnostics), - }, - ) - -# The SPA (builder/web/, built by Vite into static/dist/ — -# gitignored, so a fresh checkout needs one `npm run build`). Mounted last: -# every /api route above wins, everything else falls through to the app. -# Without a build, "/" explains how to produce one. -DIST_DIR = os.path.join(STATIC_DIR, "dist") - -if os.path.exists(os.path.join(DIST_DIR, "index.html")): - app.mount("/", StaticFiles(directory=DIST_DIR, html=True), name="app") -else: - - @app.get("/") - def missing_dist(): - return HTMLResponse( - "OBCM Web Builder" - "" - "

Frontend not built yet

" - "

The web builder's UI is compiled from builder/web/. " - "Build it once (requires Node):

" - "
cd builder/web\nnpm ci\nnpm run build
" - "

…then restart this server.

", - status_code=503, - ) diff --git a/builder/tests/test_routing_profiles.py b/builder/tests/test_routing_profiles.py deleted file mode 100644 index e3f244e36f..0000000000 --- a/builder/tests/test_routing_profiles.py +++ /dev/null @@ -1,229 +0,0 @@ -"""Routing-profile round-trips through the web builder's pack path (N6). - -These tests exercise the same `obc-pack` binary the builder dev server shells out -to (``builder/server/schema_preview.py``): a config carrying custom ``routing.profiles`` -is packed over the tiny corpus fixture, and the resulting §8.6 profile-table -bytes are compared against independently quantized expectations. A sub-1.0 -multiplier must be rejected with the packer's admissibility error — the same -message the builder surfaces as a job failure. The pure API endpoints -(``/api/schema``, ``/api/presets``) are checked with FastAPI's TestClient so no -network is needed. - -Run from the repo root with the uv-managed venv, e.g.:: - - PYTHONPATH=. uv run --locked --group builder-test python -m pytest builder/tests/ -""" -import json -import os -import re -import struct -import subprocess - -import pytest - -HERE = os.path.dirname(os.path.abspath(__file__)) -BUILDER_ROOT = os.path.dirname(HERE) -REPO_ROOT = os.path.dirname(BUILDER_ROOT) -TINY_PBF = os.path.join(HERE, "corpus", "data", "tiny.osm.pbf") -SCHEMA_PRESET = os.path.join(BUILDER_ROOT, "presets", "schema.json") - -# Canonical class order; must match obc-map-core/src/nav.rs and the OBCM spec. -HIGHWAY_CLASSES = [ - "cycleway", "path", "track", "footway", "steps", "bridleway", "living_street", - "residential", "service", "unclassified", "tertiary", "secondary", "primary", "trunk_cycl", -] -SURFACE_CLASSES = ["unknown", "paved", "compacted", "gravel", "dirt", "rough", "cobbles", "grass"] -NAME_LEN = 12 -PROFILE_RECORD_LEN = 56 # 12 name + 32 highway + 8 surface + climb_weight + 3 reserved (v12) -CLIMB_WEIGHT_OFF = 52 -# The one OBCM version literal in the tree is the format crate's constant. -OBCM_VERSION = int(re.search(r"pub const VERSION: u8 = (\d+);", - open(os.path.join(REPO_ROOT, "firmware/obc-formats/src/obcm.rs")).read())[1]) - -def _pack_bin(): - override = os.environ.get("OBC_PACK_BIN") - if override and os.path.exists(override): - return override - for profile in ("release", "debug"): - p = os.path.join(REPO_ROOT, "target", profile, "obc-pack") - if os.path.exists(p) and os.access(p, os.X_OK): - return p - return None - -requires_pack = pytest.mark.skipif( - _pack_bin() is None or not os.path.exists(TINY_PBF), - reason="obc-pack binary or tiny corpus fixture not built", -) - -def _quantize(v): - """Mirror obc-pack's quantize_multiplier: forbidden -> 0, else round(v*16) clamped 16..255.""" - if v == "forbidden": - return 0 - q = round(v * 16) - return max(16, min(255, q)) - -def _expected_record(profile): - """Build the 56-byte v12 §8.6 record we expect the packer to write for a profile.""" - default_q = _quantize(profile.get("default", 2.0)) - highway = [default_q] * 32 - surface = [default_q] * 8 - for cls, val in profile.get("highway", {}).items(): - highway[HIGHWAY_CLASSES.index(cls)] = _quantize(val) - for cls, val in profile.get("surface", {}).items(): - surface[SURFACE_CLASSES.index(cls)] = _quantize(val) - name = profile["name"].encode("utf-8") - assert len(name) <= NAME_LEN - name_field = name + b"\xff" * (NAME_LEN - len(name)) - # The climb weight (absent in a config means climb-blind) and three reserved ZERO bytes. - # Zero, not 0xFF: the name field is a padded string, this is a reserved field. - climb = bytes([int(profile.get("climb_weight", 0))]) + b"\x00" * 3 - return name_field + bytes(highway) + bytes(surface) + climb - -def _pack(tmp_path, profiles, min_component_edges=None): - """Pack the tiny corpus with the given routing.profiles; return the .obcm bytes.""" - cfg = json.load(open(SCHEMA_PRESET)) - cfg.pop("_meta", None) - routing = {"profiles": profiles} - if min_component_edges is not None: - routing["min_component_edges"] = min_component_edges - cfg["routing"] = routing - cfg_path = tmp_path / "config.json" - cfg_path.write_text(json.dumps(cfg)) - out_path = tmp_path / "out.obcm" - # --no-land avoids the network land-polygon dataset; the profile table is - # written regardless of graph contents. - proc = subprocess.run( - [_pack_bin(), TINY_PBF, str(cfg_path), str(out_path), "--no-land"], - capture_output=True, text=True, - ) - assert proc.returncode == 0, f"obc-pack failed: {proc.stdout}\n{proc.stderr}" - return out_path.read_bytes() - -def _profile_table(data): - """Locate and slice the §8.6 profile table out of a packed .obcm.""" - assert data[:4] == b"OBCM", "bad magic" - assert data[4] == OBCM_VERSION, f"expected OBCM v{OBCM_VERSION}, got v{data[4]}" - # Every offset that addresses the *file* counts 2^scale-byte units, not bytes. - # Arithmetic *inside* a structure (the `nav_off + 22` below) stays in bytes. - scale = data[40] # header: Offset Scale @ 40 (u8) - assert 0 <= scale <= 9, f"§1.1 restricts Offset Scale to 0..=9, got {scale}" - unit = 1 << scale - (nav_off,) = struct.unpack_from(" 64 - "highway": {"cycleway": 1.0, "track": 7.0, "steps": "forbidden", "primary": 2.5}, - "surface": {"paved": 1.0, "gravel": 5.0, "rough": "forbidden"}, - "climb_weight": 12, # v12 §8.6: flat metres charged per metre of ascent -} -MINIMAL = {"name": "Gravel", "default": 2.0} - -def _four(road, gravel=None): - """The four bike types in their fixed order, with the given Road and Gravel entries.""" - return [road, gravel or {"name": "Gravel"}, {"name": "MTB"}, {"name": "Touring"}] - -@requires_pack -def test_custom_profiles_round_trip_to_112_bytes(tmp_path): - """A config with custom weights packs to §8.6 records that match byte-for-byte.""" - data = _pack(tmp_path, _four(CUSTOM, MINIMAL)) - count, table = _profile_table(data) - assert count == 4 - rec0 = table[:PROFILE_RECORD_LEN] - rec1 = table[PROFILE_RECORD_LEN:2 * PROFILE_RECORD_LEN] - assert rec0 == _expected_record(CUSTOM) - assert rec1 == _expected_record(MINIMAL) - # Spot-check the load-bearing cells directly against the spec's encoding. - assert rec0[NAME_LEN + HIGHWAY_CLASSES.index("cycleway")] == 16 # 1.0x - assert rec0[NAME_LEN + HIGHWAY_CLASSES.index("steps")] == 0 # forbidden - assert rec0[NAME_LEN + HIGHWAY_CLASSES.index("footway")] == 64 # inherits default 4.0x - assert rec0[NAME_LEN + 32 + SURFACE_CLASSES.index("rough")] == 0 # forbidden - assert rec0[CLIMB_WEIGHT_OFF] == 12 # v12: taken verbatim, no admissibility floor - assert rec1[CLIMB_WEIGHT_OFF] == 0 # …and absent means climb-blind - assert rec0[CLIMB_WEIGHT_OFF + 1:] == b"\x00" * 3, "the reserved tail is zero" - -@requires_pack -def test_forbidden_primary_is_quantized_to_zero(tmp_path): - """The acceptance-criterion shape: switching a class to forbidden zeroes its wire byte.""" - profile = {"name": "Road", "default": 2.0, "highway": {"primary": "forbidden"}} - data = _pack(tmp_path, _four(profile)) - _count, table = _profile_table(data) - assert table[NAME_LEN + HIGHWAY_CLASSES.index("primary")] == 0 - -@requires_pack -def test_anything_but_the_four_bike_types_is_rejected(tmp_path): - """The count, the order and the names of the profiles are fixed (OBCM §8.6).""" - cfg = json.load(open(SCHEMA_PRESET)) - cfg.pop("_meta", None) - for profiles in ([CUSTOM], _four(CUSTOM)[::-1], _four({"name": "Racer"})): - cfg["routing"] = {"profiles": profiles} - cfg_path = tmp_path / "config.json" - cfg_path.write_text(json.dumps(cfg)) - proc = subprocess.run( - [_pack_bin(), TINY_PBF, str(cfg_path), str(tmp_path / "out.obcm"), "--no-land"], - capture_output=True, text=True, - ) - assert proc.returncode != 0, f"{[p['name'] for p in profiles]} must fail the pack" - assert "four bike types" in proc.stdout + proc.stderr - -@requires_pack -def test_sub_one_multiplier_is_rejected_with_admissibility_error(tmp_path): - """A multiplier below 1.0 must be rejected by the packer with the admissibility error - — the identical failure the builder API surfaces as a job error.""" - cfg = json.load(open(SCHEMA_PRESET)) - cfg.pop("_meta", None) - cfg["routing"] = {"profiles": _four({"name": "Road", "highway": {"cycleway": 0.5}})} - cfg_path = tmp_path / "config.json" - cfg_path.write_text(json.dumps(cfg)) - proc = subprocess.run( - [_pack_bin(), TINY_PBF, str(cfg_path), str(tmp_path / "out.obcm"), "--no-land"], - capture_output=True, text=True, - ) - assert proc.returncode != 0, "a sub-1.0 multiplier must fail the pack" - msg = proc.stdout + proc.stderr - assert "below 1.0" in msg - assert "admissible" in msg - -# --- Pure builder-API endpoints (no network) -------------------------------- -# Called directly (not via TestClient) so the suite needs no httpx — the -# handlers return FastAPI JSONResponses whose body we decode. - -def _endpoint_json(response): - return json.loads(bytes(response.body)) - -def test_schema_endpoint_exposes_routing_defaults(): - """The builder serves the canonical shipped profiles as the schema default — - the single source of truth the frontend's 'Reset to defaults' reads.""" - pytest.importorskip("fastapi") - from builder.server import server - - schema = _endpoint_json(server.get_schema())["schema"] - routing = schema["properties"]["routing"] - names = [p["name"] for p in routing["default"]["profiles"]] - assert names == ["Road", "Gravel", "MTB", "Touring"] - hw_enum = schema["$defs"]["profile"]["properties"]["highway"]["propertyNames"]["enum"] - assert hw_enum[:5] == HIGHWAY_CLASSES[:5] - mult = schema["$defs"]["multiplier"]["oneOf"] - assert any(o.get("minimum") == 1.0 for o in mult) - assert any(o.get("const") == "forbidden" for o in mult) - -def test_presets_round_trip_routing(): - """Every shipped preset carries a complete routing section (CLI-usable), so the - builder shows its profiles when a preset is loaded.""" - pytest.importorskip("fastapi") - from builder.server import server - - presets = _endpoint_json(server.get_presets()) - assert presets, "no presets served" - for p in presets: - routing = p["config"].get("routing") - assert routing is not None, f"preset {p['id']} lost its routing section" - assert 1 <= len(routing["profiles"]) <= 8 - assert all("name" in prof for prof in routing["profiles"]) diff --git a/builder/tests/test_schema_preview.py b/builder/tests/test_schema_preview.py deleted file mode 100644 index 58a94939d8..0000000000 --- a/builder/tests/test_schema_preview.py +++ /dev/null @@ -1,307 +0,0 @@ -"""Security and cancellation boundaries of the localhost schema lab.""" - -import asyncio -from pathlib import Path -import subprocess - -import pytest - - -def test_runtime_catalog_url_is_validated_from_process_state(monkeypatch): - pytest.importorskip("fastapi") - from builder.server import server - - monkeypatch.setenv("OBC_CATALOG_URL", "https://maps.example.test/revision/catalog.json") - assert server._catalog_url() == "https://maps.example.test/revision/catalog.json" - - monkeypatch.setenv("OBC_CATALOG_URL", "https://token:secret@maps.example.test/catalog.json") - with pytest.raises(server.HTTPException) as excinfo: - server._catalog_url() - assert excinfo.value.status_code == 503 - assert "credentials" in excinfo.value.detail - monkeypatch.setenv("OBC_CATALOG_URL", "https://maps.example.test/not-a-root.json") - with pytest.raises(server.HTTPException, match="catalog.json"): - server._catalog_url() - - -def test_runtime_catalog_proxy_rejects_other_origins_credentials_and_path_escape(monkeypatch): - pytest.importorskip("fastapi") - from builder.server import server - - monkeypatch.setenv("OBC_CATALOG_URL", "https://maps.example.test/cell-catalog/catalog.json") - assert ( - server._catalog_object_url("https://maps.example.test/cell-catalog/cells/12/3.obcm") - == "https://maps.example.test/cell-catalog/cells/12/3.obcm" - ) - for hostile in ( - "https://other.example/cell-catalog/cells/12/3.obcm", - "https://user:secret@maps.example.test/cell-catalog/cells/12/3.obcm", - "https://maps.example.test/private/object", - "https://maps.example.test/cell-catalog/%2e%2e/private", - ): - with pytest.raises(server.HTTPException) as excinfo: - server._catalog_object_url(hostile) - assert excinfo.value.status_code == 400 - - -def test_runtime_catalog_proxy_bounds_reads(monkeypatch): - pytest.importorskip("fastapi") - from builder.server import server - monkeypatch.setenv("OBC_CATALOG_URL", "https://maps.example.test/cell-catalog/catalog.json") - - class Headers: - def get(self, _name): - return None - - def get_content_type(self): - return "application/octet-stream" - - class Reply: - headers = Headers() - - def __enter__(self): - return self - - def __exit__(self, *_args): - return None - - def read(self, limit): - assert limit == server.MAX_CATALOG_OBJECT_BYTES + 1 - return b"catalog-object" - - def geturl(self): - return "https://maps.example.test/cell-catalog/object" - - seen = [] - - def open_request(request, timeout): - seen.append((request.full_url, timeout)) - return Reply() - - monkeypatch.setattr(server.urllib.request, "urlopen", open_request) - body, content_type = server._fetch_catalog_object("https://maps.example.test/cell-catalog/object") - assert body == b"catalog-object" - assert content_type == "application/octet-stream" - assert seen == [("https://maps.example.test/cell-catalog/object", 30)] - - -def test_source_is_server_configured_and_missing_state_uses_obc_commands(monkeypatch, tmp_path): - from builder.server import schema_preview - - missing = tmp_path / "freiburg.osm.pbf" - monkeypatch.setenv("OBC_SCHEMA_PREVIEW_PBF", str(missing)) - status = schema_preview.source_status() - assert not status.available - assert "obc web preview-source" in status.detail - assert "cargo" not in status.detail - - monkeypatch.setenv("OBC_SCHEMA_PREVIEW_PBF", "relative.osm.pbf") - status = schema_preview.source_status() - assert not status.available - assert "absolute path" in status.detail - - -def test_config_input_is_bounded_and_never_carries_paths_or_commands(): - from builder.server import schema_preview - - assert schema_preview.validate_config(b'{"lods":[],"features":{}}') == {"lods": [], "features": {}} - for invalid in (b"[]", b'{"lods":[]}', b"not json"): - with pytest.raises(schema_preview.PreviewError): - schema_preview.validate_config(invalid) - with pytest.raises(schema_preview.PreviewError, match="limit"): - schema_preview.validate_config(b" " * (schema_preview.MAX_CONFIG_BYTES + 1)) - - -def test_native_pack_has_fixed_argv_temp_outputs_and_no_shell(monkeypatch, tmp_path): - from builder.server import schema_preview - - source = tmp_path / "source.osm.pbf" - binary = tmp_path / "obc-pack" - source.write_bytes(b"pbf" * 512) - binary.write_bytes(b"bin") - binary.chmod(0o755) - monkeypatch.setenv("OBC_SCHEMA_PREVIEW_PBF", str(source)) - monkeypatch.setattr(schema_preview.paths, "rust_pack_bin", lambda: str(binary)) - captured = {} - - class Done: - returncode = 0 - - def __init__(self, argv, **kwargs): - captured.update(argv=argv, kwargs=kwargs) - Path(argv[3]).write_bytes(b"OBCM-map") - - def poll(self): - return 0 - - monkeypatch.setattr(schema_preview.subprocess, "Popen", Done) - result = asyncio.run(schema_preview.pack_config({"lods": [], "features": {}}, _connected)) - - argv = captured["argv"] - assert argv[0] == str(binary) - assert argv[1] == str(source) - assert argv[-2:] == ["--bbox", schema_preview.TENINGEN_BBOX] - assert captured["kwargs"]["shell"] is False - assert captured["kwargs"]["stdin"] is schema_preview.subprocess.DEVNULL - assert result.body == b"OBCM-map" - assert result.diagnostics == () - assert not Path(argv[2]).exists() and not Path(argv[3]).exists(), "temporary config/map are removed" - - -def test_pack_failure_is_bounded_and_does_not_publish_partial_output(monkeypatch, tmp_path): - from builder.server import schema_preview - - source = tmp_path / "source.osm.pbf" - binary = tmp_path / "obc-pack" - source.write_bytes(b"pbf" * 512) - binary.write_bytes(b"bin") - binary.chmod(0o755) - monkeypatch.setenv("OBC_SCHEMA_PREVIEW_PBF", str(source)) - monkeypatch.setattr(schema_preview.paths, "rust_pack_bin", lambda: str(binary)) - - class Failed: - returncode = 7 - - def __init__(self, _argv, **kwargs): - kwargs["stderr"].write(b"invalid min_lod") - kwargs["stderr"].flush() - - def poll(self): - return 7 - - monkeypatch.setattr(schema_preview.subprocess, "Popen", Failed) - with pytest.raises(schema_preview.PreviewError, match="invalid min_lod"): - asyncio.run(schema_preview.pack_config({"lods": [], "features": {}}, _connected)) - - -def test_disconnected_request_terminates_the_native_pack(monkeypatch, tmp_path): - from builder.server import schema_preview - - source = tmp_path / "source.osm.pbf" - binary = tmp_path / "obc-pack" - source.write_bytes(b"pbf" * 512) - binary.write_bytes(b"bin") - binary.chmod(0o755) - monkeypatch.setenv("OBC_SCHEMA_PREVIEW_PBF", str(source)) - monkeypatch.setattr(schema_preview.paths, "rust_pack_bin", lambda: str(binary)) - process = None - - class Running: - returncode = None - stopped = False - - def __init__(self, _argv, **_kwargs): - nonlocal process - process = self - - def poll(self): - return -15 if self.stopped else None - - def terminate(self): - self.stopped = True - self.returncode = -15 - - def kill(self): - self.stopped = True - self.returncode = -9 - - def wait(self, _timeout=None): - return self.returncode - - checks = 0 - - async def disconnect_after_start(): - nonlocal checks - checks += 1 - return checks > 1 - - monkeypatch.setattr(schema_preview.subprocess, "Popen", Running) - with pytest.raises(schema_preview.PreviewCancelled): - asyncio.run(schema_preview.pack_config({"lods": [], "features": {}}, disconnect_after_start)) - assert process is not None and process.stopped - - -async def _connected(): - return False - - -def test_preview_source_is_prepared_atomically_with_smart_osmium(monkeypatch, tmp_path): - from builder.server import schema_preview - - monkeypatch.delenv("OBC_SCHEMA_PREVIEW_PBF", raising=False) - monkeypatch.setenv("OBCM_CACHE_DIR", str(tmp_path / "cache")) - full = schema_preview._full_source() - full.parent.mkdir(parents=True) - full.write_bytes(b"source" * 1024) - monkeypatch.setattr(schema_preview.shutil, "which", lambda name: "/usr/local/bin/osmium" if name == "osmium" else None) - calls = [] - - def run(argv, **kwargs): - calls.append((argv, kwargs)) - output = Path(argv[argv.index("--output") + 1]) - output.write_bytes(b"prepared" * 1024) - return subprocess.CompletedProcess(argv, 0, "", "") - - monkeypatch.setattr(schema_preview.subprocess, "run", run) - target = schema_preview.prepare_source() - - assert target == (tmp_path / "cache/schema-preview/teningen-reference-complete.osm.pbf").resolve() - assert target.read_bytes().startswith(b"prepared") - argv, kwargs = calls[0] - assert argv[:3] == ["/usr/local/bin/osmium", "extract", "--strategy=smart"] - assert argv[argv.index("--bbox") + 1] == schema_preview.TENINGEN_BBOX - assert "--output-format=pbf" in argv - assert argv[-1] == str(full) - assert kwargs["shell"] is False - assert not list(target.parent.glob("*.part")) - - -def test_failed_source_preparation_leaves_no_partial_target(monkeypatch, tmp_path): - from builder.server import schema_preview - - monkeypatch.delenv("OBC_SCHEMA_PREVIEW_PBF", raising=False) - monkeypatch.setenv("OBCM_CACHE_DIR", str(tmp_path / "cache")) - full = schema_preview._full_source() - full.parent.mkdir(parents=True) - full.write_bytes(b"source" * 1024) - monkeypatch.setattr(schema_preview.shutil, "which", lambda _name: "/usr/bin/osmium") - - def fail(argv, **_kwargs): - Path(argv[argv.index("--output") + 1]).write_bytes(b"partial") - return subprocess.CompletedProcess(argv, 4, "", "bad polygon references") - - monkeypatch.setattr(schema_preview.subprocess, "run", fail) - target = schema_preview._default_source() - with pytest.raises(schema_preview.PreviewError, match="bad polygon references"): - schema_preview.prepare_source() - assert not target.exists() - assert not list(target.parent.glob("*.part")) - - -def test_configured_preview_source_is_never_downloaded_to_or_overwritten(monkeypatch, tmp_path): - from builder.server import schema_preview - - custom = tmp_path / "mine.osm.pbf" - monkeypatch.setenv("OBC_SCHEMA_PREVIEW_PBF", str(custom)) - monkeypatch.setattr( - schema_preview, - "_download_full_source", - lambda _target: pytest.fail("a configured custom target must never enter the downloader"), - ) - with pytest.raises(schema_preview.PreviewError, match="not overwritten"): - schema_preview.prepare_source() - - -def test_missing_osmium_uses_the_obc_doctor_remedy_before_downloading(monkeypatch, tmp_path): - from builder.server import schema_preview - - monkeypatch.delenv("OBC_SCHEMA_PREVIEW_PBF", raising=False) - monkeypatch.setenv("OBCM_CACHE_DIR", str(tmp_path / "cache")) - monkeypatch.setattr(schema_preview.shutil, "which", lambda _name: None) - monkeypatch.setattr( - schema_preview, - "_download_full_source", - lambda _target: pytest.fail("dependency preflight must happen before a large download"), - ) - with pytest.raises(schema_preview.PreviewError, match="obc doctor"): - schema_preview.prepare_source() diff --git a/builder/tests/test_schema_source.py b/builder/tests/test_schema_source.py deleted file mode 100644 index e30868d384..0000000000 --- a/builder/tests/test_schema_source.py +++ /dev/null @@ -1,111 +0,0 @@ -"""Where ``/api/schema``'s two sources come from. - -``builder/server/server.py`` serves the config JSON Schema from the obc-pack -binary when it is built, and from the checked-in repo copy otherwise. The repo -copy's *contents* are pinned on the Rust side (obc-pack's -``checked_in_schema_is_current_generated_schema``), but its **path** is built by -string-joining in Python — and that degrades silently. When obc-pack moved from -``firmware/`` to ``host/``, the binary branch kept working, ``os.path.exists`` -quietly went False, and the fallback simply stopped firing; nothing failed. CI -builds the obc-pack binary before running these tests, so the existing ``/api/schema`` -coverage took the binary branch and never noticed. Hence a test for the path -itself, and one that forces the fallback branch with no binary in sight. - -Run from the repo root with the uv-managed venv, e.g.:: - - PYTHONPATH=. uv run --locked --group builder-test python -m pytest builder/tests/ -""" -import json -import os - -import pytest - -def _endpoint_json(response): - return json.loads(bytes(response.body)) - -def test_schema_file_path_resolves(): - """SCHEMA_FILE must name a file that is actually there. - - This is the whole point of the module: the constant is assembled from path - components, so a crate that moves leaves it pointing at nothing and the - fallback dies without a sound. - """ - pytest.importorskip("fastapi") - from builder.server import server - - assert os.path.exists(server.SCHEMA_FILE), ( - f"SCHEMA_FILE points at {server.SCHEMA_FILE}, which does not exist — " - "obc-pack's schema moved and server.py was not updated, so /api/schema's " - "repo-file fallback can never fire." - ) - schema = json.load(open(server.SCHEMA_FILE)) - # Shape check, not a content pin (obc-pack's Rust test owns the contents): - # enough to catch pointing at some *other* JSON file that happens to exist. - assert "$defs" in schema and "properties" in schema - -def test_repo_file_fallback_serves_the_schema_without_a_binary(monkeypatch): - """With no obc-pack built, /api/schema still answers — from the repo file. - - The editor derives its capability from this envelope, so an unbuilt packer - must degrade to a usable schema rather than to a 503. - """ - pytest.importorskip("fastapi") - from builder.server import paths, server - - monkeypatch.setattr(paths, "rust_pack_bin", lambda: None) - - envelope = _endpoint_json(server.get_schema()) - assert envelope["source"] == "repo-file" - assert envelope["schema_version"] == 1 - # No binary means no OBCM version to report; the editor renders this as "?". - assert envelope["format_version"] is None - assert envelope["schema"] == json.load(open(server.SCHEMA_FILE)) - # The fallback has to carry the parts the editor reads, not just any JSON. - assert envelope["schema"]["properties"]["routing"]["default"]["profiles"] - -def test_both_sources_agree_on_the_envelope_shape(monkeypatch): - """Binary and repo-file envelopes carry the same keys. - - OutputTab.svelte reads schema_version, format_version and source off both - without caring which produced it, so the fallback must not be a different - shape from the real thing. Skipped when obc-pack isn't built. - """ - pytest.importorskip("fastapi") - from builder.server import paths, server - - if paths.rust_pack_bin() is None: - pytest.skip("obc-pack binary not built") - - from_binary = _endpoint_json(server.get_schema()) - if from_binary["source"] != "binary": - pytest.skip("obc-pack built, but `obc-pack schema` did not answer") - - monkeypatch.setattr(paths, "rust_pack_bin", lambda: None) - from_file = _endpoint_json(server.get_schema()) - - assert from_binary.keys() == from_file.keys() - # And the checked-in copy is the schema the binary generates — the Rust staleness - # test's claim, verified here through the endpoint that depends on it. - assert from_binary["schema"] == from_file["schema"] - -def test_unbuilt_packer_says_where_to_build_it(monkeypatch): - """With neither source available, the 503 names the repo root. - - The directory in this message is the same fact SCHEMA_FILE encodes, written - out in prose — it said `firmware/` for as long as the path did. - """ - pytest.importorskip("fastapi") - from fastapi import HTTPException - - from builder.server import paths, server - - monkeypatch.setattr(paths, "rust_pack_bin", lambda: None) - monkeypatch.setattr(server, "SCHEMA_FILE", "/nonexistent/config.schema.json") - - with pytest.raises(HTTPException) as excinfo: - server.get_schema() - assert excinfo.value.status_code == 503 - detail = excinfo.value.detail - assert "obc web" in detail - assert "OBC_PACK_BIN" in detail - assert "firmware/" not in detail, f"stale build directory in the hint: {detail!r}" diff --git a/builder/web/index.html b/builder/web/index.html deleted file mode 100644 index d8da276869..0000000000 --- a/builder/web/index.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - OpenBikeComputer · Maps - - - -
- - - diff --git a/builder/web/package.json b/builder/web/package.json index 338d10b7ed..9db01b6f75 100644 --- a/builder/web/package.json +++ b/builder/web/package.json @@ -5,14 +5,11 @@ "type": "module", "scripts": { "dev": "vite", - "build": "vite build", + "build": "npm run build:planner", "build:planner": "vite build --mode planner", "build:data": "vite build --mode data", "build:trailview": "vite build --mode trailview", - "build:web": "vite build --mode web", - "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", "check:wgsl": "node scripts/check-wgsl.mjs", "test": "vitest run", diff --git a/builder/web/public/osm_catalog.json b/builder/web/public/osm_catalog.json deleted file mode 100644 index 11662c08c5..0000000000 --- a/builder/web/public/osm_catalog.json +++ /dev/null @@ -1,84 +0,0 @@ -{ - "_note": "Curated catalog of common OSM tag keys and values for the style editor's autocomplete. Not exhaustive — freeform entry of any key/value is still allowed.", - "keys": { - "highway": [ - "motorway", "motorway_link", "trunk", "trunk_link", "primary", "primary_link", - "secondary", "secondary_link", "tertiary", "tertiary_link", "unclassified", - "residential", "living_street", "service", "pedestrian", "track", "path", - "footway", "cycleway", "bridleway", "steps", "busway", "road", "raceway" - ], - "waterway": [ - "river", "stream", "canal", "drain", "ditch", "riverbank", "dock", "weir", - "dam", "lock_gate" - ], - "railway": [ - "rail", "light_rail", "subway", "tram", "narrow_gauge", "monorail", - "funicular", "preserved", "disused", "abandoned", "construction", "platform" - ], - "natural": [ - "water", "wood", "scrub", "heath", "grassland", "wetland", "beach", "sand", - "bare_rock", "scree", "cliff", "coastline", "peak", "tree_row", "bay", - "glacier", "wood", "land", "sea" - ], - "landuse": [ - "forest", "grass", "residential", "commercial", "industrial", "retail", - "farmland", "farmyard", "meadow", "orchard", "vineyard", "cemetery", - "quarry", "military", "allotments", "recreation_ground", "village_green", - "basin", "reservoir", "construction", "railway", "brownfield", "greenfield" - ], - "leisure": [ - "park", "garden", "playground", "pitch", "sports_centre", "stadium", - "golf_course", "nature_reserve", "swimming_pool", "track", "common", - "dog_park", "marina", "water_park" - ], - "amenity": [ - "parking", "school", "university", "college", "kindergarten", "hospital", - "place_of_worship", "restaurant", "cafe", "bar", "pub", "fuel", "bank", - "pharmacy", "townhall", "library", "fountain", "grave_yard", "marketplace", - "police", "fire_station" - ], - "building": [ - "yes", "house", "residential", "apartments", "commercial", "industrial", - "retail", "church", "cathedral", "school", "university", "hospital", - "garage", "hut", "shed", "roof", "construction", "warehouse", "office", - "public", "train_station", "stadium" - ], - "boundary": [ - "administrative", "national_park", "protected_area", "maritime", - "political", "postal_code" - ], - "admin_level": ["2", "3", "4", "5", "6", "7", "8", "9", "10", "11"], - "aeroway": [ - "runway", "taxiway", "apron", "terminal", "helipad", "aerodrome", "gate" - ], - "water": [ - "lake", "pond", "reservoir", "river", "canal", "basin", "lagoon", "oxbow", - "lock", "moat" - ], - "man_made": [ - "pier", "bridge", "breakwater", "groyne", "embankment", "tower", - "lighthouse", "storage_tank", "wastewater_plant", "water_works", "dyke" - ], - "barrier": [ - "fence", "wall", "hedge", "gate", "retaining_wall", "city_wall", "bollard", - "kerb", "ditch" - ], - "place": [ - "city", "town", "village", "hamlet", "suburb", "neighbourhood", "locality", - "island", "islet", "city_block" - ], - "power": [ - "line", "minor_line", "cable", "tower", "pole", "substation", "plant", - "generator" - ], - "tourism": [ - "hotel", "hostel", "guest_house", "attraction", "museum", "viewpoint", - "camp_site", "picnic_site", "zoo", "theme_park", "artwork" - ], - "service": [ - "driveway", "parking_aisle", "alley", "siding", "spur", "yard", "drive-through" - ], - "bridge": ["yes"], - "tunnel": ["yes"] - } -} diff --git a/builder/web/src/App.svelte b/builder/web/src/App.svelte deleted file mode 100644 index 253f9f5a22..0000000000 --- a/builder/web/src/App.svelte +++ /dev/null @@ -1,129 +0,0 @@ - - - - - -
- - -
- - {#if showEditor && openEditor} - {#await openEditor() then { default: StyleEditor }} - - {/await} - {/if} -
- - - - - - - - - - diff --git a/builder/web/src/Shell.svelte b/builder/web/src/Shell.svelte index 9154f4b66e..e70dbc5d1b 100644 --- a/builder/web/src/Shell.svelte +++ b/builder/web/src/Shell.svelte @@ -116,7 +116,6 @@ OpenBikeComputer Docs Blog - Map builder Impressum Datenschutz Licences diff --git a/builder/web/src/components/ConfirmDialog.svelte b/builder/web/src/components/ConfirmDialog.svelte deleted file mode 100644 index 607f9df0a8..0000000000 --- a/builder/web/src/components/ConfirmDialog.svelte +++ /dev/null @@ -1,102 +0,0 @@ - - - - - -{#if pending} - - -{/if} - - diff --git a/builder/web/src/components/Header.svelte b/builder/web/src/components/Header.svelte deleted file mode 100644 index 6646efca68..0000000000 --- a/builder/web/src/components/Header.svelte +++ /dev/null @@ -1,86 +0,0 @@ - - -{#snippet brand()} - - OpenBikeComputer - -{/snippet} - -{#snippet appTabs()} - -{/snippet} - -
-
- {@render brand()} - - - -
- {#if tabbed} -
- {@render appTabs()} -
- {/if} -
- - diff --git a/builder/web/src/components/UpdatePrompt.svelte b/builder/web/src/components/UpdatePrompt.svelte deleted file mode 100644 index b783348da6..0000000000 --- a/builder/web/src/components/UpdatePrompt.svelte +++ /dev/null @@ -1,106 +0,0 @@ - - - -{#if shown} - {@const release = shown} -
-

Firmware {release.version} is available

- {#if info} -

This device is running {info.firmwareRevision}.

- {/if} -
- - -
-
-{/if} - - diff --git a/builder/web/src/components/advanced/CategoryRail.svelte b/builder/web/src/components/advanced/CategoryRail.svelte deleted file mode 100644 index ff58168087..0000000000 --- a/builder/web/src/components/advanced/CategoryRail.svelte +++ /dev/null @@ -1,119 +0,0 @@ - - - - - diff --git a/builder/web/src/components/advanced/ClimbWeightCell.svelte b/builder/web/src/components/advanced/ClimbWeightCell.svelte deleted file mode 100644 index a713984e6e..0000000000 --- a/builder/web/src/components/advanced/ClimbWeightCell.svelte +++ /dev/null @@ -1,117 +0,0 @@ - - -
- - {#if stated} - - {/if} -
- - diff --git a/builder/web/src/components/advanced/ColorControl.svelte b/builder/web/src/components/advanced/ColorControl.svelte deleted file mode 100644 index c2bc01dea5..0000000000 --- a/builder/web/src/components/advanced/ColorControl.svelte +++ /dev/null @@ -1,189 +0,0 @@ - - - - - {#if showLabel} - {canonical} - {/if} - - -{#if open} -
-
Device palette
-
- {#each palette.colors as hex (hex)} - - {/each} -
-
- Custom - pick(hexToRgb565(e.currentTarget.value), true)} - /> - → device - -
-
-{/if} - - diff --git a/builder/web/src/components/advanced/LodSegments.svelte b/builder/web/src/components/advanced/LodSegments.svelte deleted file mode 100644 index 22fb90ae8a..0000000000 --- a/builder/web/src/components/advanced/LodSegments.svelte +++ /dev/null @@ -1,58 +0,0 @@ - - - - {#each { length: count } as _, i (i)} - - {/each} - - - diff --git a/builder/web/src/components/advanced/LodTiers.svelte b/builder/web/src/components/advanced/LodTiers.svelte deleted file mode 100644 index fe9973bcb2..0000000000 --- a/builder/web/src/components/advanced/LodTiers.svelte +++ /dev/null @@ -1,232 +0,0 @@ - - -
-

- Each tier is a zoom band: LOD 0 is the coarsest overview, the last tier the finest. - max m/px is the most zoomed-out scale a tier covers; simplify drops - geometry detail finer than that many meters. A feature appears from its start tier - (the “levels” control in Features & styling) and every finer one. -

-

- Simplify defaults to the next finer tier's max m/px — geometry stays accurate to - one pixel at every scale the tier is drawn at — and follows that ceiling until you type - your own value. -

-

- min area drops area features (forests, landuse, water) whose - on-screen area would be smaller than that many pixels² at this tier — a coarse-view - declutter that keeps sub-pixel slivers out of the point budget. Lines (roads, paths) are - not culled by area. 0 is off; the finest tier has no coarser fallback, so it is never culled. -

-

- min line (km) is the same declutter for lines, and the reason it - is safe: it measures a road after its OSM fragments have been stitched back into - one polyline, so it drops the short leftovers stitching could not absorb — junction stubs, - roundabout arms — rather than a through-road's shortest links. At a coarse tier those are - far below a pixel yet still cost the renderer a span each; culling them is what buys a - zoomed-out view enough budget to draw a road network you can orient on. 0 is off, and it - needs merge lines switched on. -

- -
-
- tier - max m/px - simplify (m) - min area (px²) - min line (km) -
- {#each lods as lod, i (i)} -
- - LOD {i} - {#if i === 0}coarsest - {:else if i === lods.length - 1}finest{/if} - - - {#if i === 0} - ∞ - {:else} - edit(i, "max_mpp", e.currentTarget.value)} - /> - {/if} - - - edit(i, "simplify", e.currentTarget.value)} - /> - {#if lod.simplify === autoSimplify(env.config, i)} - auto - {:else} - - {/if} - - - {#if i === lods.length - 1} - — - {:else} - edit(i, "min_area_px", e.currentTarget.value)} - /> - {/if} - - - edit(i, "min_line_km", e.currentTarget.value)} - /> - - {#if lods.length > 1} - - {/if} -
- {/each} -
- - -
- - diff --git a/builder/web/src/components/advanced/MultiplierCell.svelte b/builder/web/src/components/advanced/MultiplierCell.svelte deleted file mode 100644 index 5ad75f8e4c..0000000000 --- a/builder/web/src/components/advanced/MultiplierCell.svelte +++ /dev/null @@ -1,160 +0,0 @@ - - -
- {#if forbidden} - - {:else} - - - {#if explicit} - - {/if} - {/if} -
- - diff --git a/builder/web/src/components/advanced/OptionalColorControl.svelte b/builder/web/src/components/advanced/OptionalColorControl.svelte deleted file mode 100644 index 9c3fb04423..0000000000 --- a/builder/web/src/components/advanced/OptionalColorControl.svelte +++ /dev/null @@ -1,99 +0,0 @@ - - -{#if isSet} - - onchange(v)} /> - - -{:else} - -{/if} - - diff --git a/builder/web/src/components/advanced/OutputTab.svelte b/builder/web/src/components/advanced/OutputTab.svelte deleted file mode 100644 index e65f62ef73..0000000000 --- a/builder/web/src/components/advanced/OutputTab.svelte +++ /dev/null @@ -1,158 +0,0 @@ - - -
-
-
-

Position marker

-

- The arrow drawn at the GPS position. Its shape is fixed in firmware; pick a color - that reads over both land and sea. -

-
- { - env.config.marker.color = v; - working.markModified(); - }} - /> -
- -
-
-

Chunk size

-

- Quadtree chunk payload target in bytes — an expert knob. Larger chunks mean fewer - index nodes; the maximum is the device reader's per-feature cap. -

-
- { - const v = parseInt(e.currentTarget.value, 10); - if (Number.isFinite(v)) { - env.config.chunk_size = v; - working.markModified(); - } - }} - /> -
- -
-
-

Merge fills

-

- Dissolve fill polygons that render identically — same colour, no outline — into one - shape per zoom level, dropping shared parcel boundaries. A pure size and render-cost - win with no visual change; off packs exactly as before. -

-
- -
- -
-
-

Merge lines

-

- Stitch same-styled road/path/rail fragments — one OSM way split into many segments — - into continuous polylines per zoom level. Reclaims the per-feature scratch that - saturates at mid zoom; solid lines look identical, a dashed or cased line runs - continuous across former joins. Off packs exactly as before. -

-
- -
- -
-
-

Packer

-

- The editor's capability follows the schema served by the obc-pack binary on this - machine. -

-
- - {#if schema} - OBCM v{schema.format_version ?? "?"} · schema {schema.schema_version} · {schema.source} - {:else} - schema unavailable - {/if} - -
-
- - diff --git a/builder/web/src/components/advanced/ProfilesTab.svelte b/builder/web/src/components/advanced/ProfilesTab.svelte deleted file mode 100644 index 74900e6fc3..0000000000 --- a/builder/web/src/components/advanced/ProfilesTab.svelte +++ /dev/null @@ -1,261 +0,0 @@ - - -{#if !ps} -
-

- The obc-pack build on this machine doesn't expose the routing schema, so the profile - editor is unavailable. Rebuild obc-pack (OBCM v9+) to edit bike profiles. -

-
-{:else} -
-

- Bike profiles weight the nav graph so the router prefers some way and surface types over - others. Each multiplier is ≥ 1.0 (1.0 = neutral, higher = avoid); unlisted classes use the - profile's default. The climb weight ({ps.climbMin}–{ps.climbMax}) is separate: flat - metres charged per metre of ascent, added to the cost rather than scaling it, so - {ps.climbMin} is climb-blind and only maps packed with terrain feel it. The device picks one - of the four bike types. Their names and order are fixed; only the weights change. -

-
- - {#if hint} -

{hint}

- {/if} - - {#each profiles as profile, i (i)} -
-
- {profile.name} -
- other classes - editDefault(i, v)} - onclear={() => editDefault(i, ps.defaultMultiplier)} - onhint={(h) => (hint = h)} - /> -
-
- - climb weight - - editClimb(i, v)} - onclear={() => revertClimb(i)} - onhint={(h) => (hint = h)} - /> -
- - -
- - {#each groups as group (group)} -
- {group} -
- {#each classNames(ps, group) as cls (cls)} -
- {cls} - editCell(i, group, cls, v)} - onclear={() => revertCell(i, group, cls)} - onhint={(h) => (hint = h)} - /> -
- {/each} -
-
- {/each} -
- {/each} -{/if} - - diff --git a/builder/web/src/components/advanced/ProfilesTab.svelte.test.ts b/builder/web/src/components/advanced/ProfilesTab.svelte.test.ts deleted file mode 100644 index c25fcf2807..0000000000 --- a/builder/web/src/components/advanced/ProfilesTab.svelte.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -// @vitest-environment happy-dom - -// The profiles editor mounted against the *real* schema `obc-pack schema` -// serves, so the climb-weight cell is pinned to the field the packer actually -// reads rather than to a fixture that could drift from it. - -import { readFileSync } from "node:fs"; -import { resolve } from "node:path"; -import { mount, unmount } from "svelte"; -import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import type { NavProfile, SchemaEnvelope } from "../../lib/config/model"; -import { working, type WorkingEnvelope } from "../../lib/config/storage.svelte"; -import ProfilesTab from "./ProfilesTab.svelte"; - -// Resolved from the vitest root (builder/web) — a happy-dom test's -// `import.meta.url` is not a file: URL. -const SCHEMA = JSON.parse( - readFileSync(resolve(process.cwd(), "../../host/obc-map-core/schema/config.schema.json"), "utf8"), -); -const schema = { schema_version: 1, format_version: 12, source: "binary", schema: SCHEMA } as SchemaEnvelope; - -function envelope(profiles?: NavProfile[]): WorkingEnvelope { - return { - schema_version: 1, - based_on: null, - modified: false, - config: { - lods: [{ max_mpp: null, simplify: 0 }], - features: {}, - marker: { color: "0xF800" }, - ...(profiles ? { routing: { profiles } } : {}), - }, - disabled: [], - }; -} - -const mounted: ReturnType[] = []; - -function render(): HTMLElement { - const target = document.createElement("div"); - document.body.append(target); - mounted.push(mount(ProfilesTab, { target, props: { schema } })); - return target; -} - -/** Every climb-weight input on screen, one per profile card, in card order. */ -function climbInputs(target: HTMLElement): HTMLInputElement[] { - return [...target.querySelectorAll('input[aria-label$="climb weight"]')]; -} - -function type(input: HTMLInputElement, text: string) { - input.value = text; - input.dispatchEvent(new Event("input", { bubbles: true })); - input.dispatchEvent(new Event("change", { bubbles: true })); -} - -beforeEach(() => { - working.envelope = envelope(); -}); - -afterEach(async () => { - while (mounted.length) await unmount(mounted.pop()!); - working.envelope = null; - document.body.replaceChildren(); -}); - -describe("the climb-weight cell", () => { - it("shows the shipped weights — Road 10 / Gravel 8 / MTB 6 / Touring 8", () => { - const target = render(); - const cells = climbInputs(target); - expect(cells.map((c) => c.getAttribute("aria-label"))).toEqual([ - "Road climb weight", - "Gravel climb weight", - "MTB climb weight", - "Touring climb weight", - ]); - expect(cells.map((c) => c.value)).toEqual(["10", "8", "6", "8"]); - // The bounds come off the schema, not a frontend copy. - expect(cells[0].min).toBe("0"); - expect(cells[0].max).toBe("255"); - }); - - it("writes the edited weight into the config the packer is handed", () => { - const target = render(); - type(climbInputs(target)[1], "3"); - expect(working.envelope!.config.routing!.profiles[1].climb_weight).toBe(3); - expect(working.envelope!.modified).toBe(true); - // 0 is a value, not an unset — a climb-blind profile must be expressible. - type(climbInputs(target)[1], "0"); - expect(working.envelope!.config.routing!.profiles[1].climb_weight).toBe(0); - }); - - it("refuses an out-of-range weight, reverts the field, and says why", () => { - const target = render(); - type(climbInputs(target)[0], "900"); - // Nothing reached the model — the config is still `routing`-less, exactly - // as it was before the rejected keystroke. - expect(working.envelope!.config.routing).toBeUndefined(); - expect(climbInputs(target)[0].value).toBe("10"); - expect(target.textContent).toContain("climb-blind"); - }); - - it("renders a pre-v12 profile as climb-blind rather than blank", () => { - working.envelope = envelope([{ name: "Legacy", default: 2.0 }]); - const target = render(); - const cell = climbInputs(target)[0]; - expect(cell.value).toBe("0"); - expect(cell.closest(".cell")?.classList.contains("unstated")).toBe(true); - // …and it stays absent in the config until someone edits it. - expect("climb_weight" in working.envelope!.config.routing!.profiles[0]).toBe(false); - }); -}); diff --git a/builder/web/src/components/advanced/SchemaField.svelte b/builder/web/src/components/advanced/SchemaField.svelte deleted file mode 100644 index ff9bb64f90..0000000000 --- a/builder/web/src/components/advanced/SchemaField.svelte +++ /dev/null @@ -1,98 +0,0 @@ - - -{#if isColor} - onchange(v)} - /> -{:else if options} - -{:else if isBool} - onchange(e.currentTarget.checked)} - /> -{:else if isNumber} - { - const v = parseFloat(e.currentTarget.value); - if (Number.isFinite(v)) onchange(field.type === "integer" ? Math.trunc(v) : v); - }} - /> -{:else} - onchange(e.currentTarget.value)} - /> -{/if} - - diff --git a/builder/web/src/components/advanced/SchemaLab.svelte b/builder/web/src/components/advanced/SchemaLab.svelte deleted file mode 100644 index 6e77ac58b4..0000000000 --- a/builder/web/src/components/advanced/SchemaLab.svelte +++ /dev/null @@ -1,383 +0,0 @@ - - -
-
-
-

Maintainer schema lab

-

Teningen on the real device renderer

-

- Edits debounce into one native pack of a fixed crop. Nothing here bakes a region or changes the - product builders. Expect roughly 5–15 seconds depending on the machine and cache, not an instant restyle. -

-
- - {#if phase.kind === "waiting"}Waiting for edits… - {:else if phase.kind === "packing"}Packing Teningen… - {:else if phase.kind === "displayed" && renderer}Packed in {(packDurationMs / 1000).toFixed(1)} s - {:else if phase.kind === "error"}{phase.message} - {:else}Checking source…{/if} - -
- - {#if source && !source.available} -
- Preview source unavailable - {source.detail} - obc web preview-source - -
- {:else} -
-
-
- - {#if !renderer} -
{phase.kind === "packing" ? "Packing…" : "Waiting for preview…"}
- {/if} -
- -
- {#each lodChips as _lod, index} - {@const value = representativeMpp(lodChips, index)} - - {/each} -
-
- -
-

Production frame stats

- {#if stats && renderer} -
-
Scale / LOD
{stats.metersPerPixel.toFixed(1)} m/px · {stats.lodIndex}/{stats.lodCount - 1}
-
Features
{stats.featuresDrawn}/{stats.featuresTried} drawn
-
Dropped
0}>{stats.featuresDropped}
-
Chunks
{stats.chunksVisited}
-
Spans
{stats.spansUsed}/{renderer.limits.maxSpans.toLocaleString()}
-
Frame points
{stats.pointsDrawn}/{renderer.limits.maxFramePoints.toLocaleString()}
-
Frame rings
{stats.ringsUsed}/{renderer.limits.maxFrameRings.toLocaleString()}
-
Points tried
{stats.pointsTried}
-
Decode overflows
0}>{stats.featureDecodeCapacityDrops}
-
Malformed / map errors
0}>{stats.malformedFeatures} / {stats.mapErrors}
-
- {:else} -

Stats appear after the first production render.

- {/if} - {#if renderer} -

- Per feature: {renderer.limits.maxFeaturePoints.toLocaleString()} points · {renderer.limits.maxFeatureRings.toLocaleString()} rings. - Frame: {renderer.limits.maxSpans.toLocaleString()} spans · {renderer.limits.maxFramePoints.toLocaleString()} points · {renderer.limits.maxFrameRings.toLocaleString()} rings. -

- {/if} - {#if diagnostics.length} - - {/if} -
-
- {/if} -
- - diff --git a/builder/web/src/components/advanced/StyleTable.svelte b/builder/web/src/components/advanced/StyleTable.svelte deleted file mode 100644 index c7b0c59b93..0000000000 --- a/builder/web/src/components/advanced/StyleTable.svelte +++ /dev/null @@ -1,420 +0,0 @@ - - -
-
- {Object.keys(entries).length} types — drag ⋮⋮ to reorder (order sets draw priority on ties) - -
- -
- - on - type - color - {#each extras as [name] (name)} - {name} - {/each} - w - z - prio - levels - - - {#each order as name (name)} - {#if entries[name]} - {@const def = entries[name]} -
{ - dragging = name; - e.dataTransfer!.effectAllowed = "move"; - e.dataTransfer!.setData("text/plain", name); - }} - ondragover={(e) => dragOver(e, name)} - ondragend={dragEnd} - > - - setOn(name, e.currentTarget.checked)} - /> - {#if name === "*"} - ∗ any (catch-all) - {:else} - {name} - {/if} - { - def.color = v; - working.markModified(); - }} - /> - {#each extras as [ename, eprop] (ename)} - { - // undefined ⇒ the field is cleared (optional - // color2): drop the key so it's absent from the - // emitted JSON, not present-but-undefined. - if (v === undefined) delete def[ename]; - else def[ename] = v; - working.markModified(); - }} - /> - {/each} - numEdit(name, "weight", e.currentTarget.value)} - /> - numEdit(name, "z_index", e.currentTarget.value)} - /> - - { - def.min_lod = v; - working.markModified(); - }} - /> - -
- {/if} - {/each} -
- - {#if adding} - (dupe = false)} - onkeydown={(e) => { - if (e.key === "Enter") commitAdd(); - else if (e.key === "Escape") (adding = false), (newName = ""); - }} - onblur={commitAdd} - /> - - {#each catalogValues.filter((v) => !entries[v]) as v (v)} - - {/each} - - {:else} -
- - {#if !hasCatchAll} - - {/if} -
- {/if} -
- - diff --git a/builder/web/src/components/coverage/CoverageHome.svelte b/builder/web/src/components/coverage/CoverageHome.svelte deleted file mode 100644 index e41f18ddae..0000000000 --- a/builder/web/src/components/coverage/CoverageHome.svelte +++ /dev/null @@ -1,207 +0,0 @@ - - -{#if catalogFailed || refreshing || refreshError || refreshNotice || store.refreshNotice} -
-

{refreshError ? `The map catalog could not be refreshed: ${refreshError}` : refreshing ? "Refreshing the map catalog…" : store.refreshNotice ?? refreshNotice ?? "Refresh the map catalog to use the current published map data. Your selection is kept."}

- - {#if refreshBlocked}

Wait for the device transfer or map cleanup to finish before refreshing.

{/if} -
-{/if} - -{#key store} -
- - -
-
-
-

Choose coverage

- {#if partCount > 0} - - {partCount} - {partCount === 1 ? "part" : "parts"} - - {/if} -
-
- - {#if partCount > 0 || store.indexError || store.resolutionError} - - {/if} -
-
- -
-
-

Download your map

-
-
- - Map style · Optional - {styleNames} - -
-
- (sendReady = ready)} onFailureChange={(failed) => (downloadFailed = failed)} onRefreshBlockedChange={(blocked) => (runBlocked = blocked)} /> -
- -
-
-

Or send directly to device

-
- -
-
-
- -{/key} - - diff --git a/builder/web/src/components/coverage/CoverageHome.svelte.test.ts b/builder/web/src/components/coverage/CoverageHome.svelte.test.ts deleted file mode 100644 index 6d74947135..0000000000 --- a/builder/web/src/components/coverage/CoverageHome.svelte.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -// @vitest-environment happy-dom - -import { mount, tick, unmount } from "svelte"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import { CatalogClient } from "../../lib/catalog/client"; -import { readFileSync } from "node:fs"; -import { URL as NodeURL } from "node:url"; -const EXAMPLE_ROOT = readFileSync(new NodeURL("../../../../../host/obc-pack/schema/catalog.example.json", import.meta.url), "utf8"); -import { DeviceJob } from "../../lib/device/job.svelte"; -import CoverageHome from "./CoverageHome.svelte"; -import Home from "../../routes/Home.svelte"; - -vi.mock("./CoverageMap.svelte", async () => ({ default: (await import("../../../test-support/coverage/Selection.svelte")).default })); -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" } })); - -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(); } } -function button(target: HTMLElement, text: string) { - return [...target.querySelectorAll("button")].find((b) => b.textContent === text)!; -} -afterEach(() => { document.body.replaceChildren(); vi.clearAllMocks(); }); - -describe("catalog recovery", () => { - it("keeps selection on refresh failure, then replaces the whole catalog and exposes removed coverage", async () => { - const target = document.createElement("div"); - document.body.append(target); - const root = JSON.parse(EXAMPLE_ROOT); - root.regions = root.regions.filter((r: { id: string }) => r.id !== "europe/switzerland" && !r.id.startsWith("europe/switzerland/")); - const body = JSON.stringify(root); - const refreshCatalog = vi.fn() - .mockRejectedValueOnce(new Error("offline")) - .mockResolvedValueOnce({ client: client(body, "https://maps.test/new/catalog.json"), body }); - const component = mount(CoverageHome, { target, props: { client: client(EXAMPLE_ROOT, "https://maps.test/old/catalog.json"), rootBody: EXAMPLE_ROOT, refreshCatalog } }); - button(target, "Choose Switzerland").click(); - await settle(); - expect(target.textContent).toContain("Switzerland"); - button(target, "Refresh map catalog").click(); - await settle(); - expect(target.textContent).toContain("could not be refreshed: offline"); - expect(target.querySelector('[data-catalog]')?.getAttribute("data-catalog")).toContain("/old/"); - expect(target.querySelector('[aria-label="Remove Switzerland"]')).not.toBeNull(); - button(target, "Refresh map catalog").click(); - await settle(); - expect(target.querySelector('[data-catalog]')?.getAttribute("data-catalog")).toContain("/new/"); - expect(target.textContent).toContain("This region is no longer in the map catalog"); - expect(document.activeElement).toBe(target.querySelector(".recovery")); - (target.querySelector('[aria-label="Remove Switzerland"]') as HTMLButtonElement).click(); - await tick(); - expect(target.querySelector('[aria-label="Remove Switzerland"]')).toBeNull(); - expect(refreshCatalog).toHaveBeenCalledTimes(2); - await unmount(component); - }); - - it("keeps the old catalog if a picked-file device transfer starts during refresh", async () => { - let finishRefresh!: (result: { client: CatalogClient; body: string }) => void; - const refreshCatalog = vi.fn(() => new Promise<{ client: CatalogClient; body: string }>((resolve) => { finishRefresh = resolve; })); - const target = document.createElement("div"); - document.body.append(target); - const component = mount(CoverageHome, { target, props: { client: client(EXAMPLE_ROOT, "https://maps.test/old/catalog.json"), rootBody: EXAMPLE_ROOT, refreshCatalog } }); - await settle(); - button(target, "Refresh map catalog").click(); - await settle(); - let finishSend!: () => void; - const job = new DeviceJob("map"); - const send = job.run(() => new Promise((resolve) => { finishSend = resolve; }), () => "sent"); - finishRefresh({ client: client(EXAMPLE_ROOT, "https://maps.test/new/catalog.json"), body: EXAMPLE_ROOT }); - await settle(); - expect(target.querySelector('[data-catalog]')?.getAttribute("data-catalog")).toContain("/old/"); - expect(target.textContent).toContain("Wait for the device transfer"); - expect(button(target, "Refresh map catalog").disabled).toBe(true); - expect(job.running).toBe(true); - finishSend(); - await send; - await settle(); - expect(button(target, "Refresh map catalog").disabled).toBe(false); - await unmount(component); - }); - - it("offers a native button to refresh an initially unreadable catalog", async () => { - host.catalog.mockRejectedValueOnce(new Error("removed root")) - .mockResolvedValueOnce({ url: "https://maps.test/new/catalog.json", body: EXAMPLE_ROOT }); - const target = document.createElement("div"); - document.body.append(target); - const component = mount(Home, { target }); - await settle(); - expect(target.querySelector('[role="alert"]')?.textContent).toContain("removed root"); - button(target, "Refresh map catalog").click(); - await settle(); - expect(host.catalog).toHaveBeenLastCalledWith({ refresh: true }); - expect(target.querySelector('[data-catalog]')?.getAttribute("data-catalog")).toContain("/new/"); - await unmount(component); - }); -}); diff --git a/builder/web/src/components/coverage/DownloadStep.svelte b/builder/web/src/components/coverage/DownloadStep.svelte deleted file mode 100644 index 156e7f462e..0000000000 --- a/builder/web/src/components/coverage/DownloadStep.svelte +++ /dev/null @@ -1,439 +0,0 @@ - - -{#if !ledger || ledger.cellCount === 0} -

Choose a region or draw an area on the map.

-{:else} -
- {#if proof} -
- - - - - - - - {#each proof.holes as r, k (k)} - - - {/each} - -
{proofCaption(proof)}
-
- {/if} - -
- {#if run.refusal} -

{run.refusal}

- {:else if run.estimateError} -

- Could not check memory requirements: {run.estimateError} - -

- {:else if run.memoryCaution} -

{run.memoryCaution}

- {/if} - -
- - - {#if run.cellStorageNotice}{run.cellStorageNotice}{/if} -
- - {#if run.phase === "idle" || run.phase === "cancelled" || run.phase === "error" || run.phase === "done"} - - - {:else} -
- {#if run.phase !== "finalizing"} - - {/if} - {#if run.phase === "downloading" && run.dlProgress} - - 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 run.phase === "assembling"} - - assembling — {ASM_PHASE_LABEL[run.asmPhase]} · {Math.round(run.asmFraction * 100)}%{#if run.readMode} - · cells {run.readMode}{/if} - - {:else if run.phase === "saving"} - - {run.sendingToDevice ? "sending the map" : "saving the map"}{#if run.runFileName} - — {run.runFileName}{/if} - - {:else if run.phase === "finalizing"} - finishing up — removing temporary map data - {/if} -
-
- -
- {/if} - - {#if run.phase === "done"} -
- {#if run.lastRunKind === "device"} -

Assembled and sent {run.runFileName}.

- {:else} -

Downloaded {run.savedFile?.name}.

- {/if} - {#if run.savedFile} -

{formatBytes(run.savedFile.byteLength)}

- {/if} - {#if run.readMode} -

- 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 run.runWarnings as w, k (k)} -

{w}

- {/each} -
- {:else if run.phase === "error"} -

- {#if run.persisted} - The map was not completed. Discard the file it left behind: {run.errorMessage} - {:else} - Nothing was saved: {run.errorMessage} - {/if} -

- {:else if run.phase === "cancelled"} -

- {#if run.persisted} - Cancelled — discard the incomplete file it left behind. - {:else} - Cancelled — nothing was saved. - {/if} -

- {/if} -
-
-{/if} - - diff --git a/builder/web/src/components/coverage/DownloadStep.svelte.test.ts b/builder/web/src/components/coverage/DownloadStep.svelte.test.ts deleted file mode 100644 index 65ca81207c..0000000000 --- a/builder/web/src/components/coverage/DownloadStep.svelte.test.ts +++ /dev/null @@ -1,1077 +0,0 @@ -// @vitest-environment happy-dom - -import { mount, tick, unmount } from "svelte"; -import { SvelteMap } from "svelte/reactivity"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -interface TestCellStore { - revision: string; - alive: boolean; - has: ReturnType Promise>>; - put: ReturnType Promise>>; -} - -const seams = vi.hoisted(() => ({ - sendMapBlob: vi.fn(), - sendMapBytes: vi.fn(), - readMapOutput: vi.fn(async () => new Blob([Uint8Array.of(1, 2, 3, 4)])), - cellStoreWritable: vi.fn(async () => false), - clearAssemblyStorage: vi.fn(async () => undefined), - clearCellStores: vi.fn(async () => undefined), - clearMapWorkStorage: vi.fn(async () => undefined), - hasRoomFor: vi.fn(async (_bytes: number, _reclaimable = 0) => false), - openCellInventory: vi.fn<() => Promise>(async () => null), - openCellStore: vi.fn<() => Promise>(async () => null), - downloadCells: vi.fn(), - discardCellStore: vi.fn(async () => undefined), - discardMapOutput: vi.fn(async () => undefined), - reclaimableAssemblyBytes: vi.fn(async () => 0), - saveBlob: vi.fn(), - workerOutput: "stored" as "stored" | "file", - /** Make the worker end the run with a `done` the protocol guard rejects. */ - unreadableDone: false, - workerError: null as string | null, - workerAssemble: 0, - requireDisk: false, - memoryRequiresDisk: false, - holdEstimates: false, - estimateReplies: [] as Array<(error?: boolean) => void>, - workerTerminate: 0, - worker: null as null | { onmessage: ((event: MessageEvent) => void) | null }, - holdAssembly: false, - plan: { items: [], totalBytes: 0, knownEmpty: [] } as { - items: Array<{ band: string | null; cell: { id: string; sha256: string; bytes: number; partial?: boolean } }>; - totalBytes: number; - knownEmpty: never[]; - }, -})); - -vi.mock("../../lib/cells/store", () => ({ - cellStoreRevision: () => "test-revision", - cellStoreWritable: seams.cellStoreWritable, - clearAssemblyStorage: seams.clearAssemblyStorage, - clearCellStores: seams.clearCellStores, - clearMapWorkStorage: seams.clearMapWorkStorage, - discardCellStore: seams.discardCellStore, - discardMapOutput: seams.discardMapOutput, - hasRoomFor: seams.hasRoomFor, - openCellInventory: seams.openCellInventory, - openCellStore: seams.openCellStore, - readMapOutput: seams.readMapOutput, - reclaimableAssemblyBytes: seams.reclaimableAssemblyBytes, -})); - -vi.mock("../../lib/catalog/download", () => ({ - planCells: () => seams.plan, - downloadCells: seams.downloadCells, -})); - -vi.mock("../../lib/device/write", () => ({ - sendMapBlob: seams.sendMapBlob, - sendMapBytes: seams.sendMapBytes, -})); -vi.mock("../../lib/download", () => ({ saveBlob: seams.saveBlob })); - -import { DeviceJob, jobRegistry } from "../../lib/device/job.svelte"; -import { deviceHolder } from "../../lib/device/session.svelte"; -import type { SendAssembledMap } from "../../lib/device/write"; -import { DeviceError, type FlatStoreClient } from "../../lib/usb/client"; -import MapSend from "../device/MapSend.svelte"; -import DownloadStep from "./DownloadStep.svelte"; - -class AssembleWorker { - onmessage: ((event: MessageEvent) => void) | null = null; - onerror: ((event: ErrorEvent) => void) | null = null; - onmessageerror: (() => void) | null = null; - - constructor() { - seams.worker = this; - } - - postMessage(request: { type?: string; estimateId?: number; onDisk?: boolean; requireDisk?: boolean }) { - if (request.type === "estimate") { - const reply = (error = false) => this.onmessage?.( - new MessageEvent("message", { - data: error ? { type: "error", estimateId: request.estimateId, code: "internal", message: "stale estimate" } : { - type: "estimate-result", - estimateId: request.estimateId, - onDisk: request.onDisk, - estimate: { - engineBytes: 1, - inputBytes: 1, - outputBytes: 1, - peakBytes: seams.memoryRequiresDisk && !request.onDisk ? 120 : 3, - budgetBytes: 100, - ceilingBytes: 100, - headroomBytes: seams.memoryRequiresDisk && !request.onDisk ? 0 : 97, - fits: !seams.memoryRequiresDisk || request.onDisk === true, - }, - }, - }), - ); - seams.estimateReplies.push(reply); - if (!seams.holdEstimates) queueMicrotask(() => reply()); - } else if (request.type === "assemble") { - seams.workerAssemble += 1; - seams.requireDisk = request.requireDisk ?? false; - if (seams.holdAssembly) return; - queueMicrotask(() => { - if (seams.workerError) { - this.onmessage?.( - new MessageEvent("message", { - data: { type: "error", code: "io", message: seams.workerError }, - }), - ); - return; - } - this.onmessage?.( - new MessageEvent("message", { - data: seams.workerOutput === "stored" - ? { type: "stored-map", sha256: "abc", byteLength: 4 } - : { - type: "file", - sha256: "abc", - byteLength: 4, - bytes: Uint8Array.of(1, 2, 3, 4), - }, - }), - ); - queueMicrotask(() => - this.onmessage?.( - new MessageEvent("message", { - data: seams.unreadableDone - ? { type: "done", warnings: [], summary: {} } - : { type: "done", warnings: [], summary: {}, wasmMemoryBytes: 16 * 1024 * 1024 }, - }), - ), - ); - }); - } - } - - terminate() { - seams.workerTerminate += 1; - } -} - -describe("direct assembler delivery", () => { - beforeEach(() => { - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); - vi.stubGlobal("Worker", AssembleWorker); - try { - globalThis.localStorage?.removeItem("obcm.keepMapCells"); - } catch {} - seams.sendMapBlob.mockReset(); - seams.sendMapBytes.mockReset(); - seams.cellStoreWritable.mockReset().mockResolvedValue(false); - seams.clearAssemblyStorage.mockReset().mockResolvedValue(undefined); - seams.clearCellStores.mockReset().mockResolvedValue(undefined); - seams.clearMapWorkStorage.mockReset().mockResolvedValue(undefined); - seams.hasRoomFor.mockReset().mockResolvedValue(false); - seams.openCellInventory.mockReset().mockResolvedValue(null); - seams.openCellStore.mockReset().mockResolvedValue(null); - seams.downloadCells.mockReset().mockImplementation( - async ( - _plan: unknown, - options: { onProgress?: (progress: Record) => void }, - ) => { - options.onProgress?.({ - completedCells: 0, - totalCells: 0, - receivedBytes: 0, - totalBytes: 0, - }); - }, - ); - seams.discardCellStore.mockReset().mockResolvedValue(undefined); - seams.discardMapOutput.mockClear(); - seams.reclaimableAssemblyBytes.mockReset().mockResolvedValue(0); - seams.saveBlob.mockClear(); - seams.workerOutput = "stored"; - seams.unreadableDone = false; - seams.workerError = null; - seams.workerAssemble = 0; - seams.requireDisk = false; - seams.memoryRequiresDisk = false; - seams.holdEstimates = false; - seams.estimateReplies = []; - seams.workerTerminate = 0; - seams.worker = null; - seams.holdAssembly = false; - seams.plan = { items: [], totalBytes: 0, knownEmpty: [] }; - }); - - afterEach(() => { - deviceHolder.interrupted = null; - vi.useRealTimers(); - vi.unstubAllGlobals(); - document.body.replaceChildren(); - }); - - it("drains old catalog work before refresh and closes admission until resumed", async () => { - let returnFetch!: () => void; - let oldSignal!: AbortSignal; - seams.downloadCells.mockImplementation((_plan, options) => new Promise((resolve) => { - oldSignal = options.signal; - returnFetch = resolve; - })); - const { component, target } = await mountReadyStep(); - (target.querySelector("button.primary") as HTMLButtonElement).click(); - for (let n = 0; n < 30 && !returnFetch; n++) { await Promise.resolve(); await tick(); } - expect(returnFetch).toBeDefined(); - let drained = false; - const pause = component.pauseForRefresh().then((resume) => { drained = true; return resume; }); - await tick(); - expect(oldSignal.aborted).toBe(true); - expect(drained).toBe(false); - await expectSecondRunRefused(component); - returnFetch(); - const resume = await pause; - await tick(); - expect(seams.workerAssemble).toBe(0); - expect(seams.saveBlob).not.toHaveBeenCalled(); - expect((target.querySelector("button.primary") as HTMLButtonElement).disabled).toBe(true); - resume(); - await waitForReady(target); - await unmount(component); - }); - - it("refuses catalog refresh while an actual device PUT is active", async () => { - let releasePut!: () => void; - seams.sendMapBlob.mockImplementation((_client, _blob, _name, options) => new Promise((resolve) => { - releasePut = () => resolve({ objectId: 1, revision: 1 }); - options.signal.addEventListener("abort", () => resolve({ objectId: 1, revision: 1 })); - })); - const { component } = await mountReadyStep(); - const job = new DeviceJob("map"); - const send = job.run((ctx) => component.sendToDevice({} as FlatStoreClient, ctx), () => "done"); - for (let n = 0; n < 60 && !releasePut; n++) { await Promise.resolve(); await tick(); } - expect(releasePut).toBeDefined(); - await expect(component.pauseForRefresh()).rejects.toThrow(/Wait for the map send/); - expect(job.running).toBe(true); - releasePut(); - await send; - await unmount(component); - }); - - it("shows the projected memory refusal and closes Download map", async () => { - seams.memoryRequiresDisk = true; - const { component, target } = await mountReadyStep(); - const refusal = target.querySelector(".warn")?.textContent ?? ""; - expect(refusal).toContain("120 B of browser memory"); - expect(refusal).toContain("100 B"); - expect(refusal).toContain("Reduce the map selection"); - expect((target.querySelector("button.primary") as HTMLButtonElement).disabled).toBe(true); - await unmount(component); - }); - - it("shows download progress, then the assembly phase the worker reports", async () => { - seams.holdAssembly = true; - let report!: (progress: { completedCells: number; totalCells: number; receivedBytes: number; totalBytes: number }) => void; - let finishDownload!: () => void; - seams.downloadCells.mockImplementation((_plan, options) => new Promise((resolve) => { - report = options.onProgress!; - finishDownload = resolve; - })); - const { component, target } = await mountReadyStep(); - (target.querySelector("button.primary") as HTMLButtonElement).click(); - for (let attempt = 0; attempt < 30 && !report; attempt++) { - await Promise.resolve(); - await tick(); - } - expect(report).toBeDefined(); - report({ completedCells: 1, totalCells: 2, receivedBytes: 500, totalBytes: 1_000 }); - await tick(); - expect(target.textContent).toContain("downloading cells — 1/2"); - expect(target.textContent).toContain("500 B of 1000 B"); - expect(target.querySelector(".bar span")?.getAttribute("style")).toContain("50%"); - - finishDownload(); - for (let attempt = 0; attempt < 30 && seams.workerAssemble === 0; attempt++) { - await Promise.resolve(); - await tick(); - } - expect(seams.workerAssemble).toBe(1); - seams.worker!.onmessage!(new MessageEvent("message", { data: { type: "progress", phase: "nav", fraction: 0.25 } })); - await tick(); - expect(target.textContent).toContain("assembling — stitching the road network · 25%"); - expect(target.querySelector(".bar span")?.getAttribute("style")).toContain("25%"); - [...target.querySelectorAll("button")].find((button) => button.textContent === "Cancel")!.click(); - await unmount(component); - }); - - it("refuses lost required cell storage before downloading", async () => { - seams.cellStoreWritable.mockResolvedValue(true); - seams.hasRoomFor.mockResolvedValue(true); - const { component } = await mountReadyStep(); - const job = new DeviceJob("map"); - await job.run((ctx) => component.sendToDevice({} as FlatStoreClient, ctx), () => "sent"); - expect(job.error).toContain("storage required"); - expect(seams.downloadCells).not.toHaveBeenCalled(); - expect(seams.workerAssemble).toBe(0); - await unmount(component); - }); - - it("carries disk admission after the running effect clears the estimate", async () => { - seams.cellStoreWritable.mockResolvedValue(true); - seams.hasRoomFor.mockResolvedValue(true); - seams.openCellStore.mockResolvedValue(testCellStore()); - seams.sendMapBlob.mockResolvedValue({ objectId: 1n }); - const { component } = await mountReadyStep(); - const job = new DeviceJob("map"); - await job.run((ctx) => component.sendToDevice({} as FlatStoreClient, ctx), () => "sent"); - expect(seams.requireDisk).toBe(true); - expect(seams.workerAssemble).toBe(1); - expect(seams.clearAssemblyStorage).toHaveBeenCalledOnce(); - await unmount(component); - }); - - it("admits a disk-only rebuild only when cached cells make the quota projection fit", async () => { - seams.memoryRequiresDisk = true; - seams.cellStoreWritable.mockResolvedValue(true); - // Between this run's disk projection with its 800 MB cell cached (2.2 GB) and with - // nothing cached (3 GB), so only the cache decides admission. - seams.hasRoomFor.mockImplementation(async (bytes: number) => bytes <= 2_500_000_000); - seams.plan = { - items: [ - { band: "fine", cell: { id: "cell-1", sha256: "cached", bytes: 800_000_000 } }, - { band: "fine", cell: { id: "cell-2", sha256: "missing", bytes: 200_000_000 } }, - ], - totalBytes: 1_000_000_000, - knownEmpty: [], - }; - seams.sendMapBlob.mockResolvedValue({ objectId: 1n }); - const large = { - ...store, - ledger: { - totalBytes: 1_000_000_000, - cellCount: 2, - core: { bytes: 400_000_000 }, - terrain: null, - isFinal: true, - }, - }; - // The rider kept map data last time, so the estimate counts cached cells from the start. - globalThis.localStorage.setItem("obcm.keepMapCells", "true"); - const mountWithCells = async (cells: TestCellStore) => { - seams.openCellInventory.mockResolvedValue(cells); - seams.openCellStore.mockResolvedValue(cells); - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); - const built = await mountReadyStep({ store: large }); - const download = built.target.querySelector("button.primary") as HTMLButtonElement; - for (let attempt = 0; attempt < 40 && download.disabled && !built.target.querySelector(".warn"); attempt++) { - await new Promise((resolve) => setTimeout(resolve, 20)); - await tick(); - } - return { ...built, download }; - }; - - const cold = await mountWithCells(testCellStore()); - expect(cold.target.querySelector(".warn")?.textContent ?? "").toContain("Reduce the map selection"); - expect(cold.download.disabled).toBe(true); - await unmount(cold.component); - - const cached = testCellStore(); - cached.has.mockImplementation(async (key) => key === "cached"); - const warm = await mountWithCells(cached); - expect(warm.target.querySelector(".warn")).toBeNull(); - expect(warm.download.disabled).toBe(false); - const job = new DeviceJob("map"); - await job.run((ctx) => warm.component.sendToDevice({} as FlatStoreClient, ctx), () => "sent"); - expect(job.phase).toBe("done"); - expect(seams.workerAssemble).toBe(1); - expect(seams.requireDisk).toBe(true); - await unmount(warm.component); - }); - - it("keeps prior assembly files when the fresh disk preflight refuses", async () => { - seams.cellStoreWritable.mockResolvedValue(true); - seams.hasRoomFor.mockResolvedValue(false); - seams.openCellStore.mockResolvedValue(testCellStore()); - seams.sendMapBlob.mockResolvedValue({ objectId: 1n }); - const { component } = await mountReadyStep(); - const job = new DeviceJob("map"); - await job.run((ctx) => component.sendToDevice({} as FlatStoreClient, ctx), () => "sent"); - expect(seams.clearAssemblyStorage).not.toHaveBeenCalled(); - expect(seams.workerAssemble).toBe(1); - await unmount(component); - }); - - it("ignores stale estimate success and failure while a new selection is pending", async () => { - seams.holdEstimates = true; - seams.cellStoreWritable.mockResolvedValue(true); - seams.hasRoomFor.mockResolvedValue(true); - const ledgers = new SvelteMap([["current", store.ledger]]); - const changing = { ...store, get ledger() { return ledgers.get("current")!; } }; - const { component, target } = await mountReadyStep({ store: changing }); - const oldReply = seams.estimateReplies[0]; - seams.hasRoomFor.mockResolvedValue(false); - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); - ledgers.set("current", { ...store.ledger, totalBytes: 8 }); - await expectSecondRunRefused(component); - await tick(); - vi.advanceTimersByTime(500); - for (let attempt = 0; attempt < 10 && seams.estimateReplies.length < 2; attempt++) { - await Promise.resolve(); - await tick(); - } - expect(seams.estimateReplies).toHaveLength(2); - oldReply(); - oldReply(true); - await tick(); - expect(target.textContent).not.toContain("stale estimate"); - await expectSecondRunRefused(component); - seams.estimateReplies[1](); - oldReply(); - await tick(); - vi.useRealTimers(); - seams.sendMapBlob.mockResolvedValue({ objectId: 1n }); - const job = new DeviceJob("map"); - await job.run((ctx) => component.sendToDevice({} as FlatStoreClient, ctx), () => "sent"); - expect(seams.workerAssemble).toBe(1); - expect(seams.requireDisk).toBe(false); - await unmount(component); - }); - - it("does not post an old storage probe after a newer selection was estimated", async () => { - let finishOld!: (value: boolean) => void; - seams.cellStoreWritable.mockImplementationOnce(() => new Promise((resolve) => { finishOld = resolve; })); - const ledgers = new SvelteMap([["current", store.ledger]]); - const changing = { ...store, get ledger() { return ledgers.get("current")!; } }; - const { component } = await mountReadyStep({ store: changing }); - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); - ledgers.set("current", { ...store.ledger, totalBytes: 8 }); - await tick(); - vi.advanceTimersByTime(500); - await Promise.resolve(); - await tick(); - expect(seams.estimateReplies).toHaveLength(1); - finishOld(true); - await Promise.resolve(); - await tick(); - expect(seams.estimateReplies).toHaveLength(1); - vi.useRealTimers(); - seams.sendMapBlob.mockResolvedValue({ objectId: 1n }); - const job = new DeviceJob("map"); - await job.run((ctx) => component.sendToDevice({} as FlatStoreClient, ctx), () => "sent"); - expect(seams.workerAssemble).toBe(1); - expect(seams.requireDisk).toBe(false); - await unmount(component); - }); - - it("makes the Step 3 Cancel abort PUT before it can commit", async () => { - let committed = false; - let putAborted = false; - seams.sendMapBlob.mockImplementation( - (_client: unknown, _blob: Blob, _name: string, ctx: { signal: AbortSignal }) => - new Promise((resolve, reject) => { - if (ctx.signal.aborted) { - putAborted = true; - reject(ctx.signal.reason); - return; - } - const commit = setTimeout(() => { - committed = true; - resolve({ objectId: 1n }); - }, 100); - ctx.signal.addEventListener( - "abort", - () => { - putAborted = true; - clearTimeout(commit); - reject(ctx.signal.reason); - }, - { once: true }, - ); - }), - ); - const ledger = { - totalBytes: 4, - cellCount: 1, - core: { bytes: 4 }, - terrain: null, - isFinal: true, - }; - const store = { - ledger, - resolution: { cellsByBand: new Map(), parts: [] }, - indices: new Map(), - catalog: { - schema: { - name: "Test schema", - bands: [{ id: "fine", lods: [16], role: "fine", cell_log2: 18 }], - }, - }, - terrain: null, - client: { fetchImpl: globalThis.fetch }, - selection: { parts: [] }, - lightSkin: { name: "Default" }, - darkSkin: { name: "Dusk" }, - rootBody: "{}", - holeCells: () => [], - }; - const { component, target } = await mountReadyStep({ store }); - const job = new DeviceJob("map"); - const running = job.run( - (ctx) => component.sendToDevice({} as FlatStoreClient, ctx), - () => "sent", - ); - for (let attempt = 0; attempt < 20 && !target.textContent?.includes("sending the map"); attempt++) { - await Promise.resolve(); - await tick(); - } - expect(target.textContent).toContain("sending the map"); - - const cancel = [...target.querySelectorAll("button")].find((button) => button.textContent === "Cancel"); - expect(cancel).toBeDefined(); - (cancel as HTMLButtonElement).click(); - await running; - - expect(putAborted).toBe(true); - expect(committed).toBe(false); - expect(job.phase).toBe("idle"); - expect(seams.discardMapOutput).toHaveBeenCalledOnce(); - await unmount(component); - }); - - it("sends a resident fallback without a duplicate Blob and removes direct staging", async () => { - seams.workerOutput = "file"; - seams.sendMapBytes.mockResolvedValue({ objectId: 1n }); - const { component } = await mountReadyStep(); - const job = new DeviceJob("map"); - - const result = await job.run( - (ctx) => component.sendToDevice({} as FlatStoreClient, ctx), - () => "sent", - ); - - expect(result).toEqual({ objectId: 1n }); - expect(seams.sendMapBytes).toHaveBeenCalledOnce(); - expect(seams.sendMapBytes.mock.calls[0][1]).toEqual(Uint8Array.of(1, 2, 3, 4)); - expect(seams.sendMapBlob).not.toHaveBeenCalled(); - expect(seams.discardMapOutput).toHaveBeenCalledOnce(); - await unmount(component); - }); - - it("terminates the idle estimate worker when the step unmounts", async () => { - const { component } = await mountReadyStep(); - - expect(seams.workerAssemble).toBe(0); - expect(seams.workerTerminate).toBe(0); - await unmount(component); - - expect(seams.workerTerminate).toBe(1); - }); - - it("preserves a physical link failure when teardown cancels direct delivery", async () => { - let rejectPut: ((cause: unknown) => void) | null = null; - seams.sendMapBlob.mockImplementation( - () => new Promise((_resolve, reject) => (rejectPut = reject)), - ); - const { component } = await mountReadyStep(); - const job = new DeviceJob("map"); - const running = job.run( - (ctx) => component.sendToDevice({} as FlatStoreClient, ctx), - () => "sent", - ); - for (let attempt = 0; attempt < 20 && rejectPut === null; attempt++) { - await Promise.resolve(); - await tick(); - } - expect(rejectPut).not.toBeNull(); - - rejectPut!(new DeviceError("link", "the USB cable disconnected")); - await unmount(component); - await running; - - expect(deviceHolder.interrupted).toContain("plug it back in"); - expect(seams.discardMapOutput).toHaveBeenCalledOnce(); - }); - - it("keeps every delivery action closed until deferred cleanup has finished", async () => { - let releaseCleanup!: () => void; - const cleanup = new Promise((resolve) => (releaseCleanup = () => resolve(undefined))); - seams.discardMapOutput.mockImplementationOnce(() => cleanup); - seams.sendMapBlob.mockResolvedValue({ objectId: 1n }); - const readyChanges: boolean[] = []; - const { component, target } = await mountReadyStep({ - onSendReadyChange: (ready) => readyChanges.push(ready), - }); - const first = new DeviceJob("map"); - const running = first.run( - (ctx) => component.sendToDevice({} as FlatStoreClient, ctx), - () => "sent", - ); - - for (let attempt = 0; attempt < 20 && !target.textContent?.includes("finishing up"); attempt++) { - await Promise.resolve(); - await tick(); - } - expect(target.textContent).toContain("finishing up"); - expect(target.textContent).not.toContain("Download map"); - expect(target.textContent).not.toContain("Cancel"); - expect(readyChanges.at(-1)).toBe(false); - - const second = new DeviceJob("map"); - await expect( - second.run( - (ctx) => component.sendToDevice({} as FlatStoreClient, ctx), - () => "sent twice", - ), - ).resolves.toBeNull(); - expect(second.error).toContain("not ready"); - expect(seams.sendMapBlob).toHaveBeenCalledOnce(); - - releaseCleanup(); - await running; - await tick(); - expect(first.phase).toBe("done"); - expect(target.textContent).toContain("Assembled and sent"); - await unmount(component); - }); - - it("keeps committed success when the real TransferBar is cancelled and unmounted during cleanup", async () => { - let commit!: (result: { objectId: bigint }) => void; - seams.sendMapBlob.mockImplementation( - () => new Promise((resolve) => (commit = resolve)), - ); - let releaseCleanup!: () => void; - const cleanup = new Promise((resolve) => (releaseCleanup = () => resolve(undefined))); - seams.discardMapOutput.mockImplementationOnce(() => cleanup); - const built = await mountReadyStep(); - const transferTarget = document.createElement("div"); - document.body.append(transferTarget); - let success: unknown = null; - let failure: unknown = null; - const send: SendAssembledMap = async (client, ctx) => { - try { - success = await built.component.sendToDevice(client, ctx); - return success as Awaited>; - } catch (cause) { - failure = cause; - throw cause; - } - }; - const mapSend = mount(MapSend, { - target: transferTarget, - props: { - client: {} as FlatStoreClient, - ledger: ledger as never, - sendAssembled: send, - sendReady: true, - }, - }); - - (transferTarget.querySelector("button.primary") as HTMLButtonElement).click(); - for (let attempt = 0; attempt < 20 && typeof commit !== "function"; attempt++) { - await Promise.resolve(); - await tick(); - } - const staleCancel = [...transferTarget.querySelectorAll("button")].find( - (button) => button.textContent === "Cancel", - ) as HTMLButtonElement; - expect(staleCancel).toBeDefined(); - - commit({ objectId: 1n }); - for (let attempt = 0; attempt < 20 && !transferTarget.textContent?.includes("Removing temporary"); attempt++) { - await Promise.resolve(); - await tick(); - } - const job = jobRegistry.active; - expect(job?.phase).toBe("finalizing"); - expect(transferTarget.textContent).toContain("Removing temporary map data"); - expect(transferTarget.textContent).not.toContain("Cancel"); - - // Exercise both stale UI cancellation and the surface's onDestroy cancellation after the - // durable commit. Neither may reach DownloadStep's detached abort listener. - staleCancel.click(); - await unmount(mapSend); - expect(job?.running).toBe(true); - releaseCleanup(); - for (let attempt = 0; attempt < 20 && job?.running; attempt++) { - await Promise.resolve(); - await tick(); - } - - expect(success).toEqual({ objectId: 1n }); - expect(failure).toBeNull(); - expect(job?.phase).toBe("done"); - expect(seams.discardMapOutput).toHaveBeenCalledOnce(); - expect(built.target.textContent).toContain("Assembled and sent"); - expect(built.target.textContent).not.toContain("Cancelled"); - expect(built.target.textContent).not.toContain("Nothing was saved"); - await unmount(built.component); - }); - - it("finishes committed cleanup before terminating the worker after its step unmounts", async () => { - let releaseCleanup!: () => void; - seams.discardMapOutput.mockImplementationOnce( - () => new Promise((resolve) => (releaseCleanup = () => resolve(undefined))), - ); - seams.sendMapBlob.mockResolvedValue({ objectId: 1n }); - const built = await mountReadyStep(); - const job = new DeviceJob("map"); - const running = job.run( - (ctx) => built.component.sendToDevice({} as FlatStoreClient, ctx), - () => "sent", - ); - for (let attempt = 0; attempt < 20 && !built.target.textContent?.includes("finishing up"); attempt++) { - await Promise.resolve(); - await tick(); - } - expect(job.phase).toBe("finalizing"); - - await unmount(built.component); - expect(job.running).toBe(true); - expect(seams.workerTerminate).toBe(0); - releaseCleanup(); - await running; - - expect(job.phase).toBe("done"); - expect(seams.discardMapOutput).toHaveBeenCalledOnce(); - expect(seams.workerTerminate).toBe(1); - }); - - /** Operation held, how to hold it, and the stale-store cleanups run 1 leaves behind. */ - const unabortableOperations: Array<[ - string, - (gate: () => Promise, open: () => Promise) => void, - number, - ]> = [ - ["destructive clear", (gate) => seams.clearCellStores.mockImplementationOnce(gate), 0], - [ - "store open and its stale cleanup", - (gate, open) => seams.openCellStore.mockImplementationOnce(async () => { - await gate(); - return open(); - }), - 1, - ], - [ - "cell write and its cleanup", - (gate, open) => seams.openCellStore.mockImplementationOnce(async () => { - const cells = await open(); - cells.put.mockImplementationOnce(gate); - return cells; - }), - 1, - ], - ]; - - it.each(unabortableOperations)("keeps run 2 blocked until a cancelled %s has settled", async (_held, hold, staleCleanups) => { - const built = await mountReadyStep(); - seams.cellStoreWritable.mockResolvedValue(true); - seams.hasRoomFor.mockResolvedValue(true); - seams.plan = { - items: [{ band: "fine", cell: { id: "cell-1", sha256: "digest", bytes: 4 } }], - totalBytes: 4, - knownEmpty: [], - }; - const opened: TestCellStore[] = []; - const open = async () => { - const cells = testCellStore(); - opened.push(cells); - return cells; - }; - seams.openCellStore.mockImplementation(open); - seams.discardCellStore.mockImplementation(async () => { - const live = opened.at(-1); - if (live) live.alive = false; - }); - let cellBytes = Uint8Array.of(1, 2, 3, 4); - // As with several download slots, an abort can settle the download while a cell write is in flight. - seams.downloadCells.mockImplementation((plan, options) => new Promise((resolve, reject) => { - options.signal.addEventListener("abort", () => reject(options.signal.reason), { once: true }); - Promise.resolve(options.onCell((plan as typeof seams.plan).items[0], cellBytes)).then(() => resolve(), reject); - })); - let release!: () => void; - hold(() => new Promise((resolve) => (release = () => resolve(undefined))), open); - const first = new DeviceJob("map"); - const cancelled = first.run( - (ctx) => built.component.sendToDevice({} as FlatStoreClient, ctx), - () => "unreachable", - ); - for (let attempt = 0; attempt < 20 && typeof release !== "function"; attempt++) { - await Promise.resolve(); - await tick(); - } - expect(release).toBeDefined(); - - first.cancel(); - // Let every part of the cancellation that does not wait for the held operation finish. - await new Promise((resolve) => setTimeout(resolve, 10)); - await expectSecondRunRefused(built.component); - expect(first.running).toBe(true); - expect(built.target.textContent).not.toContain("Cancelled"); - release(); - await cancelled; - expect(first.phase).toBe("idle"); - - cellBytes = Uint8Array.of(5, 6, 7, 8); - await waitForReady(built.target); - let commit!: (result: { objectId: bigint }) => void; - seams.sendMapBlob.mockImplementationOnce(() => new Promise((resolve) => (commit = resolve))); - const second = new DeviceJob("map"); - const survived = second.run( - (ctx) => built.component.sendToDevice({} as FlatStoreClient, ctx), - () => "second survived", - ); - for (let attempt = 0; attempt < 20 && typeof commit !== "function"; attempt++) { - await Promise.resolve(); - await tick(); - } - const secondStore = opened.at(-1)!; - expect(secondStore.alive).toBe(true); - expect(secondStore.put).toHaveBeenCalledWith("digest", Uint8Array.of(5, 6, 7, 8)); - expect(opened.slice(0, -1).every((cells) => !cells.alive)).toBe(true); - expect(seams.discardCellStore).toHaveBeenCalledTimes(staleCleanups); - commit({ objectId: 2n }); - await expect(survived).resolves.toMatchObject({ objectId: 2n }); - expect(second.result).toBe("second survived"); - await unmount(built.component); - }); - - it("keeps a remount and its run behind an unmounted component's deferred cell write", async () => { - const firstBuilt = await mountReadyStep(); - seams.cellStoreWritable.mockResolvedValue(true); - seams.hasRoomFor.mockResolvedValue(true); - seams.plan = { - items: [{ band: "fine", cell: { id: "cell-1", sha256: "digest", bytes: 4 } }], - totalBytes: 4, - knownEmpty: [], - }; - let current: ReturnType | null = null; - seams.discardCellStore.mockImplementation(async () => { - if (current) current.alive = false; - }); - const firstStore = testCellStore(); - let releasePut!: () => void; - firstStore.put.mockImplementationOnce( - () => new Promise((resolve) => (releasePut = () => resolve(undefined))), - ); - seams.openCellStore.mockImplementation(async () => { - current = firstStore; - return firstStore; - }); - seams.downloadCells.mockImplementationOnce(async (plan, options) => { - const item = (plan as typeof seams.plan).items[0]; - await options.onCell(item, Uint8Array.of(1, 2, 3, 4)); - }); - const first = new DeviceJob("map"); - const cancelled = first.run( - (ctx) => firstBuilt.component.sendToDevice({} as FlatStoreClient, ctx), - () => "unreachable", - ); - for (let attempt = 0; attempt < 20 && typeof releasePut !== "function"; attempt++) { - await Promise.resolve(); - await tick(); - } - - await unmount(firstBuilt.component); - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); - const secondBuilt = await mountReadyStep(); - await expectSecondRunRefused(secondBuilt.component); - expect(first.running).toBe(true); - expect(seams.clearMapWorkStorage).toHaveBeenCalledOnce(); - - releasePut(); - await cancelled; - expect(firstStore.alive).toBe(false); - for (let attempt = 0; attempt < 20 && seams.clearMapWorkStorage.mock.calls.length < 2; attempt++) { - await Promise.resolve(); - await tick(); - } - expect(seams.clearMapWorkStorage).toHaveBeenCalledTimes(2); - - const secondStore = testCellStore(); - seams.openCellStore.mockImplementation(async () => { - current = secondStore; - return secondStore; - }); - seams.downloadCells.mockImplementationOnce(async (plan, options) => { - const item = (plan as typeof seams.plan).items[0]; - await options.onCell(item, Uint8Array.of(5, 6, 7, 8)); - }); - await waitForReady(secondBuilt.target); - let commit!: (result: { objectId: bigint }) => void; - seams.sendMapBlob.mockImplementationOnce(() => new Promise((resolve) => (commit = resolve))); - const second = new DeviceJob("map"); - const survived = second.run( - (ctx) => secondBuilt.component.sendToDevice({} as FlatStoreClient, ctx), - () => "second survived", - ); - for (let attempt = 0; attempt < 20 && typeof commit !== "function"; attempt++) { - await Promise.resolve(); - await tick(); - } - expect(secondStore.alive).toBe(true); - expect(secondStore.put).toHaveBeenCalledWith("digest", Uint8Array.of(5, 6, 7, 8)); - commit({ objectId: 2n }); - await expect(survived).resolves.toMatchObject({ objectId: 2n }); - await unmount(secondBuilt.component); - }); - - it("keeps map actions disabled until destructive mount maintenance finishes", async () => { - let releaseMountClear!: () => void; - seams.clearMapWorkStorage.mockImplementationOnce( - () => new Promise((resolve) => (releaseMountClear = () => resolve(undefined))), - ); - const target = document.createElement("div"); - document.body.append(target); - const component = mount(DownloadStep, { target, props: { store: store as never } }); - await tick(); - vi.advanceTimersByTime(500); - await Promise.resolve(); - await tick(); - vi.useRealTimers(); - for (let attempt = 0; attempt < 20 && typeof releaseMountClear !== "function"; attempt++) { - await Promise.resolve(); - await tick(); - } - - const button = [...target.querySelectorAll("button")].find((candidate) => candidate.textContent === "Download map"); - expect(button).toBeDefined(); - expect((button as HTMLButtonElement).disabled).toBe(true); - await expectSecondRunRefused(component); - expect(seams.workerAssemble).toBe(0); - - releaseMountClear(); - await waitForReady(target); - seams.sendMapBlob.mockResolvedValueOnce({ objectId: 3n }); - const run = new DeviceJob("map"); - await expect( - run.run( - (ctx) => component.sendToDevice({} as FlatStoreClient, ctx), - () => "started after maintenance", - ), - ).resolves.toMatchObject({ objectId: 3n }); - expect(run.result).toBe("started after maintenance"); - await unmount(component); - }); - - /** A stray message is droppable; the run's only ending is not. Dropping a `done` the guard - * rejects would leave the screen waiting for a message that has already been sent. */ - it("fails the run when the finished result is one this build cannot read", async () => { - seams.unreadableDone = true; - const { component, target } = await mountReadyStep(); - - (target.querySelector("button.primary") as HTMLButtonElement).click(); - for (let attempt = 0; attempt < 40 && !target.textContent?.includes("Nothing was saved"); attempt++) { - await new Promise((resolve) => setTimeout(resolve, 10)); - await tick(); - } - - expect(target.textContent).toContain("Nothing was saved"); - expect(seams.saveBlob).not.toHaveBeenCalled(); - await unmount(component); - }); - - it("reports an assembly failure and reopens Download map", async () => { - seams.workerError = "the scratch handle was closed"; - const { component, target } = await mountReadyStep(); - (target.querySelector("button.primary") as HTMLButtonElement).click(); - for (let attempt = 0; attempt < 40 && !target.textContent?.includes("Nothing was saved"); attempt++) { - await new Promise((resolve) => setTimeout(resolve, 10)); - await tick(); - } - expect(target.textContent).toContain("Nothing was saved: the scratch handle was closed"); - expect(seams.saveBlob).not.toHaveBeenCalled(); - await waitForReady(target); - await unmount(component); - }); - - it("keeps the ordinary download path and does not delete its source early", async () => { - seams.workerOutput = "file"; - const { component, target } = await mountReadyStep(); - - (target.querySelector("button.primary") as HTMLButtonElement).click(); - for (let attempt = 0; attempt < 20 && !target.textContent?.includes("Downloaded OBC map.obcm"); attempt++) { - await Promise.resolve(); - await tick(); - } - - expect(target.textContent).toContain("Downloaded OBC map.obcm"); - expect(seams.saveBlob).toHaveBeenCalledOnce(); - const [blob, name] = seams.saveBlob.mock.calls[0] as [Blob, string]; - expect(blob.size).toBe(4); - expect(name).toBe("OBC map.obcm"); - expect(seams.discardMapOutput).not.toHaveBeenCalled(); - await unmount(component); - }); -}); - -const ledger = { - totalBytes: 4, - cellCount: 1, - core: { bytes: 4 }, - terrain: null, - isFinal: true, -}; -const store = { - ledger, - resolution: { cellsByBand: new Map(), parts: [] }, - indices: new Map(), - catalog: { - schema: { - name: "Test schema", - bands: [{ id: "fine", lods: [16], role: "fine", cell_log2: 18 }], - }, - }, - terrain: null, - client: { fetchImpl: globalThis.fetch }, - selection: { parts: [] }, - lightSkin: { name: "Default" }, - darkSkin: { name: "Dusk" }, - rootBody: "{}", - holeCells: () => [], -}; - -async function mountReadyStep( - props: { onSendReadyChange?: (ready: boolean) => void; store?: typeof store } = {}, -) { - const target = document.createElement("div"); - document.body.append(target); - const component = mount(DownloadStep, { target, props: { ...props, store: (props.store ?? store) as never } }); - await tick(); - for (let attempt = 0; attempt < 10 && target.textContent?.includes("Deleting…"); attempt++) { - await Promise.resolve(); - await tick(); - } - vi.advanceTimersByTime(500); - for (let attempt = 0; attempt < 10; attempt++) { - await Promise.resolve(); - await tick(); - } - vi.useRealTimers(); - return { component, target }; -} - -function testCellStore(): TestCellStore { - return { - revision: "test-revision", - alive: true, - has: vi.fn(async (_key: string, _bytes: number) => false), - put: vi.fn(async (_key: string, _bytes: Uint8Array) => undefined), - }; -} - -async function expectSecondRunRefused(component: { sendToDevice: SendAssembledMap }) { - const second = new DeviceJob("map"); - await expect( - second.run( - (ctx) => component.sendToDevice({} as FlatStoreClient, ctx), - () => "must stay blocked", - ), - ).resolves.toBeNull(); - expect(second.error).toContain("not ready"); -} - -async function waitForReady(target: HTMLElement) { - for (let attempt = 0; attempt < 40; attempt++) { - const button = [...target.querySelectorAll("button")].find((candidate) => candidate.textContent === "Download map"); - if (button && !(button as HTMLButtonElement).disabled) return; - await new Promise((resolve) => setTimeout(resolve, 20)); - await tick(); - } - throw new Error("the map builder did not become ready for the next run"); -} diff --git a/builder/web/src/components/coverage/MapSummary.svelte b/builder/web/src/components/coverage/MapSummary.svelte deleted file mode 100644 index 429418adfa..0000000000 --- a/builder/web/src/components/coverage/MapSummary.svelte +++ /dev/null @@ -1,152 +0,0 @@ - - -
-

Map summary

- - {#if store.indexError} -

- Couldn't load map coverage: {store.indexError} - -

- {:else if store.resolutionError} -

This selection can't be built: {store.resolutionError}

- {:else if !ledger} -

Loading map coverage…

- {:else if !hasParts} -

Choose coverage on the map.

- {:else} - {#if ledger.isFinal} -

- {formatBytes(ledger.totalBytes)} estimated total -

- {:else} -

Calculating…

- {/if} - - {#if holeCount > 0} - - {/if} - {#if partialHatchCount > 0} - - {:else if hasDrawnPartialCoverage} -

- Street detail may be incomplete at the edge of the available map data. - Choose a listed region for its published coverage. -

- {/if} - - {#if ledger.terrain} - {#if ledger.terrain.missingCount > 0} -

- Elevation data is missing in some selected areas. Climbs there read as flat. -

- {/if} -

{ledger.terrain.attribution}

- {#each ledger.terrain.references as reference (reference.key)} -

- Summit heights from {reference.product}: {reference.attribution} ({reference.licence}) -

- {/each} - {/if} - - {#if store.catalog.source} -

- {store.catalog.source.attribution} · {store.catalog.source.license} -

- {/if} - -

- Downloads as one map file. Card space is checked before sending. -

- {/if} -
- - diff --git a/builder/web/src/components/coverage/MapSummary.svelte.test.ts b/builder/web/src/components/coverage/MapSummary.svelte.test.ts deleted file mode 100644 index 009fbcb328..0000000000 --- a/builder/web/src/components/coverage/MapSummary.svelte.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -// @vitest-environment happy-dom - -import { mount, tick, unmount } from "svelte"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import type { CoverageStore } from "../../lib/coverage/store.svelte"; -import MapSummary from "./MapSummary.svelte"; - -afterEach(() => document.body.replaceChildren()); - -describe("MapSummary", () => { - it("shows all coverage gaps and both data credits before a build", async () => { - const store = { - selection: { parts: [{ id: "area" }] }, - ledger: { - isFinal: true, - totalBytes: 4_096, - cellCount: 3, - terrain: { - bytes: 1_024, - missingCount: 2, - attribution: "Terrain source credit", - references: [], - }, - }, - catalog: { - source: { - attribution: "Map source credit", - license: "Map licence", - license_url: "https://example.org/licence", - }, - }, - holeCells: () => ["hole-1", "hole-2"], - partialDetailCells: () => ["partial-1"], - partialHatchCells: () => ["partial-1"], - focusWarnings: vi.fn(), - } as unknown as CoverageStore; - const target = document.createElement("div"); - document.body.append(target); - const component = mount(MapSummary, { target, props: { store } }); - await tick(); - const content = (element: Element) => element.textContent?.replace(/\s+/g, " ").trim(); - - expect(content(target.querySelector(".total")!)).toContain("4.0 KB estimated total"); - expect([...target.querySelectorAll(".warnline")].map(content)).toEqual([ - expect.stringContaining("Map data is missing in some selected areas"), - expect.stringContaining("Street detail may stop near these gaps"), - ]); - expect(content(target.querySelector(".terrain")!)).toContain("Elevation data is missing in some selected areas"); - expect([...target.querySelectorAll(".attribution")].map(content)).toEqual([ - "Terrain source credit", - expect.stringContaining("Map source credit"), - ]); - expect(content(target.querySelector(".fit")!)).toContain("one map file"); - const warnings = target.querySelectorAll("button.warnline"); - warnings[0].click(); - warnings[1].click(); - expect(store.focusWarnings).toHaveBeenNthCalledWith(1, "hole"); - expect(store.focusWarnings).toHaveBeenNthCalledWith(2, "partial"); - expect(target.textContent).not.toContain("1.0 KB"); - await unmount(component); - }); - - it.each([ - { label: "a region border", kind: "region", drawnCells: ["border"], warns: false }, - { 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 }; - const store = { - selection: { parts: [region, drawn] }, - resolution: { - parts: [ - { part: region, cellsByBand: new Map([["fine", ["full", "border"]]]) }, - { part: drawn, cellsByBand: new Map([["fine", drawnCells]]) }, - ], - }, - ledger: { isFinal: true, totalBytes: 4_096, cellCount: 3, terrain: null }, - catalog: { - schema: { bands: [{ id: "fine", role: "fine", lods: [0], cell_log2: 18 }] }, - }, - holeCells: () => [], - partialDetailCells: () => ["border"], - partialHatchCells: () => [], - } as unknown as CoverageStore; - const target = document.createElement("div"); - document.body.append(target); - const component = mount(MapSummary, { target, props: { store } }); - await tick(); - expect(target.querySelectorAll(".warnline")).toHaveLength(warns ? 1 : 0); - if (warns) expect(target.textContent).toContain("Street detail may be incomplete"); - expect(target.querySelector(".total")?.textContent).toContain("4.0 KB"); - await unmount(component); - }); -}); diff --git a/builder/web/src/components/coverage/PartsList.svelte b/builder/web/src/components/coverage/PartsList.svelte deleted file mode 100644 index e0507e97a8..0000000000 --- a/builder/web/src/components/coverage/PartsList.svelte +++ /dev/null @@ -1,118 +0,0 @@ - - -{#if parts.length === 0} -

Choose a region or draw an area on the map.

-{:else} -
    - {#each parts as part (part.id)} - {@const resolved = store.resolution?.parts.find((p) => p.part.id === part.id)} - {@const regionError = - part.kind === "region" ? (store.regionErrors.get(part.regionId) ?? null) : null} -
  • (store.highlightPartId = part.id)} - onmouseleave={() => { - if (store.highlightPartId === part.id) store.highlightPartId = null; - }} - > - - {part.name} - {#if regionError} - {regionError} - {#if part.kind === "region" && store.region(part.regionId)} - - {/if} - {:else if !store.indices || resolved?.pending} - Calculating… - {/if} - -
  • - {/each} -
-{/if} - - diff --git a/builder/web/src/components/device/CardFormat.svelte b/builder/web/src/components/device/CardFormat.svelte deleted file mode 100644 index 665000ba4c..0000000000 --- a/builder/web/src/components/device/CardFormat.svelte +++ /dev/null @@ -1,85 +0,0 @@ - - - -
-

Card

- {#if storeId === null} -

This card is not initialized as an OpenBikeComputer flat store.

-

Format it here, reconnect after the restart, then send a map.

- {:else} -

Erase and initialize the card again if you want a completely clean device.

- {/if} - - - - {#if error}{/if} -
- - diff --git a/builder/web/src/components/device/DeviceStep.svelte b/builder/web/src/components/device/DeviceStep.svelte deleted file mode 100644 index 7ba51bf6f2..0000000000 --- a/builder/web/src/components/device/DeviceStep.svelte +++ /dev/null @@ -1,156 +0,0 @@ - - - -{#if 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} -

- -
- - {#await loadSurfaces()} -

Loading…

- {:then { default: Surfaces }} - - {:catch} - - {/await} -{:else if session.status === "connecting"} -

Connecting…

-{:else} - {#if deviceHolder.interrupted} - - {/if} -
- -

Connect by USB, then choose your device.

-
- {#if session.status === "error" && session.error} - - {/if} -{/if} - - diff --git a/builder/web/src/components/device/DeviceSurfaces.svelte b/builder/web/src/components/device/DeviceSurfaces.svelte deleted file mode 100644 index f2180a10e5..0000000000 --- a/builder/web/src/components/device/DeviceSurfaces.svelte +++ /dev/null @@ -1,56 +0,0 @@ - - - -{#if store} - - - - -{/if} - diff --git a/builder/web/src/components/device/FirmwareCard.svelte b/builder/web/src/components/device/FirmwareCard.svelte deleted file mode 100644 index a28a2574e8..0000000000 --- a/builder/web/src/components/device/FirmwareCard.svelte +++ /dev/null @@ -1,254 +0,0 @@ - - - - -
-

Firmware

- -

- Running - {running ?? "unknown"} -

- - {#if status === "available" && release} -

{release.version} is available.

- {:else if status === "current"} -

Up to date.

- {:else if status === "ahead" && release} -

This device is newer than the published {release.version}.

- {:else if status === "unknown" && running} - -

Development build — automatic updates are paused.

- {:else if status === "unknown"} -

This device has not reported a firmware version yet.

- {:else if checkFailed} -

Couldn't check for updates.

- {:else} -

No published update to compare against.

- {/if} - -
- {#if status === "available" && release} - - {/if} - - -
- - - - {#if staged && !armed} -
- -

The image is on the card either way; this is what makes it the one that boots.

-
- {/if} - - {#if armed && staged} -

- {staged.version} is armed. The device reboots and installs it on its own — keep it powered. -

- {/if} - - {#if armError} - - {/if} -
- - diff --git a/builder/web/src/components/device/MapSend.svelte b/builder/web/src/components/device/MapSend.svelte deleted file mode 100644 index abe7dec433..0000000000 --- a/builder/web/src/components/device/MapSend.svelte +++ /dev/null @@ -1,127 +0,0 @@ - - - -
-

Map

- -
- {#if ledger && sendAssembled} - {@const send = sendAssembled} - - {/if} - - -
- - {#if !job.running} -

- This replaces the active map. The replaced map cannot be recovered. A regional map is hundreds of megabytes — expect minutes, and keep the cable in. -

- {/if} - - -
- - diff --git a/builder/web/src/components/device/MapSend.svelte.test.ts b/builder/web/src/components/device/MapSend.svelte.test.ts deleted file mode 100644 index 5b70fb7319..0000000000 --- a/builder/web/src/components/device/MapSend.svelte.test.ts +++ /dev/null @@ -1,134 +0,0 @@ -// @vitest-environment happy-dom - -import { mount, tick, unmount } from "svelte"; -import { afterEach, describe, expect, it } from "vitest"; -import type { Ledger } from "../../lib/catalog/ledger"; -import { jobRegistry } from "../../lib/device/job.svelte"; -import type { JobContext } from "../../lib/device/progress"; -import { deviceHolder } from "../../lib/device/session.svelte"; -import type { SendAssembledMap } from "../../lib/device/write"; -import { DeviceError, type FlatStoreClient } from "../../lib/usb/client"; -import MapSend from "./MapSend.svelte"; - -const ledger = { isFinal: true } as Ledger; -const client = {} as FlatStoreClient; - -afterEach(() => { - deviceHolder.interrupted = null; - document.body.replaceChildren(); -}); - -describe("MapSend lifecycle", () => { - it("warns before either send path can replace the active map", async () => { - const target = document.createElement("div"); - document.body.append(target); - const send: SendAssembledMap = async () => { - throw new Error("must not run"); - }; - const component = mount(MapSend, { - target, - props: { client, ledger, sendAssembled: send, sendReady: true }, - }); - await tick(); - - expect(target.querySelectorAll(".actions button")).toHaveLength(2); - expect(target.querySelector(".hint")?.textContent).toContain("replaces the active map"); - expect(target.querySelector(".hint")?.textContent).toContain("cannot be recovered"); - await unmount(component); - }); - - it("shows the card's no-space refusal, then retries from the same controls", async () => { - const target = document.createElement("div"); - document.body.append(target); - let attempts = 0; - const send: SendAssembledMap = async () => { - if (++attempts === 1) throw new DeviceError("no-space", "The card needs 262144 B for this map."); - return { objectId: 7n, revision: 2n, payloadLength: 4n, payloadCrc32: 0 }; - }; - const component = mount(MapSend, { - target, - props: { client, ledger, sendAssembled: send, sendReady: true }, - }); - await tick(); - (target.querySelector("button.primary") as HTMLButtonElement).click(); - await tick(); - await tick(); - - expect(target.querySelector('[role="alert"]')?.textContent).toContain("262144 B"); - (target.querySelector("button.primary") as HTMLButtonElement).click(); - await tick(); - await tick(); - expect(attempts).toBe(2); - expect(target.querySelector(".done")?.textContent).toContain("map 7"); - await unmount(component); - }); - - it("cancels the owned job when disconnect unmounts the surface", async () => { - let context: JobContext | null = null; - const send: SendAssembledMap = (_client, ctx) => { - context = ctx; - return new Promise((_resolve, reject) => { - ctx.signal.addEventListener("abort", () => reject(ctx.signal.reason), { once: true }); - }); - }; - const target = document.createElement("div"); - document.body.append(target); - const component = mount(MapSend, { - target, - props: { client, ledger, sendAssembled: send, sendReady: true }, - }); - - const button = target.querySelector("button.primary") as HTMLButtonElement; - button.click(); - await tick(); - expect(context).not.toBeNull(); - expect(jobRegistry.active?.label).toBe("map"); - - await unmount(component); - await Promise.resolve(); - await tick(); - - expect(context!.signal.aborted).toBe(true); - expect(jobRegistry.active).toBeNull(); - }); - - it("keeps direct send disabled until the assembler's complete preflight is ready", async () => { - const target = document.createElement("div"); - document.body.append(target); - const send: SendAssembledMap = async () => { - throw new Error("must not run"); - }; - const component = mount(MapSend, { - target, - props: { client, ledger, sendAssembled: send, sendReady: false }, - }); - await tick(); - - expect((target.querySelector("button.primary") as HTMLButtonElement).disabled).toBe(true); - await unmount(component); - }); - - it("keeps a physical link failure when disconnect unmount also cancels the job", async () => { - let rejectSend: ((cause: unknown) => void) | null = null; - const send: SendAssembledMap = () => - new Promise((_resolve, reject) => { - rejectSend = reject; - }); - const target = document.createElement("div"); - document.body.append(target); - const component = mount(MapSend, { - target, - props: { client, ledger, sendAssembled: send, sendReady: true }, - }); - (target.querySelector("button.primary") as HTMLButtonElement).click(); - await tick(); - - rejectSend!(new DeviceError("link", "the USB cable disconnected")); - await unmount(component); - await Promise.resolve(); - await tick(); - - expect(deviceHolder.interrupted).toContain("plug it back in"); - expect(jobRegistry.active).toBeNull(); - }); -}); diff --git a/builder/web/src/components/device/RideExport.svelte b/builder/web/src/components/device/RideExport.svelte deleted file mode 100644 index bca13b876a..0000000000 --- a/builder/web/src/components/device/RideExport.svelte +++ /dev/null @@ -1,198 +0,0 @@ - - - -
-

Rides

- - {#if listError} - - - {:else if loading} -

Reading the device's rides…

- {:else if entries.length === 0} -

No rides recorded on this device yet.

- {:else} -
    - {#each entries as entry (entry.objectId)} -
  • -
    -

    - {entry.displayName || `Ride ${entry.objectId}`} - {#if exported.has(rideKey(scope, entry.objectId))} - exported - {/if} -

    -

    {formatBytes(Number(entry.payloadLength))}

    -
    - -
  • - {/each} -
- -

- An export is not a backup — the device is not told anything, and the file you save is the - only copy. -

- {/if} - - -
- - diff --git a/builder/web/src/components/device/RouteDrop.svelte b/builder/web/src/components/device/RouteDrop.svelte deleted file mode 100644 index 24db7567aa..0000000000 --- a/builder/web/src/components/device/RouteDrop.svelte +++ /dev/null @@ -1,345 +0,0 @@ - - - -{#snippet tile()} -
{ - e.preventDefault(); - dragging = true; - // The wasm module is ~95 KB and loads on demand; starting it on hover turns the - // conversion into a plain function call by the time the file lands. - void initConvert(); - }} - ondragleave={() => (dragging = false)} - ondrop={onDrop} -> - {#if route} -
-

{route.header.name}

-

{summary}

-
- - -
-
- {:else} - -

{empty ? "No routes on the device yet — drop a GPX here" : "Drop GPX here"}

-

- or click to choose{#if onmultiple} · several files become a trip{/if} -

- {/if} - - - - {#if readError} - - {/if} - - - - -
-{/snippet} - -{#if heading !== null} -
-

{heading}

- {@render tile()} -
-{:else} - {@render tile()} -{/if} - - diff --git a/builder/web/src/components/device/TransferBar.svelte b/builder/web/src/components/device/TransferBar.svelte deleted file mode 100644 index 80363aaa62..0000000000 --- a/builder/web/src/components/device/TransferBar.svelte +++ /dev/null @@ -1,101 +0,0 @@ - - - -{#if job.running} -
-
-
- {heading} - - {formatBytes(job.done)}{job.total ? ` of ${formatBytes(job.total)}` : ""}{job.rate - ? ` · ${formatRate(job.rate)}` - : ""}{eta ? ` · about ${formatDuration(eta)} left` : ""} - - {#if job.phase !== "finalizing"} - - {/if} -
-
-{/if} - -{#if job.phase === "error" && job.error} - -{/if} - -{#if job.phase === "done" && job.result} -

{job.result}

-{/if} - - diff --git a/builder/web/src/components/device/TransferBar.svelte.test.ts b/builder/web/src/components/device/TransferBar.svelte.test.ts deleted file mode 100644 index 89ad867433..0000000000 --- a/builder/web/src/components/device/TransferBar.svelte.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -// @vitest-environment happy-dom - -import { mount, tick, unmount } from "svelte"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import { DeviceJob } from "../../lib/device/job.svelte"; -import type { JobContext } from "../../lib/device/progress"; -import TransferBar from "./TransferBar.svelte"; - -afterEach(() => { - vi.useRealTimers(); - document.body.replaceChildren(); -}); - -describe("TransferBar", () => { - it("shows transferred bytes, total bytes, and a measured upload rate", async () => { - vi.useFakeTimers({ toFake: ["Date"] }); - const target = document.createElement("div"); - document.body.append(target); - const job = new DeviceJob("map"); - let context!: JobContext; - let finish!: () => void; - const running = job.run(async (ctx) => { - context = ctx; - ctx.phase("sending", 2_000); - return new Promise((resolve) => { finish = resolve; }); - }, () => "sent"); - const component = mount(TransferBar, { target, props: { job } }); - context.progress(0, 2_000); - vi.setSystemTime(Date.now() + 1_500); - context.progress(1_500, 2_000); - await tick(); - - expect(target.querySelector(".line")?.textContent).toContain("1.5 KB of 2.0 KB"); - expect(target.querySelector(".line")?.textContent).toContain("1000 B/s"); - expect(target.querySelector(".fill")?.getAttribute("style")).toContain("75%"); - - context.phase("finalizing"); - await tick(); - expect(target.textContent).toContain("Removing temporary map data"); - expect(target.querySelector("button")).toBeNull(); - finish(); - await running; - await unmount(component); - }); -}); diff --git a/builder/web/src/lib/api/client.ts b/builder/web/src/lib/api/client.ts deleted file mode 100644 index 3d8cdf0b96..0000000000 --- a/builder/web/src/lib/api/client.ts +++ /dev/null @@ -1,77 +0,0 @@ -// The dev host's transport: HTTP against `python -m builder.server`. Only -// platform/dev.ts imports it, so it never reaches the other two bundles. - -import type { Palette, SchemaPreviewMap, SchemaPreviewStatus } from "../platform/types"; -import type { Preset, SchemaEnvelope } from "../config/model"; - -// Every fetch goes through API_BASE so a deployment can relocate the API with -// a build-time env var (VITE_API_BASE) instead of code changes. -export const API_BASE: string = import.meta.env.VITE_API_BASE ?? "/api"; - -async function getJson(path: string): Promise { - const res = await fetch(API_BASE + path); - if (!res.ok) { - let detail = res.statusText; - try { - detail = (await res.json()).detail ?? detail; - } catch { - // non-JSON error body; keep statusText - } - throw new Error(detail); - } - return res.json() as Promise; -} - -async function errorDetail(res: Response): Promise { - try { - const body = (await res.json()) as { detail?: unknown }; - if (typeof body.detail === "string") return body.detail; - } catch { - // Keep the HTTP status below for a non-JSON failure. - } - return `${res.status} ${res.statusText}`; -} - -export const api = { - presets: () => getJson("/presets"), - schema: () => getJson("/schema"), - palette: () => getJson("/palette"), - async publishedCatalog(refresh = false): Promise<{ url: string; body: string }> { - const res = await fetch(`${API_BASE}/catalog/root`, refresh ? { cache: "no-cache" } : undefined); - if (!res.ok) throw new Error(await errorDetail(res)); - const url = res.headers.get("X-OBC-Catalog-Url"); - if (!url) throw new Error("The maintainer host omitted the catalog URL."); - return { url, body: await res.text() }; - }, - - async catalogFetch(input: RequestInfo | URL, init?: RequestInit): Promise { - const url = input instanceof Request ? input.url : String(input); - return fetch(`${API_BASE}/catalog/object?url=${encodeURIComponent(url)}`, init); - }, - previewStatus: () => getJson("/schema-preview/status"), - - async packPreview(config: Record, signal: AbortSignal): Promise { - const res = await fetch(`${API_BASE}/schema-preview`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(config), - signal, - }); - if (!res.ok) throw new Error(await errorDetail(res)); - let diagnostics: string[] = []; - const encoded = res.headers.get("X-OBC-Pack-Diagnostics"); - if (encoded) { - try { - const parsed: unknown = JSON.parse(atob(encoded.replaceAll("-", "+").replaceAll("_", "/"))); - if (Array.isArray(parsed) && parsed.every((line) => typeof line === "string")) diagnostics = parsed; - } catch { - // Diagnostics are advisory; never reject a valid map for a bad header. - } - } - return { - bytes: new Uint8Array(await res.arrayBuffer()), - packDurationMs: Number(res.headers.get("X-OBC-Pack-Duration-Ms") ?? 0), - diagnostics, - }; - }, -}; diff --git a/builder/web/src/lib/config/edit.test.ts b/builder/web/src/lib/config/edit.test.ts deleted file mode 100644 index 1c5ebd757a..0000000000 --- a/builder/web/src/lib/config/edit.test.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { addLodTier, autoSimplify, editLodTier, exportFile, importFile, newStyleDef, removeCategory, removeLodTier, reorderCategory } from "./edit"; -import type { PackConfig } from "./model"; -import { WORKING_SCHEMA_VERSION, type WorkingEnvelope } from "./storage.svelte"; - -function config(): PackConfig { - return { - lods: [ - { max_mpp: null, simplify: 120 }, - { max_mpp: 120, simplify: 18 }, - { max_mpp: 18, simplify: 0 }, - ], - features: { - highway: { - motorway: { color: "0xFAA0", min_lod: 0 }, - track: { color: "0xAAA0", min_lod: 2 }, - path: { color: "0xAAA0", min_lod: 1 }, - }, - natural: { land: { color: "0xFFFF", min_lod: 0 } }, - }, - marker: { color: "0xF800" }, - }; -} - -describe("LOD tier edits", () => { - it("autoSimplify is the next tier's ceiling, 0 for the finest", () => { - const cfg = config(); - expect(autoSimplify(cfg, 0)).toBe(120); - expect(autoSimplify(cfg, 1)).toBe(18); - expect(autoSimplify(cfg, 2)).toBe(0); - }); - - it("adds a finer tier at half the previous ceiling", () => { - const cfg = config(); - addLodTier(cfg); - expect(cfg.lods[3]).toEqual({ max_mpp: 9, simplify: 0 }); - // The old finest tier picks up the pixel-accurate default. - expect(cfg.lods[2].simplify).toBe(9); - }); - - it("keeps a hand-set simplify on the old finest tier when adding", () => { - const cfg = config(); - cfg.lods[2].simplify = 5; - addLodTier(cfg); - expect(cfg.lods[2].simplify).toBe(5); - }); - - it("a default simplify follows the next tier's ceiling edit", () => { - const cfg = config(); - editLodTier(cfg, 1, "max_mpp", 100); - expect(cfg.lods[0].simplify).toBe(100); // was 120 = default, tracks - editLodTier(cfg, 2, "max_mpp", 20); - expect(cfg.lods[1].simplify).toBe(20); // was 18 = default, tracks - }); - - it("a hand-set simplify does not follow ceiling edits", () => { - const cfg = config(); - editLodTier(cfg, 0, "simplify", 40); - editLodTier(cfg, 1, "max_mpp", 100); - expect(cfg.lods[0].simplify).toBe(40); - }); - - it("re-defaults a tracking simplify when the next tier is removed", () => { - const cfg = config(); - removeLodTier(cfg, 1); - expect(cfg.lods[0].simplify).toBe(18); // now tracks the old tier 2 - }); - - it("remaps min_lod on removal: above shifts down, at collapses", () => { - const cfg = config(); - removeLodTier(cfg, 1); - expect(cfg.lods.length).toBe(2); - expect(cfg.features.highway.motorway.min_lod).toBe(0); // below: unchanged - expect(cfg.features.highway.path.min_lod).toBe(1); // at k: collapses into new tier 1 - expect(cfg.features.highway.track.min_lod).toBe(1); // above: shifted down - }); - - it("pins the new coarsest tier to +inf when tier 0 is removed", () => { - const cfg = config(); - removeLodTier(cfg, 0); - expect(cfg.lods[0].max_mpp).toBeNull(); - }); - - it("never removes the last tier", () => { - const cfg = config(); - removeLodTier(cfg, 0); - removeLodTier(cfg, 0); - removeLodTier(cfg, 0); - expect(cfg.lods.length).toBe(1); - }); -}); - -describe("reorderCategory", () => { - it("rebuilds keys in the given order", () => { - const cfg = config(); - reorderCategory(cfg, "highway", ["path", "motorway", "track"]); - expect(Object.keys(cfg.features.highway)).toEqual(["path", "motorway", "track"]); - }); - - it("keeps entries the order list missed", () => { - const cfg = config(); - reorderCategory(cfg, "highway", ["track"]); - expect(Object.keys(cfg.features.highway)).toEqual(["track", "motorway", "path"]); - }); -}); - -describe("category/type edits", () => { - it("removeCategory returns the disabled-list keys", () => { - const cfg = config(); - const keys = removeCategory(cfg, "highway"); - expect(keys.sort()).toEqual(["highway/motorway", "highway/path", "highway/track"]); - expect(cfg.features.highway).toBeUndefined(); - }); - - it("new types default to the finest tier", () => { - const cfg = config(); - expect(newStyleDef(cfg).min_lod).toBe(2); - }); -}); - -describe("export / import round-trip", () => { - const env: WorkingEnvelope = { - schema_version: WORKING_SCHEMA_VERSION, - based_on: { id: "default", version: 1 }, - modified: true, - config: config(), - disabled: ["highway/track"], - }; - - it("export is a bare CLI-shaped config with _meta + disabled", () => { - const out = JSON.parse(exportFile(env)); - expect(out._meta.app).toBe("obcm-web-builder"); - expect(out._meta.based_on).toEqual({ id: "default", version: 1 }); - expect(Object.keys(out.features)).toEqual(["highway", "natural"]); - expect(out.disabled).toEqual(["highway/track"]); - }); - - it("round-trips through import with provenance and disabled intact", () => { - const back = importFile(exportFile(env)); - expect(back).not.toBeNull(); - expect(back!.based_on).toEqual({ id: "default", version: 1 }); - expect(back!.disabled).toEqual(["highway/track"]); - expect(back!.modified).toBe(true); - expect(Object.keys(back!.config.features.highway)).toEqual(["motorway", "track", "path"]); - }); - - it("imports a bare CLI config with disabled entries", () => { - const bare = JSON.stringify({ - lods: [{ max_mpp: null, simplify: 0 }], - features: { highway: { motorway: { color: "0xFAA0" } } }, - marker: { color: "0xF800" }, - disabled: ["highway/motorway"], - }); - const env2 = importFile(bare); - expect(env2).not.toBeNull(); - expect(env2!.based_on).toBeNull(); - expect(env2!.disabled).toEqual(["highway/motorway"]); - }); - - it("rejects non-config JSON", () => { - expect(importFile("42")).toBeNull(); - expect(importFile('{"hello": "world"}')).toBeNull(); - expect(importFile("not json")).toBeNull(); - }); - - it("rejects an internal storage envelope", () => { - expect(importFile(JSON.stringify(env))).toBeNull(); - }); - - it("rejects unsupported or malformed builder metadata", () => { - const exported = JSON.parse(exportFile(env)); - exported._meta.schema_version = 2; - expect(importFile(JSON.stringify(exported))).toBeNull(); - exported._meta.schema_version = WORKING_SCHEMA_VERSION; - exported._meta.based_on = { id: "default", version: -1 }; - expect(importFile(JSON.stringify(exported))).toBeNull(); - }); -}); diff --git a/builder/web/src/lib/config/edit.ts b/builder/web/src/lib/config/edit.ts deleted file mode 100644 index 6cad196ed9..0000000000 --- a/builder/web/src/lib/config/edit.ts +++ /dev/null @@ -1,154 +0,0 @@ -import { deepCopy, normalizeConfig, type PackConfig, type StyleDef } from "./model"; -import { WORKING_SCHEMA_VERSION, type WorkingEnvelope } from "./storage.svelte"; - -/** - * The pixel-accurate simplify default for tier `i`: one pixel at the finest - * scale the tier is drawn at, which is the next finer tier's ceiling. The - * finest tier keeps full detail (0). - */ -export function autoSimplify(config: PackConfig, i: number): number { - return config.lods[i + 1]?.max_mpp ?? 0; -} - -/** - * Set one tier field. A coarser neighbor whose simplify still sits at the - * pixel-accurate default follows a ceiling change; a hand-set value stays. - */ -export function editLodTier( - config: PackConfig, - i: number, - field: "max_mpp" | "simplify" | "min_area_px" | "min_line_km", - value: number, -) { - if (field === "max_mpp" && i > 0 && config.lods[i - 1].simplify === config.lods[i].max_mpp) { - config.lods[i - 1].simplify = value; - } - config.lods[i][field] = value; -} - -/** - * Append a finer tier at half the previous ceiling, with full detail. The - * old finest tier is no longer finest: unless it was hand-set, its simplify - * moves from 0 to the new pixel-accurate default. - */ -export function addLodTier(config: PackConfig) { - const last = config.lods[config.lods.length - 1]; - const prev = last.max_mpp != null ? last.max_mpp : 120; - const next = Math.max(1, Math.round(prev / 2)); - if (!last.simplify) last.simplify = next; - config.lods.push({ max_mpp: next, simplify: 0 }); -} - -/** - * Remove tier `k` and remap every feature's start tier: levels above the - * removed one shift down by one; the removed level collapses into the tier - * that took its index. The (new) coarsest tier is pinned back to +inf. - */ -export function removeLodTier(config: PackConfig, k: number) { - if (config.lods.length <= 1) return; - const removed = config.lods[k]; - config.lods.splice(k, 1); - config.lods[0].max_mpp = null; - // A coarser neighbor tracking the removed ceiling re-defaults to the - // tier that took its place. - if (k > 0 && config.lods[k - 1].simplify === removed.max_mpp) { - config.lods[k - 1].simplify = autoSimplify(config, k - 1); - } - const n = config.lods.length; - for (const cat of Object.keys(config.features)) { - for (const name of Object.keys(config.features[cat])) { - const def = config.features[cat][name]; - let m = typeof def.min_lod === "number" ? def.min_lod : 0; - if (m > k) m -= 1; - def.min_lod = Math.max(0, Math.min(n - 1, m)); - } - } -} - -/** Rebuild one category in the given name order (drag-reorder commit). */ -export function reorderCategory(config: PackConfig, cat: string, orderedNames: string[]) { - const entries = config.features[cat]; - if (!entries) return; - const reordered: Record = {}; - for (const name of orderedNames) { - if (name in entries) reordered[name] = entries[name]; - } - // Anything the order list missed (shouldn't happen) keeps its old position. - for (const name of Object.keys(entries)) { - if (!(name in reordered)) reordered[name] = entries[name]; - } - config.features[cat] = reordered; -} - -/** Defaults for a freshly added feature type. */ -export function newStyleDef(config: PackConfig): StyleDef { - return { z_index: 10, color: "0xFFFF", weight: 1, min_lod: config.lods.length - 1, priority: 3 }; -} - -/** Remove a category; returns its "cat/name" keys for disabled-list cleanup. */ -export function removeCategory(config: PackConfig, cat: string): string[] { - const keys = Object.keys(config.features[cat] ?? {}).map((n) => `${cat}/${n}`); - delete config.features[cat]; - return keys; -} - -/** - * An exported file is a bare, CLI-usable packer config (the packer ignores `_meta` - * and `disabled`) carrying provenance for re-import. - */ -export function exportFile(env: WorkingEnvelope): string { - const out: Record = { - _meta: { - app: "obcm-web-builder", - schema_version: env.schema_version, - based_on: env.based_on, - exported: new Date().toISOString().slice(0, 10), - }, - ...deepCopy(env.config), - }; - if (env.disabled.length) out.disabled = [...env.disabled]; - return JSON.stringify(out, null, 2); -} - -/** - * Accept a builder export or bare CLI config and normalize it into a working envelope. - * Returns null when the JSON isn't a config at all. - */ -export function importFile(text: string): WorkingEnvelope | null { - let raw: unknown; - try { - raw = JSON.parse(text); - } catch { - return null; - } - if (typeof raw !== "object" || raw === null) return null; - const obj = raw as Record; - - if (typeof obj.features !== "object" || obj.features === null) return null; - - const metaValue = obj._meta; - if (metaValue !== undefined && (typeof metaValue !== "object" || metaValue === null || Array.isArray(metaValue))) { - return null; - } - const meta = metaValue as Record | undefined; - if (meta?.schema_version !== undefined && meta.schema_version !== WORKING_SCHEMA_VERSION) return null; - const basedOnValue = meta?.based_on; - let basedOn: WorkingEnvelope["based_on"] = null; - if (basedOnValue !== undefined && basedOnValue !== null) { - if (typeof basedOnValue !== "object" || Array.isArray(basedOnValue)) return null; - const candidate = basedOnValue as Record; - if (typeof candidate.id !== "string" || !Number.isInteger(candidate.version) || Number(candidate.version) < 0) { - return null; - } - basedOn = { id: candidate.id, version: Number(candidate.version) }; - } - const { config, disabled } = normalizeConfig(obj); - const extraDisabled = Array.isArray(obj.disabled) ? (obj.disabled as string[]) : []; - return { - schema_version: WORKING_SCHEMA_VERSION, - based_on: basedOn, - modified: true, // an import is by definition not a pristine preset - config, - disabled: [...new Set([...disabled, ...extraDisabled])], - }; -} diff --git a/builder/web/src/lib/config/model.test.ts b/builder/web/src/lib/config/model.test.ts deleted file mode 100644 index 9c2cfcb855..0000000000 --- a/builder/web/src/lib/config/model.test.ts +++ /dev/null @@ -1,258 +0,0 @@ -import { describe, expect, it } from "vitest"; -import preset from "../../../../presets/schema.json"; -import { buildConfigForSubmit, normalizeConfig, type SchemaEnvelope } from "./model"; - -const sampleConfig = { - _meta: { id: "x", name: "X", version: 1 }, - lods: [ - { max_mpp: 99, simplify: 50 }, // coarsest must be pinned back to null - { max_mpp: 120, simplify: 12 }, - ], - features: { - highway: { - motorway: { color: "0xFAA0", z_index: 60, weight: 3, min_lod: 0 }, - path: { color: "0xAAA0", min_lod: 9 }, // out of range for 2 lods - }, - natural: { - land: { color: "0xFFFF", z_index: 1, min_lod: 0, priority: 1 }, - }, - }, - marker: { color: "0xF800" }, - disabled: ["highway/path"], -}; - -// Mirrors the OBCM style schema obc-pack serves: the five original fields plus -// line_style + color2. Values are placeholders — buildConfigForSubmit only reads -// the property *names*, for its known-key set. -const mockSchema: SchemaEnvelope = { - schema_version: 1, - format_version: 10, - source: "binary", - schema: { - $defs: { - style: { - properties: { - color: {}, - z_index: {}, - weight: {}, - priority: {}, - min_lod: {}, - line_style: { enum: ["solid", "dashed", "ticked"], default: "solid" }, - color2: { $ref: "#/$defs/color" }, - }, - }, - }, - }, -}; - -describe("normalizeConfig", () => { - it("strips _meta, lifts disabled, pins the coarsest tier, clamps min_lod", () => { - const { config, disabled } = normalizeConfig(sampleConfig); - const raw = config as unknown as Record; - expect(raw._meta).toBeUndefined(); - expect(disabled).toEqual(["highway/path"]); - expect(raw.disabled).toBeUndefined(); - expect(config.lods[0].max_mpp).toBeNull(); - expect(config.features.highway.path.min_lod).toBe(1); - }); - - it("defaults an empty config to one coarsest tier and a red marker", () => { - const { config } = normalizeConfig({}); - expect(config.lods).toEqual([{ max_mpp: null, simplify: 0 }]); - expect(config.marker).toEqual({ color: "0xF800" }); - }); -}); - -describe("buildConfigForSubmit", () => { - it("drops disabled features and fills priority", () => { - const { config } = normalizeConfig(sampleConfig); - const out = buildConfigForSubmit(config, ["highway/path"], mockSchema); - expect(out.config.features.highway.path).toBeUndefined(); - expect(out.config.features.highway.motorway.priority).toBe(3); - expect(out.config.features.natural.land.priority).toBe(1); - }); - - it("strips per-style keys the served schema does not declare", () => { - const { config } = normalizeConfig(sampleConfig); - config.features.highway.motorway.experimental = true; // not in the schema - const out = buildConfigForSubmit(config, [], mockSchema); - expect(out.config.features.highway.motorway.experimental).toBeUndefined(); - expect(out.strippedKeys).toEqual(["experimental"]); - }); - - it("keeps line_style + color2 now that the v10 schema declares them", () => { - const { config } = normalizeConfig(sampleConfig); - config.features.highway.motorway.line_style = "dashed"; - config.features.highway.motorway.color2 = "0x8410"; - const out = buildConfigForSubmit(config, [], mockSchema); - expect(out.config.features.highway.motorway.line_style).toBe("dashed"); - expect(out.config.features.highway.motorway.color2).toBe("0x8410"); - expect(out.strippedKeys).toEqual([]); - }); - - it("round-trips an absent color2 as absent (no key, no null)", () => { - const { config } = normalizeConfig(sampleConfig); - const style = buildConfigForSubmit(config, [], mockSchema).config.features.highway.motorway; - expect("color2" in style).toBe(false); - expect(JSON.stringify(style).includes("color2")).toBe(false); - }); - - it("round-trips a present color2 (including black 0x0000, a legit color)", () => { - const { config } = normalizeConfig(sampleConfig); - config.features.highway.motorway.color2 = "0x0000"; // black is NOT "unset" - const style = buildConfigForSubmit(config, [], mockSchema).config.features.highway.motorway; - expect("color2" in style).toBe(true); - expect(style.color2).toBe("0x0000"); - }); - - it("clearing color2 (undefined) drops the key from the submitted config", () => { - const { config } = normalizeConfig(sampleConfig); - // The StyleTable clear handler `delete`s the key; a stray present-but- - // undefined value must still emit as absent, not as `"color2":null`. - config.features.highway.motorway.color2 = undefined; - const out = buildConfigForSubmit(config, [], mockSchema); - const style = out.config.features.highway.motorway; - expect("color2" in style).toBe(false); - expect(out.strippedKeys).toEqual([]); // dropping undefined isn't "stripping" - }); - - it("carries the routing section through to the submitted config", () => { - const { config } = normalizeConfig({ - ...sampleConfig, - routing: { - min_component_edges: 40, - profiles: [{ name: "Road", default: 3, highway: { steps: "forbidden" } }], - }, - }); - const out = buildConfigForSubmit(config, [], mockSchema).config; - expect(out.routing).toEqual({ - min_component_edges: 40, - profiles: [{ name: "Road", default: 3, highway: { steps: "forbidden" } }], - }); - // …and it's a copy, not an alias into the working config. - out.routing!.profiles[0].name = "Mutated"; - expect(config.routing!.profiles[0].name).toBe("Road"); - }); - - it("omits routing entirely when the config has none (CLI-default parity)", () => { - const { config } = normalizeConfig(sampleConfig); - const out = buildConfigForSubmit(config, [], mockSchema).config; - expect("routing" in out).toBe(false); - }); - - it("emits a positive min_area_px but drops it on the finest tier", () => { - const cfg = normalizeConfig({ - lods: [ - { max_mpp: null, simplify: 120, min_area_px: 6 }, - { max_mpp: 120, simplify: 18, min_area_px: 4 }, - { max_mpp: 18, simplify: 0, min_area_px: 4 }, // finest — packer ignores it - ], - features: {}, - marker: { color: "0xF800" }, - }).config; - const out = buildConfigForSubmit(cfg, [], mockSchema).config; - expect(out.lods[0].min_area_px).toBe(6); - expect(out.lods[1].min_area_px).toBe(4); - expect("min_area_px" in out.lods[2]).toBe(false); - }); - - it("round-trips min_line_km, and omits it where it is off", () => { - // The shipped preset's two coarse tiers only fit highway=primary because the stub cull - // frees the spans for it, so a rebuild that dropped the knob would come back over budget - // with the roads torn out. - const cfg = normalizeConfig({ - lods: [ - { max_mpp: null, simplify: 3000, min_area_px: 350, min_line_km: 1.0 }, - { max_mpp: 400, simplify: 1500, min_area_px: 1000, min_line_km: 0.5 }, - { max_mpp: 120, simplify: 200, min_area_px: 50 }, - { max_mpp: 30, simplify: 0 }, - ], - features: {}, - marker: { color: "0xF800" }, - }).config; - expect(cfg.lods.map((l) => l.min_line_km)).toEqual([1.0, 0.5, undefined, undefined]); - const out = buildConfigForSubmit(cfg, [], mockSchema).config; - expect(out.lods[0].min_line_km).toBe(1.0); - expect(out.lods[1].min_line_km).toBe(0.5); - expect("min_line_km" in out.lods[2]).toBe(false); - expect("min_line_km" in out.lods[3]).toBe(false); - }); - - it("omits min_area_px entirely when it is 0/absent (byte-identical off)", () => { - const cfg = normalizeConfig({ - lods: [{ max_mpp: null, simplify: 0, min_area_px: 0 }, { max_mpp: 30, simplify: 0 }], - features: {}, - marker: { color: "0xF800" }, - }).config; - const out = buildConfigForSubmit(cfg, [], mockSchema).config; - expect("min_area_px" in out.lods[0]).toBe(false); - expect("min_area_px" in out.lods[1]).toBe(false); - }); - - it("emits merge_fills only when on (absent/false ⇒ byte-identical off)", () => { - const base = { lods: [{ max_mpp: null, simplify: 0 }], features: {}, marker: { color: "0xF800" } }; - - const off = buildConfigForSubmit(normalizeConfig(base).config, [], mockSchema).config; - expect("merge_fills" in off).toBe(false); - - const explicitOff = buildConfigForSubmit( - normalizeConfig({ ...base, merge_fills: false }).config, - [], - mockSchema, - ).config; - expect("merge_fills" in explicitOff).toBe(false); - - const on = buildConfigForSubmit(normalizeConfig({ ...base, merge_fills: true }).config, [], mockSchema).config; - expect(on.merge_fills).toBe(true); - }); - - it("emits merge_lines only when on (absent/false ⇒ byte-identical off)", () => { - const base = { lods: [{ max_mpp: null, simplify: 0 }], features: {}, marker: { color: "0xF800" } }; - - const off = buildConfigForSubmit(normalizeConfig(base).config, [], mockSchema).config; - expect("merge_lines" in off).toBe(false); - - const explicitOff = buildConfigForSubmit( - normalizeConfig({ ...base, merge_lines: false }).config, - [], - mockSchema, - ).config; - expect("merge_lines" in explicitOff).toBe(false); - - const on = buildConfigForSubmit(normalizeConfig({ ...base, merge_lines: true }).config, [], mockSchema).config; - expect(on.merge_lines).toBe(true); - }); - - it("preserves feature key order (style IDs are document order)", () => { - // Build a config whose keys would re-sort alphabetically if mishandled. - const cfg = normalizeConfig({ - lods: [{ max_mpp: null, simplify: 0 }], - features: { - waterway: { river: { color: "0x555F" } }, - highway: { primary: { color: "0xFD40" }, cycleway: { color: "0x501F" } }, - }, - marker: { color: "0xF800" }, - }).config; - const out = buildConfigForSubmit(cfg, [], null).config; - expect(Object.keys(out.features)).toEqual(["waterway", "highway"]); - expect(Object.keys(out.features.highway)).toEqual(["primary", "cycleway"]); - // …and JSON serialization (what the server receives) keeps that order. - expect(JSON.stringify(out.features).indexOf("waterway")).toBeLessThan( - JSON.stringify(out.features).indexOf("highway"), - ); - }); -}); - -describe("shipped preset round trip", () => { - it("keeps every tier setting and the top-level options the packer reads", () => { - const { config, disabled } = normalizeConfig(preset as unknown as Record); - const out: Record = { ...buildConfigForSubmit(config, disabled, null).config }; - const expected: Record = { ...preset }; - for (const key of ["_meta", "features"]) { - delete out[key]; - delete expected[key]; - } - expect(out).toEqual(expected); - }); -}); - diff --git a/builder/web/src/lib/config/model.ts b/builder/web/src/lib/config/model.ts deleted file mode 100644 index ec49c1c395..0000000000 --- a/builder/web/src/lib/config/model.ts +++ /dev/null @@ -1,223 +0,0 @@ -// The packer-config data model. The bare config shape is owned by obc-pack; this -// module only normalizes it for editing and rebuilds it for submission. CRITICAL -// invariant: the `features` object's key insertion order assigns style IDs 1-based in -// the packer, so every function that rebuilds the tree must copy keys in order, never -// re-sort them. - -export interface LodTier { - max_mpp: number | null; - simplify: number; - // Drop area features whose projected area is below this many square pixels at this - // tier's finest on-screen scale; absent or 0 means off. Lines are never culled, and - // the packer ignores it on the finest tier, which has no coarser fallback. - min_area_px?: number; - // Line tolerance in metres when it differs from `simplify`; absent means `simplify`. - line_simplify?: number; - // Continue solid, uncased lines through junctions as trails; fewer records per junction. - merge_line_trails?: boolean; - // Replace classified thematic fills with the packer's semantic-grid generalisation. - semantic_coverage?: boolean; - // Drop lines shorter than this many kilometres, measured after same-class fragments - // are stitched together, which needs `merge_lines`. It clears the junction stubs and - // roundabout arms stitching could not absorb and keeps the long-distance skeleton. - // Polygons are never touched. Absent or 0 means off. - min_line_km?: number; -} - -export interface StyleDef { - color: string | number; - z_index?: number; - weight?: number; - priority?: number; - min_lod?: number; - // Schema-declared style fields and any future ones ride along untouched. `color2` is - // optional: its key is simply absent when unset, never null or "0x0000", because - // black is a legit color and absence is not. - [key: string]: unknown; -} - -/** One routing edge-weight multiplier: a number >= 1.0 or the string "forbidden". The - * bounds and the sentinel are owned by obc-pack's schema; this type mirrors the - * two-variant shape. */ -export type Multiplier = number | "forbidden"; - -/** One bike profile: a display name, a `default` multiplier for unlisted classes, and - * per-class overrides keyed by the schema's class-name enums. `highway` and `surface` - * are sparse — an absent class inherits `default`. */ -export interface NavProfile { - name: string; - default?: Multiplier; - highway?: Record; - surface?: Record; - // Flat metres charged per metre of ascent, `0..255`. Unlike a class multiplier it - // does NOT inherit anything — absent means `0`, climb-blind, which is how the packer - // reads it. - climb_weight?: number; -} - -/** The `routing` config section (owned by obc-pack; see `obc-pack schema`). */ -export interface RoutingConfig { - min_component_edges?: number; - profiles: NavProfile[]; -} - -export interface PackConfig { - lods: LodTier[]; - features: Record>; - marker: { color: string | number }; - chunk_size?: number; - // Dissolve pixel-identical fill polygons per LOD. Absent or false is a visual no-op - // size and render win. - merge_fills?: boolean; - // Stitch same-styled connected line fragments into maximal polylines per LOD — - // reclaims a span and a ring per join. Solid lines are unchanged; dashed and cased - // phase runs continuous. - merge_lines?: boolean; - // Contour-line settings ride through untouched; the packer validates them. - contours?: unknown; - // Bike-type routing profiles. Absent means the packer bakes in its four shipped - // defaults; the profile editor materializes it on first edit. - routing?: RoutingConfig; -} - -/** One checked-in schema document offered by the maintainer editor. */ -export interface Preset { - id: string; - name: string; - description: string; - version: number; - /** Representative colors, read out of the config. */ - swatch?: string[]; - /** The packer config to build with. */ - config?: PackConfig; -} - -/** A preset that carries its config — what the style editor applies. */ -export type BuildablePreset = Preset & { config: PackConfig }; - -/** Narrow a schema document to one the editor can actually apply. */ -export function isBuildable(preset: Preset): preset is BuildablePreset { - return preset.config !== undefined; -} - -/** The schema envelope served by /api/schema (from `obc-pack schema`). */ -export interface SchemaEnvelope { - schema_version: number; - format_version: number | null; - schema: { - $defs: { style: { properties: Record } }; - [key: string]: unknown; - }; - source: "binary" | "repo-file"; -} - -export function deepCopy(v: T): T { - return JSON.parse(JSON.stringify(v)) as T; -} - -/** - * Adopt a loaded config as editable state: guarantee lods/features/marker exist, pin the - * coarsest tier to +inf, clamp per-style min_lod, and lift out the `disabled` list — a - * top-level `["cat/name", …]` array the packer ignores. - */ -export function normalizeConfig(raw: Record): { - config: PackConfig; - disabled: string[]; -} { - const cfg = deepCopy(raw) as unknown as PackConfig & { disabled?: unknown; _meta?: unknown }; - delete cfg._meta; - if (!Array.isArray(cfg.lods) || cfg.lods.length === 0) { - cfg.lods = [{ max_mpp: null, simplify: 0 }]; - } - cfg.lods = cfg.lods.map((l, i) => ({ - max_mpp: i === 0 ? null : (l.max_mpp ?? null), - simplify: l.simplify ?? 0, - ...(l.min_area_px ? { min_area_px: l.min_area_px } : {}), - ...(l.line_simplify ? { line_simplify: l.line_simplify } : {}), - ...(l.merge_line_trails ? { merge_line_trails: true } : {}), - ...(l.semantic_coverage ? { semantic_coverage: true } : {}), - ...(l.min_line_km ? { min_line_km: l.min_line_km } : {}), - })); - cfg.features = cfg.features ?? {}; - cfg.marker = cfg.marker ?? { color: "0xF800" }; - const disabled = Array.isArray(cfg.disabled) ? (cfg.disabled as string[]) : []; - delete cfg.disabled; - const maxLod = cfg.lods.length - 1; - for (const cat of Object.keys(cfg.features)) { - for (const name of Object.keys(cfg.features[cat])) { - const def = cfg.features[cat][name]; - if (typeof def.min_lod === "number") { - def.min_lod = Math.max(0, Math.min(maxLod, def.min_lod | 0)); - } - } - } - return { config: cfg, disabled }; -} - -/** - * The config actually submitted to a build: disabled features dropped, min_lod clamped - * to the LOD count, and per-style keys not declared by the served schema stripped, so - * the UI never sends styling the binary would silently ignore. Returns the stripped key - * names alongside the config. Key order is preserved throughout, because it assigns - * style IDs. - */ -export function buildConfigForSubmit( - config: PackConfig, - disabled: string[], - schema: SchemaEnvelope | null, -): { config: PackConfig; strippedKeys: string[] } { - const disabledSet = new Set(disabled); - const known = schema ? new Set(Object.keys(schema.schema.$defs.style.properties)) : null; - const stripped = new Set(); - const n = config.lods.length; - const out: PackConfig = { - lods: config.lods.map((l, i) => { - const tier: LodTier = { max_mpp: i === 0 ? null : (l.max_mpp ?? null), simplify: l.simplify || 0 }; - // Emit only a positive footprint floor; the finest tier's value is ignored by - // the packer, so leaving it off keeps the submitted config clean. - if (l.min_area_px && i < n - 1) tier.min_area_px = l.min_area_px; - // Same rule: zero and false are the off values. - if (l.line_simplify) tier.line_simplify = l.line_simplify; - if (l.merge_line_trails) tier.merge_line_trails = true; - if (l.semantic_coverage) tier.semantic_coverage = true; - if (l.min_line_km) tier.min_line_km = l.min_line_km; - return tier; - }), - features: {}, - marker: config.marker, - }; - if (config.chunk_size != null) out.chunk_size = config.chunk_size; - // Emit merge_fills / merge_lines only when on; absent is the packer's default (off). - if (config.merge_fills) out.merge_fills = true; - if (config.merge_lines) out.merge_lines = true; - // Routing profiles ride through untouched, validated by the packer. Absent means the - // binary bakes in its four shipped defaults, so CLI parity holds. - if (config.routing) out.routing = deepCopy(config.routing); - if (config.contours != null) out.contours = deepCopy(config.contours); - for (const cat of Object.keys(config.features)) { - for (const name of Object.keys(config.features[cat])) { - if (disabledSet.has(`${cat}/${name}`)) continue; - const def = config.features[cat][name]; - const copy: StyleDef = { ...def }; - copy.min_lod = Math.max(0, Math.min(n - 1, (def.min_lod ?? 0) | 0)); - copy.priority = def.priority || 3; - for (const key of Object.keys(copy)) { - // A cleared optional field is present-but-undefined after a spread; drop - // it so JSON emits absence, not the key. - if (copy[key] === undefined) { - delete copy[key]; - continue; - } - // Keys the served schema does not declare would be silently ignored by the - // binary — strip them and report which. - if (known && !known.has(key)) { - stripped.add(key); - delete copy[key]; - } - } - out.features[cat] = out.features[cat] || {}; - out.features[cat][name] = copy; - } - } - return { config: out, strippedKeys: [...stripped] }; -} diff --git a/builder/web/src/lib/config/profiles.test.ts b/builder/web/src/lib/config/profiles.test.ts deleted file mode 100644 index 7b103f297a..0000000000 --- a/builder/web/src/lib/config/profiles.test.ts +++ /dev/null @@ -1,218 +0,0 @@ -import { describe, expect, it } from "vitest"; -import type { NavProfile, PackConfig, SchemaEnvelope } from "./model"; -import { - cellValue, - checkClimbWeight, - checkMultiplier, - clearCell, - clearClimbWeight, - displayProfiles, - ensureRouting, - hasClimbWeight, - isExplicit, - profileClimbWeight, - profileDefault, - readProfileSchema, - resetProfile, - setCell, - setClimbWeight, -} from "./profiles"; - -// A schema envelope shaped like `obc-pack schema`'s routing bits (trimmed). -const road: NavProfile = { - name: "Road", - default: 3.0, - highway: { cycleway: 1.0, primary: 1.8, steps: "forbidden" }, - surface: { paved: 1.0, gravel: 5.0 }, - climb_weight: 10, -}; -const gravel: NavProfile = { name: "Gravel", default: 2.0, highway: { track: 1.2 }, climb_weight: 8 }; - -function schemaEnvelope(): SchemaEnvelope { - return { - schema_version: 1, - format_version: 9, - source: "binary", - schema: { - $defs: { - style: { properties: {} }, - multiplier: { oneOf: [{ type: "number", minimum: 1.0 }, { const: "forbidden" }] }, - profile: { - properties: { - name: { maxLength: 12, "x-maxUtf8Bytes": 12 }, - default: { default: 2.0 }, - climb_weight: { minimum: 0, maximum: 255, default: 0 }, - highway: { - propertyNames: { - enum: ["cycleway", "path", "track", "steps", "primary"], - }, - }, - surface: { propertyNames: { enum: ["unknown", "paved", "gravel"] } }, - }, - }, - }, - properties: { - routing: { - properties: { profiles: { minItems: 1, maxItems: 8 } }, - default: { profiles: [road, gravel] }, - }, - }, - }, - } as unknown as SchemaEnvelope; -} - -const PS = readProfileSchema(schemaEnvelope())!; - -describe("readProfileSchema", () => { - it("reads class enums, bounds, and shipped defaults from the schema", () => { - expect(PS.highwayClasses).toEqual(["cycleway", "path", "track", "steps", "primary"]); - expect(PS.surfaceClasses).toEqual(["unknown", "paved", "gravel"]); - expect(PS.multiplierMin).toBe(1.0); - expect(PS.defaultMultiplier).toBe(2.0); - expect(PS.climbMin).toBe(0); - expect(PS.climbMax).toBe(255); - expect(PS.climbDefault).toBe(0); - expect(PS.defaultProfiles.map((p) => p.name)).toEqual(["Road", "Gravel"]); - }); - - it("falls back to the u8 range when the schema predates the v12 climb weight", () => { - const env = schemaEnvelope() as any; - delete env.schema.$defs.profile.properties.climb_weight; - const ps = readProfileSchema(env)!; - expect([ps.climbMin, ps.climbMax, ps.climbDefault]).toEqual([0, 255, 0]); - }); - - it("returns null when the schema doesn't describe routing", () => { - const bare = { schema_version: 1, format_version: 6, source: "binary", schema: { $defs: { style: { properties: {} } } } } as unknown as SchemaEnvelope; - expect(readProfileSchema(bare)).toBeNull(); - expect(readProfileSchema(null)).toBeNull(); - }); -}); - -describe("cell value / explicit / inherit", () => { - it("shows the explicit override, and the profile default for unlisted classes", () => { - expect(cellValue(road, "highway", "cycleway", PS)).toBe(1.0); - expect(isExplicit(road, "highway", "cycleway")).toBe(true); - // `path` is not listed → inherits the profile default (3.0). - expect(cellValue(road, "highway", "path", PS)).toBe(3.0); - expect(isExplicit(road, "highway", "path")).toBe(false); - // steps is explicitly forbidden. - expect(cellValue(road, "highway", "steps", PS)).toBe("forbidden"); - }); - - it("falls back to the schema default multiplier when the profile omits `default`", () => { - const p: NavProfile = { name: "X" }; - expect(profileDefault(p, PS)).toBe(2.0); - expect(cellValue(p, "surface", "gravel", PS)).toBe(2.0); - }); -}); - -describe("setCell / clearCell", () => { - it("writes an explicit override and reverts it to inherit", () => { - const p: NavProfile = { name: "X", default: 2.0 }; - setCell(p, "highway", "primary", 4.0); - expect(p.highway).toEqual({ primary: 4.0 }); - expect(cellValue(p, "highway", "primary", PS)).toBe(4.0); - setCell(p, "surface", "paved", "forbidden"); - expect(p.surface).toEqual({ paved: "forbidden" }); - clearCell(p, "highway", "primary"); - expect(isExplicit(p, "highway", "primary")).toBe(false); - expect(cellValue(p, "highway", "primary", PS)).toBe(2.0); - }); -}); - -describe("multiplier validation", () => { - it("rejects a sub-minimum value with an admissibility hint", () => { - const r = checkMultiplier(0.5, PS.multiplierMin); - expect(r.ok).toBe(false); - expect(r.hint).toMatch(/admissible/); - expect(r.hint).toMatch(/shortest-path/); - }); - - it("rejects a non-number (cleared field) without the scary message", () => { - const r = checkMultiplier(NaN, PS.multiplierMin); - expect(r.ok).toBe(false); - expect(r.hint).toMatch(/number/); - }); - - it("accepts a value at or above the minimum", () => { - expect(checkMultiplier(1.0, PS.multiplierMin).ok).toBe(true); - expect(checkMultiplier(5.5, PS.multiplierMin).ok).toBe(true); - }); -}); - -describe("climb weight", () => { - it("reads the profile's own weight, and 0 (not NaN) for a pre-v12 config", () => { - expect(profileClimbWeight(road, PS)).toBe(10); - expect(hasClimbWeight(road)).toBe(true); - // A config written before OBCM v12 simply has no such key. - const legacy: NavProfile = { name: "Old", default: 2.0 }; - expect(hasClimbWeight(legacy)).toBe(false); - expect(profileClimbWeight(legacy, PS)).toBe(0); - expect(Number.isNaN(profileClimbWeight(legacy, PS))).toBe(false); - // A hand-edited config could carry a null / string; still not NaN. - const junk = { name: "Junk", climb_weight: null } as unknown as NavProfile; - expect(profileClimbWeight(junk, PS)).toBe(0); - }); - - it("sets a weight and reverts to climb-blind by dropping the key", () => { - const p: NavProfile = { name: "X" }; - setClimbWeight(p, 12); - expect(p.climb_weight).toBe(12); - expect(hasClimbWeight(p)).toBe(true); - clearClimbWeight(p); - expect("climb_weight" in p).toBe(false); - expect(profileClimbWeight(p, PS)).toBe(0); - }); - - it("accepts whole numbers across the schema range, including 0", () => { - for (const n of [0, 1, 6, 8, 10, 255]) { - expect(checkClimbWeight(n, PS.climbMin, PS.climbMax).ok).toBe(true); - } - }); - - it("rejects out-of-range, fractional and empty entries", () => { - expect(checkClimbWeight(256, PS.climbMin, PS.climbMax).ok).toBe(false); - expect(checkClimbWeight(-1, PS.climbMin, PS.climbMax).ok).toBe(false); - expect(checkClimbWeight(2.5, PS.climbMin, PS.climbMax).ok).toBe(false); - const empty = checkClimbWeight(NaN, PS.climbMin, PS.climbMax); - expect(empty.ok).toBe(false); - expect(empty.hint).toMatch(/whole number/); - // Unlike a multiplier there is no admissibility floor to name — the term - // is added, so nothing here talks about the A* bound. - expect(checkClimbWeight(256, PS.climbMin, PS.climbMax).hint).not.toMatch(/admissible/); - }); -}); - -describe("routing lifecycle over a config", () => { - function bareConfig(): PackConfig { - return { lods: [{ max_mpp: null, simplify: 0 }], features: {}, marker: { color: "0xF800" } }; - } - - it("displays shipped defaults for a config with no routing section", () => { - const cfg = bareConfig(); - expect(cfg.routing).toBeUndefined(); - expect(displayProfiles(cfg, PS).map((p) => p.name)).toEqual(["Road", "Gravel"]); - }); - - it("materializes routing from the shipped defaults on first ensure", () => { - const cfg = bareConfig(); - const routing = ensureRouting(cfg, PS); - expect(cfg.routing).toBe(routing); - expect(routing.profiles.map((p) => p.name)).toEqual(["Road", "Gravel"]); - // A deep copy — editing the config must not mutate the schema defaults. - routing.profiles[0].name = "Edited"; - expect(PS.defaultProfiles[0].name).toBe("Road"); - }); - - it("resets a bike type to its shipped weights", () => { - const cfg = bareConfig(); - ensureRouting(cfg, PS); - cfg.routing!.profiles[0].highway = { cycleway: 9.0 }; // tamper with Road - setClimbWeight(cfg.routing!.profiles[0], 0); // …and make it climb-blind - resetProfile(cfg, 0, PS); - expect(cfg.routing!.profiles[0].highway).toEqual(road.highway); - expect(cfg.routing!.profiles[0].highway!.cycleway).toBe(1.0); - expect(cfg.routing!.profiles[0].climb_weight).toBe(10); // the shipped weight is back - }); -}); diff --git a/builder/web/src/lib/config/profiles.ts b/builder/web/src/lib/config/profiles.ts deleted file mode 100644 index 365a580d27..0000000000 --- a/builder/web/src/lib/config/profiles.ts +++ /dev/null @@ -1,243 +0,0 @@ -// Pure logic for the routing-profile editor. Everything here is driven by the -// config JSON Schema served by `obc-pack schema` — the class-name enums, the -// multiplier bound and the four shipped default profiles all come from the schema -// and are never re-hardcoded in Svelte. The component in components/advanced/ is -// thin glue over these functions. - -import { - deepCopy, - type Multiplier, - type NavProfile, - type PackConfig, - type RoutingConfig, - type SchemaEnvelope, -} from "./model"; - -export type ClassGroup = "highway" | "surface"; - -/** The profile-editor capabilities read out of the served schema. */ -export interface ProfileSchema { - /** Highway class names, in canonical order (schema propertyNames enum). */ - highwayClasses: string[]; - /** Surface class names, in canonical order. */ - surfaceClasses: string[]; - /** Lower bound for a numeric multiplier (schema $defs/multiplier). */ - multiplierMin: number; - /** The per-profile `default` fallback multiplier (schema default: 2.0). */ - defaultMultiplier: number; - /** Climb-weight bounds, `0..255` (schema profile.climb_weight minimum/maximum). */ - climbMin: number; - climbMax: number; - /** The climb weight an unstated field means — `0`, climb-blind (schema default). */ - climbDefault: number; - /** The four bike types' shipped weights (Road / Gravel / MTB / Touring), in their fixed order. */ - defaultProfiles: NavProfile[]; -} - -// Loose views into the schema tree — the served envelope only strong-types -// $defs.style, so the routing bits are read defensively with fallbacks that match -// the spec (a schema that predates routing simply yields no editor). -interface SchemaTree { - properties?: { - routing?: { - default?: { profiles?: NavProfile[] }; - }; - }; - $defs?: { - multiplier?: { oneOf?: { type?: string; minimum?: number }[] }; - profile?: { - properties?: { - default?: { default?: number }; - climb_weight?: { minimum?: number; maximum?: number; default?: number }; - highway?: { propertyNames?: { enum?: string[] } }; - surface?: { propertyNames?: { enum?: string[] } }; - }; - }; - }; -} - -/** - * Read the routing-profile capabilities out of the served schema, or null when the - * schema does not describe routing — the editor hides itself rather than guessing. - */ -export function readProfileSchema(env: SchemaEnvelope | null): ProfileSchema | null { - const s = (env?.schema ?? null) as SchemaTree | null; - const profile = s?.$defs?.profile?.properties; - const highwayClasses = profile?.highway?.propertyNames?.enum; - const surfaceClasses = profile?.surface?.propertyNames?.enum; - const defaultProfiles = s?.properties?.routing?.default?.profiles; - if (!highwayClasses?.length || !surfaceClasses?.length || !defaultProfiles?.length) { - return null; - } - const numberVariant = s?.$defs?.multiplier?.oneOf?.find((o) => o.type === "number"); - return { - highwayClasses, - surfaceClasses, - multiplierMin: numberVariant?.minimum ?? 1, - defaultMultiplier: profile?.default?.default ?? 2, - // An older schema states no climb bounds; the wire field is a `u8` either - // way, so fall back to its full range and to climb-blind. - climbMin: profile?.climb_weight?.minimum ?? 0, - climbMax: profile?.climb_weight?.maximum ?? 255, - climbDefault: profile?.climb_weight?.default ?? 0, - defaultProfiles, - }; -} - -/** The canonical shipped profiles (a fresh deep copy so edits never alias). */ -export function defaultProfiles(ps: ProfileSchema): NavProfile[] { - return deepCopy(ps.defaultProfiles); -} - -/** The class names for a group, in canonical (schema) order. */ -export function classNames(ps: ProfileSchema, group: ClassGroup): string[] { - return group === "highway" ? ps.highwayClasses : ps.surfaceClasses; -} - -/** A profile's per-class map for a group (may be absent). */ -function classMap(profile: NavProfile, group: ClassGroup): Record | undefined { - return group === "highway" ? profile.highway : profile.surface; -} - -/** `true` when the class carries an explicit override (vs. inheriting `default`). */ -export function isExplicit(profile: NavProfile, group: ClassGroup, cls: string): boolean { - const map = classMap(profile, group); - return !!map && Object.prototype.hasOwnProperty.call(map, cls); -} - -/** A profile's effective `default` multiplier (falls back to the schema default). */ -export function profileDefault(profile: NavProfile, ps: ProfileSchema): Multiplier { - return profile.default ?? ps.defaultMultiplier; -} - -/** `true` when the profile states a climb weight of its own, rather than being - * climb-blind by omission. */ -export function hasClimbWeight(profile: NavProfile): boolean { - return typeof profile.climb_weight === "number" && Number.isFinite(profile.climb_weight); -} - -/** - * A profile's effective climb weight — flat metres charged per metre of ascent. - * Unlike a class multiplier this inherits nothing: an absent or non-numeric field is - * the schema's `0`, climb-blind, which is exactly how the packer reads it. - */ -export function profileClimbWeight(profile: NavProfile, ps: ProfileSchema): number { - return hasClimbWeight(profile) ? profile.climb_weight! : ps.climbDefault; -} - -/** - * Whether a raw climb-weight entry is admissible. The field is a `u8`, so the only - * rules are "a whole number" and the schema's `0..255`. There is no `>= 1.0` floor, - * because the climb term is *added* after the way-kind scaling and so can never make - * an edge cheaper than the crow flies. `0` is a meaningful value, not an unset one. - */ -export function checkClimbWeight(n: number, min: number, max: number): { ok: boolean; hint: string | null } { - if (!Number.isFinite(n) || !Number.isInteger(n)) { - return { ok: false, hint: `enter a whole number between ${min} and ${max} (${min} = climb-blind).` }; - } - if (n < min || n > max) { - return { - ok: false, - hint: - `a climb weight is a whole number between ${min} and ${max} — it's the byte the ` + - `map carries per profile (OBCM §8.6). ${min} is climb-blind: the router costs ` + - "ascent at nothing and plans exactly as it did before the map had terrain.", - }; - } - return { ok: true, hint: null }; -} - -/** Set a profile's climb weight (caller has already validated it). */ -export function setClimbWeight(profile: NavProfile, v: number): void { - profile.climb_weight = v; -} - -/** Drop a profile's climb weight, leaving it climb-blind like an unstated field. */ -export function clearClimbWeight(profile: NavProfile): void { - delete profile.climb_weight; -} - -/** - * The effective multiplier shown in a cell: the explicit override if the class carries - * one, otherwise the profile `default`. This mirrors the packer, which fills every wire - * slot from `default` and overlays the map. - */ -export function cellValue( - profile: NavProfile, - group: ClassGroup, - cls: string, - ps: ProfileSchema, -): Multiplier { - const map = classMap(profile, group); - if (map && Object.prototype.hasOwnProperty.call(map, cls)) return map[cls]; - return profileDefault(profile, ps); -} - -/** - * Whether a raw numeric entry is admissible against the schema's minimum. A value below - * it is rejected with a hint that mirrors the packer's error text, so the CLI and the web - * builder tell the user the same thing. This is the single copy of that message. - */ -export function checkMultiplier(n: number, min: number): { ok: boolean; hint: string | null } { - if (!Number.isFinite(n)) return { ok: false, hint: "enter a number ≥ " + min.toFixed(1) + "." }; - if (n < min) { - return { - ok: false, - hint: - `a multiplier below ${min.toFixed(1)} breaks the router's ` + - "shortest-path guarantee — every non-zero weight must stay ≥ 1.0 so the " + - "great-circle A* heuristic remains admissible. Use “forbidden” to exclude " + - "the class instead.", - }; - } - return { ok: true, hint: null }; -} - -/** Write an explicit override for a class (number already clamped, or "forbidden"). */ -export function setCell(profile: NavProfile, group: ClassGroup, cls: string, v: Multiplier): void { - if (group === "highway") (profile.highway ??= {})[cls] = v; - else (profile.surface ??= {})[cls] = v; -} - -/** Drop a class's explicit override so it inherits `default` again. */ -export function clearCell(profile: NavProfile, group: ClassGroup, cls: string): void { - const map = classMap(profile, group); - if (!map) return; - delete map[cls]; -} - -/** Set a profile's per-profile `default` multiplier. */ -export function setProfileDefault(profile: NavProfile, v: Multiplier): void { - profile.default = v; -} - -/** - * The profiles the editor should display for a config: the config's own - * `routing.profiles` if present, otherwise the schema's shipped defaults, shown - * read-until-edited so an untouched CLI config stays `routing`-less. - */ -export function displayProfiles(config: PackConfig, ps: ProfileSchema): NavProfile[] { - return config.routing?.profiles ?? defaultProfiles(ps); -} - -/** - * Materialize `config.routing` so it can be edited in place, seeding it from the schema - * defaults when the config did not carry a routing section. Idempotent. - */ -export function ensureRouting(config: PackConfig, ps: ProfileSchema): RoutingConfig { - if (!config.routing) { - config.routing = { profiles: defaultProfiles(ps) }; - } else if (!Array.isArray(config.routing.profiles) || config.routing.profiles.length === 0) { - config.routing.profiles = defaultProfiles(ps); - } - return config.routing; -} - -/** Reset bike type `i` to its shipped weights. The order of the types is fixed. */ -export function resetProfile(config: PackConfig, i: number, ps: ProfileSchema): NavProfile | null { - const routing = ensureRouting(config, ps); - if (i < 0 || i >= routing.profiles.length) return null; - const replacement = deepCopy(ps.defaultProfiles[i]); - routing.profiles[i] = replacement; - return replacement; -} diff --git a/builder/web/src/lib/config/schema_fields.test.ts b/builder/web/src/lib/config/schema_fields.test.ts deleted file mode 100644 index 216e343bc2..0000000000 --- a/builder/web/src/lib/config/schema_fields.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { describe, expect, it } from "vitest"; -import generatedConfigSchema from "../../../../../host/obc-map-core/schema/config.schema.json"; -import { - enumDisplayValue, - resolveSchemaField, - stringEnumOptions, - type JsonSchema, -} from "./schema_fields"; - -const generated = generatedConfigSchema as unknown as JsonSchema; - -function generatedStyleField(name: string): JsonSchema { - const defs = generated.$defs as Record; - const style = defs.style; - return (style.properties as Record)[name]; -} - -function generatedProfileField(name: string): JsonSchema { - const defs = generated.$defs as Record; - const profile = defs.profile; - return (profile.properties as Record)[name]; -} - -describe("generic schema field resolution", () => { - it("renders the generated nullable line_style ref as the solid/dashed/ticked enum", () => { - const raw = generatedStyleField("line_style"); - expect(raw.anyOf).toBeDefined(); // discriminates from the former inline-enum mock - - const resolved = resolveSchemaField(generated, raw); - const options = stringEnumOptions(resolved.schema); - expect(resolved.nullable).toBe(true); - expect(options).toEqual(["solid", "dashed", "ticked"]); - expect(enumDisplayValue("dashed", resolved.schema, options!)).toBe("dashed"); - expect(enumDisplayValue(null, resolved.schema, options!)).toBe("solid"); - expect(enumDisplayValue("invalid", resolved.schema, options!)).toBe("solid"); - }); - - it("resolves the generated color ref while preserving its field description", () => { - const resolved = resolveSchemaField(generated, generatedStyleField("color2")); - expect(resolved.schema.description).toMatch(/secondary RGB565/); - expect(resolved.schema.oneOf).toEqual((generated.$defs as Record).color.oneOf); - }); - - it("normalizes generated nullable numeric type arrays", () => { - const resolved = resolveSchemaField(generated, generatedStyleField("weight")); - expect(resolved).toMatchObject({ nullable: true, schema: { type: "integer", minimum: 0, maximum: 255 } }); - }); - - it("retains the other generated nullable ref's genuine multiplier union", () => { - const resolved = resolveSchemaField(generated, generatedProfileField("default")); - const multiplier = (generated.$defs as Record).multiplier; - expect(resolved.nullable).toBe(true); - expect(resolved.schema.oneOf).toEqual(multiplier.oneOf); - expect(resolved.schema.default).toBe(2.0); - }); - - it("leaves unknown and cyclic refs unresolved without recursing forever", () => { - expect(resolveSchemaField({}, { $ref: "#/$defs/missing" }).schema).toEqual({ - $ref: "#/$defs/missing", - }); - - const cyclic: JsonSchema = { $defs: { a: { $ref: "#/$defs/b" }, b: { $ref: "#/$defs/a" } } }; - expect(() => resolveSchemaField(cyclic, { $ref: "#/$defs/a" })).not.toThrow(); - expect(resolveSchemaField(cyclic, { $ref: "#/$defs/a" }).schema.$ref).toBeDefined(); - }); -}); diff --git a/builder/web/src/lib/config/schema_fields.ts b/builder/web/src/lib/config/schema_fields.ts deleted file mode 100644 index ceb307bb79..0000000000 --- a/builder/web/src/lib/config/schema_fields.ts +++ /dev/null @@ -1,111 +0,0 @@ -// Defensive resolution for fields rendered by the advanced editor's generic -// SchemaField component. obc-pack owns the schema; this module only turns the -// common JSON Schema spellings it emits ($ref, nullable unions/type arrays) -// into the single field shape the control needs. - -export type JsonSchema = Record; - -export interface ResolvedSchemaField { - schema: JsonSchema; - nullable: boolean; -} - -const MAX_RESOLVE_DEPTH = 32; - -function isSchema(value: unknown): value is JsonSchema { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - -function localRef(root: JsonSchema, ref: string): JsonSchema | null { - if (!ref.startsWith("#/")) return null; - let cursor: unknown = root; - for (const encoded of ref.slice(2).split("/")) { - let segment: string; - try { - segment = decodeURIComponent(encoded).replace(/~1/g, "/").replace(/~0/g, "~"); - } catch { - return null; - } - if (!isSchema(cursor) || !Object.prototype.hasOwnProperty.call(cursor, segment)) return null; - cursor = cursor[segment]; - } - return isSchema(cursor) ? cursor : null; -} - -function isNullSchema(schema: JsonSchema): boolean { - if (schema.type === "null" || schema.const === null) return true; - return Array.isArray(schema.enum) && schema.enum.length === 1 && schema.enum[0] === null; -} - -function resolveNode( - root: JsonSchema, - input: JsonSchema, - activeRefs: Set, - depth: number, -): ResolvedSchemaField { - if (depth >= MAX_RESOLVE_DEPTH) return { schema: { ...input }, nullable: false }; - - let schema: JsonSchema = { ...input }; - let nullable = false; - - const ref = schema.$ref; - if (typeof ref === "string" && !activeRefs.has(ref)) { - const target = localRef(root, ref); - if (target) { - activeRefs.add(ref); - const resolved = resolveNode(root, target, activeRefs, depth + 1); - activeRefs.delete(ref); - const siblings = { ...schema }; - delete siblings.$ref; - schema = { ...resolved.schema, ...siblings }; - nullable ||= resolved.nullable; - } - } - - for (const unionKey of ["anyOf", "oneOf"] as const) { - const variants = schema[unionKey]; - if (!Array.isArray(variants) || !variants.every(isSchema)) continue; - const resolved = variants.map((variant) => resolveNode(root, variant, activeRefs, depth + 1)); - const concrete = resolved.filter((variant) => !isNullSchema(variant.schema)); - const nullCount = resolved.length - concrete.length; - nullable ||= nullCount > 0 || resolved.some((variant) => variant.nullable); - - // `T | null` is the shape schemars emits for Option. Collapse only - // that unambiguous case; a genuine multi-shape union remains a union. - if (nullCount > 0 && concrete.length === 1) { - const parent = { ...schema }; - delete parent[unionKey]; - schema = { ...concrete[0].schema, ...parent }; - } else { - schema[unionKey] = resolved.map((variant) => variant.schema); - } - } - - if (Array.isArray(schema.type)) { - const types = schema.type.filter((type): type is string => typeof type === "string"); - const concrete = types.filter((type) => type !== "null"); - nullable ||= concrete.length !== types.length; - if (concrete.length === 1) schema.type = concrete[0]; - else if (concrete.length > 1) schema.type = concrete; - } - - return { schema, nullable }; -} - -/** Resolve one schema field without throwing on unknown, external, or cyclic refs. */ -export function resolveSchemaField(root: JsonSchema, field: JsonSchema): ResolvedSchemaField { - return resolveNode(root, field, new Set(), 0); -} - -/** String options for a select control, or null when this is not a string enum. */ -export function stringEnumOptions(schema: JsonSchema): string[] | null { - if (!Array.isArray(schema.enum) || !schema.enum.every((value) => typeof value === "string")) return null; - return schema.enum; -} - -/** Stable select value: null/unknown values display the schema default or first option. */ -export function enumDisplayValue(value: unknown, schema: JsonSchema, options: string[]): string { - if (typeof value === "string" && options.includes(value)) return value; - if (typeof schema.default === "string" && options.includes(schema.default)) return schema.default; - return options[0] ?? ""; -} diff --git a/builder/web/src/lib/config/storage.svelte.ts b/builder/web/src/lib/config/storage.svelte.ts deleted file mode 100644 index 0bcf465615..0000000000 --- a/builder/web/src/lib/config/storage.svelte.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { deepCopy, normalizeConfig, type BuildablePreset, type PackConfig } from "./model"; - -// The working config lives in the browser (localStorage), never on the server -// — that keeps the backend stateless (no accounts needed) and survives -// reloads. Snapshot semantics: picking a preset COPIES it; edits mark the -// envelope modified ("Custom — based on X"). The maintainer route may seed an -// empty browser from its sole buildable schema once; preset updates never -// silently change an existing map — "Reset to preset" re-copies explicitly. - -export interface WorkingEnvelope { - schema_version: typeof WORKING_SCHEMA_VERSION; - based_on: { id: string; version: number } | null; - modified: boolean; - config: PackConfig; - disabled: string[]; -} - -const STORAGE_KEY = "obcm.working"; -export const WORKING_SCHEMA_VERSION = 1; - -function currentEnvelope(raw: unknown): WorkingEnvelope | null { - if (typeof raw !== "object" || raw === null) return null; - const env = raw as Record; - if (env.schema_version !== WORKING_SCHEMA_VERSION) return null; - if (typeof env.config !== "object" || env.config === null || Array.isArray(env.config)) return null; - if (typeof env.modified !== "boolean") return null; - if (!Array.isArray(env.disabled) || !env.disabled.every((key) => typeof key === "string")) return null; - const basedOn = env.based_on; - if ( - basedOn !== null && - (typeof basedOn !== "object" || - Array.isArray(basedOn) || - typeof (basedOn as Record).id !== "string" || - !Number.isInteger((basedOn as Record).version) || - Number((basedOn as Record).version) < 0) - ) { - return null; - } - return env as unknown as WorkingEnvelope; -} - -export class WorkingConfig { - envelope = $state(null); - - /** Restore the current localStorage envelope; false for absent or invalid data. */ - restore(): boolean { - try { - const raw = localStorage.getItem(STORAGE_KEY); - if (!raw) return false; - const env = currentEnvelope(JSON.parse(raw)); - if (!env) return false; - const { config, disabled } = normalizeConfig( - env.config as unknown as Record, - ); - this.envelope = { ...env, config, disabled: [...new Set([...env.disabled, ...disabled])] }; - return true; - } catch { - return false; - } - } - - /** Snapshot a preset into the working config (discards previous state). - * Takes a preset that carries a config — a catalog preset (hosted tier) - * names a baked artifact and has nothing to snapshot. */ - applyPreset(preset: BuildablePreset) { - const { config, disabled } = normalizeConfig( - preset.config as unknown as Record, - ); - this.envelope = { - schema_version: WORKING_SCHEMA_VERSION, - based_on: { id: preset.id, version: preset.version }, - modified: false, - config: deepCopy(config), - disabled, - }; - this.persist(); - } - - /** Replace the whole envelope (import). */ - adopt(envelope: WorkingEnvelope) { - this.envelope = envelope; - this.persist(); - } - - /** - * Call after any edit to the config tree (the advanced editor's hook). - * Persisting is debounced: number inputs fire per keystroke and the - * envelope is tens of KB of JSON. - */ - markModified() { - if (!this.envelope) return; - this.envelope.modified = true; - clearTimeout(this.saveTimer); - this.saveTimer = setTimeout(() => this.persist(), 400); - } - - private saveTimer: ReturnType | undefined; - - persist() { - if (!this.envelope) return; - clearTimeout(this.saveTimer); - try { - localStorage.setItem(STORAGE_KEY, JSON.stringify(this.envelope)); - } catch { - // Quota/private-mode failures are non-fatal: the session still works. - } - } -} - -export const working = new WorkingConfig(); diff --git a/builder/web/src/lib/constants.ts b/builder/web/src/lib/constants.ts index 1207ff0874..efc087f58d 100644 --- a/builder/web/src/lib/constants.ts +++ b/builder/web/src/lib/constants.ts @@ -1,5 +1,5 @@ /** - * Links out of the builder, in one place. + * Links out of the app, in one place. * * The docs and the landing page (with the live demo on it) are the other two * surfaces of the same site, and where they are depends on how *this* bundle was @@ -8,8 +8,8 @@ * * unset — the default — means the site is somewhere else, so name it * 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. + * * set to a relative prefix (the deploy passes `../`, because the app is + * published at `/plan/` beside `/docs/`) means the site is right here. * Nothing absolute is baked in, so the whole artifact survives the move to a * custom domain — see .github/workflows/deploy-site.yml. * diff --git a/builder/web/src/lib/coverage/run.svelte.ts b/builder/web/src/lib/coverage/run.svelte.ts index bd7488e899..915c43dd63 100644 --- a/builder/web/src/lib/coverage/run.svelte.ts +++ b/builder/web/src/lib/coverage/run.svelte.ts @@ -1,8 +1,8 @@ // 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. +// wasm in a Worker, and 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. +// acknowledge. import { ASSEMBLE_PHASES, type AssemblePhase, type MemoryEstimate } from "../assemble/bridge"; import { @@ -34,7 +34,6 @@ import { } from "../cells/store"; import { projectedRunDiskBytes } from "../cells/quota"; import { acquireMapWorkStorage } from "../cells/workBarrier"; -import { saveBlob } from "../download"; import { downloadCells, planCells, @@ -90,8 +89,7 @@ export type Phase = | "cancelled" | "error"; -interface DeviceOutput { - readonly kind: "device"; +interface Output { readonly client: FlatStoreClient; readonly ctx: JobContext; readonly resolve: (result: PutResponse) => void; @@ -105,14 +103,6 @@ interface DeviceOutput { 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. @@ -173,13 +163,7 @@ export class MapRun { #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 + /** The one delivery, so `done` can wait for a 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 @@ -208,7 +192,6 @@ export class MapRun { #runFileName = $state("OBC map.obcm"); #output = $state.raw(null); - #lastRunKind = $state("download"); #nextRunId = 0; #activeRunId = 0; #failure: Promise = Promise.resolve(); @@ -236,8 +219,6 @@ export class MapRun { 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; } @@ -248,8 +229,6 @@ export class MapRun { 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; } @@ -301,10 +280,9 @@ export class MapRun { // 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); + // A run is cancelled through the DeviceJob so the same signal reaches the in-flight + // PUT; its one abort listener enters failRun. + if (this.#output && !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 @@ -362,13 +340,11 @@ export class MapRun { 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. + // No sink was available, so the bytes came across instead. The send 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); + this.#delivery = this.#deliverResidentMap(msg.bytes, msg.byteLength); void this.#delivery.catch(() => {}); break; case "done": @@ -388,7 +364,7 @@ export class MapRun { // 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") { + if (!this.#sinkClosed && this.#output) { this.#output.removeAbort(); this.#output.ctx.phase("finalizing"); this.#phase = "finalizing"; @@ -409,7 +385,7 @@ export class MapRun { // shared `output` after its cleanup finished. this.#phase = "finalizing"; await this.#cleanupTransientCells(); - if (this.#output?.kind === "device") { + if (this.#output) { if (!this.#output.result) { await this.#failRun(new Error("The device did not commit the assembled map.")); break; @@ -471,14 +447,13 @@ export class MapRun { `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."); + if (!this.#output) 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. */ + /** Send the verified one-file result without ever materialising an OPFS map in the tab + * heap: the PUT reads the Blob twice in bounded slices (CRC then transfer). */ async #deliverMap(blob: Blob, byteLength: number) { if (this.#sinkClosed) return; if (blob.size !== byteLength) { @@ -486,21 +461,14 @@ export class MapRun { `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; + if (!this.#output) throw new Error("The direct map destination was closed."); + const { sendMapBlob } = await import("../device/write"); + this.#output.result = await sendMapBlob(this.#output.client, blob, this.#runFileName, this.#output.ctx); } #settleDevice(result: PutResponse | unknown, failed = false) { const current = this.#output; - if (current?.kind !== "device" || current.settled) return; + if (!current || current.settled) return; current.settled = true; current.removeAbort(); if (failed) current.reject(result); @@ -587,11 +555,8 @@ export class MapRun { // 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; - } + if (owner.failing || owner.settled) return; + owner.failing = true; this.#activeRunId = 0; const controller = this.#abortCtl; this.#abortCtl = null; @@ -616,7 +581,7 @@ export class MapRun { 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(); + await this.#cleanupDirectOutput(); owner.releaseWork?.(); owner.releaseWork = null; this.#errorMessage = cause instanceof Error ? cause.message : String(cause); @@ -704,11 +669,8 @@ export class MapRun { 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 = []; @@ -719,7 +681,7 @@ export class MapRun { this.#cachedCells = 0; this.#cachedBytes = 0; this.#phase = "downloading"; - if (out.kind === "device") out.ctx.phase("downloading", l.totalBytes); + out.ctx.phase("downloading", l.totalBytes); const plan = planCells(resolution, store.catalog, indices, store.terrain, store.articles); const cells: WorkerCell[] = []; @@ -826,7 +788,7 @@ export class MapRun { }, onProgress: (p) => { this.#dlProgress = p; - if (out.kind === "device") out.ctx.progress(p.receivedBytes, p.totalBytes); + out.ctx.progress(p.receivedBytes, p.totalBytes); }, signal: runAbort.signal, }), @@ -852,7 +814,7 @@ export class MapRun { } this.#phase = "assembling"; - if (out.kind === "device") out.ctx.phase("assembling", 0); + out.ctx.phase("assembling", 0); this.#asmPhase = "open"; this.#asmPhaseStart = { open: performance.now() }; const req: AssembleWorkerRequest = { @@ -892,17 +854,6 @@ export class MapRun { 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. */ @@ -913,8 +864,7 @@ export class MapRun { ctx.signal.reason ?? new DOMException("cancelled", "AbortError"), device.runId ?? 0, ); - const device: DeviceOutput = { - kind: "device", + const device: Output = { client, ctx, resolve, @@ -943,7 +893,7 @@ export class MapRun { }); }); - readonly #refreshBlocked = $derived(this.#output?.kind === "device" || this.#phase === "finalizing"); + readonly #refreshBlocked = $derived(this.#output !== null || this.#phase === "finalizing"); /** Quiesce this catalog before a replacement can admit another assembly. */ async pauseForRefresh(): Promise<() => void> { @@ -957,24 +907,9 @@ export class MapRun { } 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); - } + // Assembly and PUT are one DeviceJob. Ask its controller to cancel: merely aborting the + // cell downloader would let a live PUT commit and only then paint the run as cancelled. + this.#output?.ctx.cancel(new DOMException("cancelled", "AbortError")); } retryEstimate(): void { diff --git a/builder/web/src/lib/device/flows.test.ts b/builder/web/src/lib/device/flows.test.ts index 708dd0e961..4ae0e8aec9 100644 --- a/builder/web/src/lib/device/flows.test.ts +++ b/builder/web/src/lib/device/flows.test.ts @@ -31,7 +31,7 @@ import { initConvert } from "../convert/bridge"; import { expectBytes } from "../../../test-support/bytes"; import { loadFlatDevice } from "../../../test-support/flat-device/load"; import { prepareRoute } from "./route"; -import { armUpdate, sendMapBlob, sendMapBytes, sendMapFile, sendRoute, stageFirmware } from "./write"; +import { armUpdate, sendMapBlob, sendMapBytes, sendRoute, stageFirmware } from "./write"; import type { JobContext, JobPhase } from "./progress"; function repoRoot(): string { @@ -131,9 +131,10 @@ describe("map upload from a file", () => { it("commits one object and reports the id the device assigned", async () => { await withDevice({}, async ({ client, device }) => { const bytes = syntheticBytes(200_000); - const file = new File([bytes], "grimsel-default.obcm"); + const map = new Blob([bytes]); + const name = "grimsel-default.obcm"; const ctx = context(); - const result = await sendMapFile(client, file, ctx); + const result = await sendMapBlob(client, map, name, ctx); expect(result.objectId).toBe(1n); expect(result.payloadLength).toBe(BigInt(bytes.length)); @@ -149,10 +150,11 @@ describe("map upload from a file", () => { it("replaces the selected map on a second send instead of accumulating another object", async () => { await withDevice({}, async ({ client, device }) => { const bytes = syntheticBytes(64 * 1024); - const file = new File([bytes], "grimsel-default.obcm"); - const first = await sendMapFile(client, file, context()); + const map = new Blob([bytes]); + const name = "grimsel-default.obcm"; + const first = await sendMapBlob(client, map, name, context()); const replacement = syntheticBytes(96 * 1024); - const second = await sendMapFile(client, new File([replacement], "monaco.obcm"), context()); + const second = await sendMapBlob(client, new Blob([replacement]), "monaco.obcm", context()); expect(second.objectId).toBe(first.objectId); expect(second.revision).toBe(first.revision + 1n); @@ -175,7 +177,7 @@ describe("map upload from a file", () => { device.seed({ kind: ObjectKind.Route, displayName: "not a map", bytes: syntheticBytes(512) }); const bytes = syntheticBytes(32 * 1024); - const result = await sendMapFile(client, new File([bytes], "replacement.obcm"), context()); + const result = await sendMapBlob(client, new Blob([bytes]), "replacement.obcm", context()); expect(result.objectId).toBe(active.objectId); expect(result.revision).toBe(active.revision + 1n); @@ -196,8 +198,9 @@ describe("map upload from a file", () => { // bytes before the old map can be retired. const oldBytes = syntheticBytes(64); const held = device.seed({ kind: ObjectKind.MapShard, displayName: "installed", bytes: oldBytes }); - const file = new File([syntheticBytes(256 * 1024)], "too-big.obcm"); - const failure = await sendMapFile(client, file, context()).catch((cause: unknown) => cause); + const map = new Blob([syntheticBytes(256 * 1024)]); + const name = "too-big.obcm"; + const failure = await sendMapBlob(client, map, name, context()).catch((cause: unknown) => cause); expect(failure).toBeInstanceOf(DeviceError); expect((failure as DeviceError).code).toBe("no-space"); expect((failure as DeviceError).refusal?.context).toBe(BigInt(256 * 1024)); @@ -209,7 +212,8 @@ describe("map upload from a file", () => { it("reports an unplug mid-transfer, and the next attempt is an ordinary one", async () => { const first = flatDevice({ packetSize: 4096, streamHighWaterMark: 8 * 1024 }); const bytes = syntheticBytes(2 * 1024 * 1024); - const file = new File([bytes], "big.obcm"); + const map = new Blob([bytes]); + const name = "big.obcm"; const ctx = context({ at: (done, phase) => { // Pull the cable a little way into the *send*, not the read: mid-stream is the @@ -217,7 +221,7 @@ describe("map upload from a file", () => { if (phase === "sending" && done > 256 * 1024) void first.link.device.close(); }, }); - const failure = await sendMapFile(first.client, file, ctx).catch((e: unknown) => e); + const failure = await sendMapBlob(first.client, map, name, ctx).catch((e: unknown) => e); expect(failure).toBeInstanceOf(DeviceError); expect((failure as DeviceError).code).toBe("link"); expect(first.device.entries, "a half-written map is never committed").toEqual([]); @@ -227,7 +231,7 @@ describe("map upload from a file", () => { // no repair. Any break before the commit leaves the card as if nothing had happened, and // transfers restart rather than resume. await withDevice({ packetSize: 4096 }, async ({ client, device }) => { - const result = await sendMapFile(client, file, context()); + const result = await sendMapBlob(client, map, name, context()); expect(result.payloadLength).toBe(BigInt(bytes.length)); expectBytes(device.payloadOf(result.objectId), bytes); }); @@ -239,7 +243,8 @@ describe("map upload from a file", () => { // and the retry is therefore not a special path, it is the first path again. await withDevice({ packetSize: 4096, streamHighWaterMark: 8 * 1024 }, async ({ client, device }) => { const bytes = syntheticBytes(1024 * 1024); - const file = new File([bytes], "cancelled.obcm"); + const map = new Blob([bytes]); + const name = "cancelled.obcm"; const oldBytes = syntheticBytes(4096); const installed = device.seed({ kind: ObjectKind.MapShard, displayName: "installed", bytes: oldBytes }); const controller = new AbortController(); @@ -252,11 +257,11 @@ describe("map upload from a file", () => { if (phase === "sending" && done > 128 * 1024) controller.abort(); }, }); - await expect(sendMapFile(client, file, ctx)).rejects.toMatchObject({ code: "aborted" }); + await expect(sendMapBlob(client, map, name, ctx)).rejects.toMatchObject({ code: "aborted" }); expect(device.entries).toEqual([installed]); expect(device.payloadOf(installed.objectId)).toEqual(oldBytes); - const result = await sendMapFile(client, file, context()); + const result = await sendMapBlob(client, map, name, context()); expect(result.objectId).toBe(installed.objectId); expect(result.revision).toBe(installed.revision + 1n); expectBytes(device.payloadOf(result.objectId), bytes); @@ -302,9 +307,10 @@ describe("map upload from a file", () => { // Three surfaces share one client and one device, which allows exactly one transfer at a // time, and the answer has to be a clean error rather than two interleaved objects. await withDevice({ packetSize: 4096, streamHighWaterMark: 8 * 1024 }, async ({ client }) => { - const file = new File([syntheticBytes(1024 * 1024)], "one.obcm"); - const running = sendMapFile(client, file, context()); - const second = sendMapFile(client, new File([syntheticBytes(4096)], "two.obcm"), context()).catch( + const map = new Blob([syntheticBytes(1024 * 1024)]); + const name = "one.obcm"; + const running = sendMapBlob(client, map, name, context()); + const second = sendMapBlob(client, new Blob([syntheticBytes(4096)]), "two.obcm", context()).catch( (e: unknown) => e, ); await running; diff --git a/builder/web/src/lib/device/job.svelte.test.ts b/builder/web/src/lib/device/job.svelte.test.ts deleted file mode 100644 index 53c2423344..0000000000 --- a/builder/web/src/lib/device/job.svelte.test.ts +++ /dev/null @@ -1,154 +0,0 @@ -/** - * The job slot: what the three surfaces render from. - * - * Two of these exist because driving the real UI found the bugs and the suite did not. `running` - * was a getter over a plain field, so the progress bar never appeared and the buttons never - * disabled — everything "worked", invisibly. And a write killed by an unplug reported itself into a - * component that unmounts the same instant, so the rider got a Connect button and no account of - * what happened to their upload. - */ - -import { describe, expect, it } from "vitest"; - -import { DeviceJob, jobRegistry } from "./job.svelte"; -import { deviceHolder } from "./session.svelte"; -import type { JobPhase } from "./progress"; - -const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); - -describe("DeviceJob", () => { - it("tracks phases, bytes and the finished sentence", async () => { - const job = new DeviceJob(); - const seen: JobPhase[] = []; - const running = job.run(async (ctx) => { - seen.push("reading"); - ctx.phase("sending", 1000); - ctx.progress(500, 1000); - expect(job.running).toBe(true); - expect(job.pct).toBe(50); - return 7; - }, (value) => `did ${value}`); - expect(job.running, "the slot is held synchronously, before the first await").toBe(true); - await running; - expect(seen).toEqual(["reading"]); - expect(job.phase).toBe("done"); - expect(job.result).toBe("did 7"); - expect(job.running).toBe(false); - }); - - it("refuses a second task while one is running", async () => { - const job = new DeviceJob(); - const first = job.run(async () => { - await settle(); - return 1; - }, () => "first"); - expect(await job.run(async () => 2, () => "second")).toBeNull(); - await first; - }); - - it("keeps a failure's code, not only its message", async () => { - const job = new DeviceJob(); - await job.run(async () => { - throw Object.assign(new Error("The device's catalog is full."), { code: "storage-full" }); - }, () => "unreachable"); - expect(job.phase).toBe("error"); - expect(job.errorCode).toBe("storage-full"); - expect(job.error).toContain("catalog is full"); - }); - - it("treats a cancel as a return to idle, not as an error", async () => { - const job = new DeviceJob(); - const running = job.run(async (ctx) => { - job.cancel(); - await settle(); - ctx.signal.throwIfAborted(); - return 1; - }, () => "unreachable"); - expect(await running).toBeNull(); - expect(job.phase).toBe("idle"); - expect(job.error).toBeNull(); - }); - - it("does not cancel host cleanup after a device commit", async () => { - const job = new DeviceJob(); - let release!: () => void; - const cleanup = new Promise((resolve) => (release = resolve)); - let signal: AbortSignal | null = null; - const running = job.run(async (ctx) => { - signal = ctx.signal; - ctx.phase("finalizing"); - await cleanup; - return 1; - }, () => "committed"); - - job.cancel(); - expect(signal!.aborted).toBe(false); - release(); - await running; - expect(job.phase).toBe("done"); - expect(job.result).toBe("committed"); - }); - - it("reports a lost link where it will still be on screen afterwards", async () => { - deviceHolder.interrupted = null; - const job = new DeviceJob(); - await job.run(async () => { - throw Object.assign(new Error("The device disconnected."), { code: "link" }); - }, () => "unreachable"); - // The surface that ran this unmounts the moment the device goes; the holder is what - // survives it, and the rider reads the sentence next to the Connect button. - expect(deviceHolder.interrupted).toContain("plug it back in"); - deviceHolder.interrupted = null; - }); -}); - -describe("jobRegistry", () => { - it("exposes a job only while it runs, labelled", async () => { - const job = new DeviceJob("map"); - expect(jobRegistry.active, "idle jobs are invisible").toBeNull(); - const running = job.run(async () => { - expect(jobRegistry.active).toBe(job); - expect(jobRegistry.active?.label).toBe("map"); - return 1; - }, () => "done"); - await running; - expect(jobRegistry.active).toBeNull(); - }); - - it("unregisters on failure and on cancel alike", async () => { - const failing = new DeviceJob("route"); - await failing.run(async () => { - throw new Error("no"); - }, () => "unreachable"); - expect(jobRegistry.active).toBeNull(); - - const cancelled = new DeviceJob("route"); - const running = cancelled.run(async (ctx) => { - cancelled.cancel(); - await settle(); - ctx.signal.throwIfAborted(); - return 1; - }, () => "unreachable"); - await running; - expect(jobRegistry.active).toBeNull(); - }); - - it("reads the first-registered job when two overlap", async () => { - const first = new DeviceJob("rides"); - const second = new DeviceJob("map"); - let release!: () => void; - const gate = new Promise((resolve) => (release = resolve)); - const a = first.run(async () => { - await gate; - return 1; - }, () => "a"); - const b = second.run(async () => { - await gate; - return 2; - }, () => "b"); - expect(jobRegistry.active).toBe(first); - release(); - await Promise.all([a, b]); - expect(jobRegistry.active).toBeNull(); - }); -}); diff --git a/builder/web/src/lib/device/job.svelte.ts b/builder/web/src/lib/device/job.svelte.ts deleted file mode 100644 index c9126f2f1f..0000000000 --- a/builder/web/src/lib/device/job.svelte.ts +++ /dev/null @@ -1,198 +0,0 @@ -/** - * One device write, followed on screen: phase, bytes, throughput, an honest estimate, and a Cancel - * that actually reaches the transport. - * - * All three flows run through this, because the interesting behaviour is identical in all three and - * only one of them is short. A large map is *minutes*, and a progress bar that only counts percent - * invites the rider to think something is stuck at 12%; a rate and a remaining time say what is - * actually happening. - * - * The rate is measured over a short trailing window rather than since the start, because the two - * phases of a transfer can run at different speeds. An average over the whole job can spend the - * first minute predicting a finish that never arrives. - */ - -import type { JobContext, JobPhase } from "./progress"; -import { deviceHolder } from "./session.svelte"; - -export type { JobContext, JobPhase }; - -/** How long a window the throughput estimate looks back over. */ -const RATE_WINDOW_MS = 4_000; - -/** - * A single job slot. - * - * One per surface (map, route, firmware), so the three can be described independently. The protocol - * client allows exactly one transfer at a time and enforces that itself; what this class guarantees - * is that *this* slot never runs two tasks at once. - */ -export class DeviceJob { - /** What this slot writes, for chrome that reports a transfer it does not own — one word, - * lowercase, reading naturally after "sending": "map", "route", "firmware", "rides". */ - readonly label: string; - - constructor(label = "transfer") { - this.label = label; - } - - phase = $state("idle"); - done = $state(0); - total = $state(0); - error = $state(null); - /** The failure's stable code where it had one. The message is for the rider; this is for the - * caller, which has to tell "the cable came out" from "the card is full" without reading - * English. */ - errorCode = $state(null); - /** A sentence for the successful case — what was written, and what it means. */ - result = $state(null); - /** Bytes per second over the last few seconds, or null before there is enough to say. */ - rate = $state(null); - - /** `$state` because {@link running} is read from the markup — a plain field would leave the - * progress bar and the disabled buttons frozen at whatever they were on first render. */ - private controller = $state(null); - /** `[timestamp, bytes]` samples inside the rate window. */ - private samples: Array<[number, number]> = []; - - get running(): boolean { - return this.controller !== null; - } - - get pct(): number { - return this.total > 0 ? Math.min(100, Math.round((this.done / this.total) * 100)) : 0; - } - - /** Seconds left at the current rate, or null when there is nothing honest to say yet. */ - get etaSeconds(): number | null { - if (!this.rate || this.total <= 0 || this.done >= this.total) return null; - return (this.total - this.done) / this.rate; - } - - /** - * Run `task`, holding this slot until it settles. - * - * Returns the task's value, or `null` if it failed or was cancelled — a caller that only wants to - * render the outcome reads {@link error} and never has to catch. A cancel is not an error: the - * job returns to `idle` with nothing said, because the rider already knows what they did. - */ - async run(task: (ctx: JobContext) => Promise, describe: (value: T) => string): Promise { - if (this.controller) return null; - const controller = new AbortController(); - this.controller = controller; - jobRegistry.add(this); - this.error = null; - this.errorCode = null; - this.result = null; - this.done = 0; - this.total = 0; - this.rate = null; - this.samples = []; - this.phase = "reading"; - try { - const value = await task({ - signal: controller.signal, - cancel: (reason) => - controller.abort(reason ?? new DOMException("cancelled by the rider", "AbortError")), - phase: (phase, total) => { - this.phase = phase; - if (total !== undefined) { - this.total = total; - this.done = 0; - } - this.samples = []; - this.rate = null; - }, - progress: (done, total) => this.sample(done, total), - }); - this.phase = "done"; - this.done = this.total; - this.result = describe(value); - return value; - } catch (cause) { - const code = (cause as { code?: unknown })?.code; - const errorCode = typeof code === "string" ? code : null; - // A physical disconnect can race the surface teardown that aborts this job. The - // transport's stable link cause is stronger evidence than the later local abort. - if (errorCode === "link") { - this.errorCode = errorCode; - this.phase = "error"; - this.error = cause instanceof Error ? cause.message : String(cause); - deviceHolder.noteInterrupted(); - } else if (controller.signal.aborted) { - this.phase = "idle"; - this.done = 0; - this.total = 0; - } else { - this.phase = "error"; - this.error = cause instanceof Error ? cause.message : String(cause); - this.errorCode = errorCode; - } - return null; - } finally { - this.controller = null; - this.rate = null; - jobRegistry.remove(this); - } - } - - /** Cancel the running task. Safe to call when nothing is running. */ - cancel(): void { - // `finalizing` starts only after the device's commit is durable. There is no transfer left - // to cancel, and aborting now would let surface teardown mislabel success as cancellation. - if (this.phase === "finalizing") return; - this.controller?.abort(new DOMException("cancelled by the rider", "AbortError")); - } - - /** Clear a finished job's outcome, so the surface goes back to offering the action. */ - reset(): void { - if (this.running) return; - this.phase = "idle"; - this.done = 0; - this.total = 0; - this.error = null; - this.result = null; - } - - private sample(done: number, total: number): void { - this.done = done; - this.total = total; - const now = Date.now(); - this.samples.push([now, done]); - while (this.samples.length > 1 && now - this.samples[0][0] > RATE_WINDOW_MS) this.samples.shift(); - const [firstAt, firstBytes] = this.samples[0]; - const elapsed = now - firstAt; - // Under a second of history says nothing useful, and a rate that jumps around is worse than - // no rate at all — the number is there to set an expectation, not to be watched. - this.rate = elapsed >= 1_000 ? ((done - firstBytes) * 1000) / elapsed : this.rate; - } -} - -/** - * Every job that is running right now, so chrome outside the surfaces — the header's device chip — - * can report a transfer without owning it. Jobs register per *run*, not per instance: an idle - * `DeviceJob` created in a component's script block is invisible here, and one abandoned by an - * unmount mid-run still unregisters, because `run()`'s `finally` is what removes it. - * - * A list rather than a single slot, deliberately: the client allows one *transfer* at a time, but a - * job may briefly overlap another during its non-transfer phases (a map send filling its scratch - * file while a pull settles). First registered wins the readout; precision beyond that buys nothing. - */ -class JobRegistry { - private jobs = $state([]); - - add(job: DeviceJob): void { - this.jobs = [...this.jobs, job]; - } - - remove(job: DeviceJob): void { - this.jobs = this.jobs.filter((j) => j !== job); - } - - /** The job the readout shows, or null when nothing is running. */ - get active(): DeviceJob | null { - return this.jobs[0] ?? null; - } -} - -export const jobRegistry = new JobRegistry(); diff --git a/builder/web/src/lib/device/rides.test.ts b/builder/web/src/lib/device/rides.test.ts deleted file mode 100644 index bf7ab68d25..0000000000 --- a/builder/web/src/lib/device/rides.test.ts +++ /dev/null @@ -1,578 +0,0 @@ -/** - * Web ride export, end to end against the simulated device. - * - * Two things are being decided here, and only one of them is "does the flow work". - * - * The first is **byte identity**: the GPX a visitor saves has to be the file the device itself would - * have written. The pinned pair is `specs/vectors/ride-v6.bin` → `track-export.gpx`, produced by the - * real `obc_route::track_to_gpx`, and the export path has to land on those exact bytes after a full - * round trip through the wire's ride object — with one documented exception the wire format makes - * unavoidable, asserted as *the only* exception rather than waved at. - * - * The second is **that nothing happened to the device**, and that claim is structural rather than - * behavioural: the only two things a peer can do to an object are a `PUT` and a `REMOVE`, and - * {@link rideAccess} hands the export path an object that has neither, at compile time *and* at - * runtime. - */ - -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 { loadFlatDevice } from "../../../test-support/flat-device/load"; -import { DeviceError, FlatStoreClient } from "../usb/client"; -import { FlatDevice, controlCeilingFor, flatDevice, type FlatDeviceOptions } from "../usb/flat-device"; -import { loopbackLink, type LoopbackOptions } from "../usb/loopback"; -import { decodeRideObject, encodeRideObject, type RideObject, type RidePoint } from "../usb/objects"; -import type { BytePipe, DeviceLink } from "../usb/pipe"; -import { EntryFlags, ObjectKind, type CatalogEntry } from "../usb/protocol"; -import type { JobContext, JobPhase } from "./progress"; -import { - exportRide, - recordedRides, - rideAccess, - rideDate, - rideFilename, - rideKey, - rideScope, - scopeKey, - type RideSource, -} from "./rides"; - -/** A card identity for the tests that only need one to compare against. */ -const CARD = "8f2c41d96b074ea3b1559c207de83466"; - -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 from " + import.meta.url); -} - -const ROOT = repoRoot(); -const vector = (name: string) => new Uint8Array(readFileSync(join(ROOT, "specs/vectors", name))); - -/** The name `track-export.gpx` was produced with (`obc_vectors::TRACK_NAME`). */ -const TRACK_NAME = "Schauinsland & back"; - -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(); -}); - -const TRACK_RECORD_LEN = 20; - -/** - * Build a ride around the exact checked-in recorded samples. Finish appends only the footer. - */ -function rideFromTrackLog(log: Uint8Array, name: string, startTime: number): RideObject { - const view = new DataView(log.buffer, log.byteOffset, log.byteLength); - const total = Math.floor(log.length / TRACK_RECORD_LEN); // a trailing partial record is ignored - const points: RidePoint[] = []; - for (let i = 0; i < total; i++) { - const at = i * TRACK_RECORD_LEN; - const hr = log[at + 16]; - const cadence = log[at + 17]; - const power = view.getUint16(at + 18, true); - points.push({ - lonMicrodegrees: view.getInt32(at, true), - latMicrodegrees: view.getInt32(at + 4, true), - elevationM: view.getInt16(at + 8, true), - segmentStart: (view.getUint16(at + 10, true) & 1) !== 0, - tMs: view.getUint32(at + 12, true), - hrBpm: hr === 0xff ? null : hr, - cadenceRpm: cadence === 0xff ? null : cadence, - powerW: power === 0xffff ? null : power, - }); - } - return { - version: 6, - isDemo: false, - effortLimits: { maxHrBpm: null, ftpW: null }, - name, - startTime, - distanceM: 4210, - movingTimeS: 1_284, - avgSpeedCms: 328, - climbM: 118, - descentM: 118, - avgHr: 135, - maxHr: 138, - avgCadence: 78, - avgPower: 205, - maxPower: 240, - energyKj: 263, - bikeType: 0, - trip: null, - points, - }; -} - -/** A long ride, for the paths that need a transfer still running when something goes wrong. */ -function longRide(points: number): RideObject { - const list: RidePoint[] = []; - for (let i = 0; i < points; i++) { - list.push({ - tMs: i * 1000, - latMicrodegrees: 47_995_000 + i * 10, - lonMicrodegrees: 7_842_000 + i * 10, - elevationM: 300 + (i % 200), - segmentStart: i === 0, - hrBpm: 120 + (i % 40), - cadenceRpm: 80, - powerW: 200, - }); - } - return { - version: 6, - isDemo: false, - effortLimits: { maxHrBpm: null, ftpW: null }, - name: "Long Way Round", - startTime: 1_783_598_400, - distanceM: points * 8, - movingTimeS: points, - avgSpeedCms: 800, - climbM: 900, - descentM: 900, - avgHr: 140, - maxHr: 160, - avgCadence: 80, - avgPower: 200, - maxPower: 400, - energyKj: points / 5, - bikeType: 0, - trip: null, - points: list, - }; -} - -interface Watched extends JobContext { - readonly phases: JobPhase[]; - readonly last: [number, number]; -} - -function context(options: { signal?: AbortSignal; at?: (done: number, phase: JobPhase) => void } = {}): Watched { - const phases: JobPhase[] = []; - let phase: JobPhase = "idle"; - let last: [number, number] = [0, 0]; - return { - signal: options.signal ?? new AbortController().signal, - cancel() {}, - phases, - get last() { - return last; - }, - phase(next) { - phase = next; - phases.push(next); - }, - progress(done, total) { - last = [done, total]; - options.at?.(done, phase); - }, - }; -} - -/** A device with seeded rides, and the read-only handle the export path gets. */ -function deviceWith(rides: RideObject[], options: LoopbackOptions & FlatDeviceOptions = {}) { - const rig = flatDevice(options); - // The store assigns the ids; a test names a ride by the entry it got back. - const entries = rides.map((ride) => - rig.device.seed({ kind: ObjectKind.Ride, displayName: ride.name, bytes: encodeRideObject(ride) }), - ); - return { ...rig, entries, source: rideAccess(rig.client) }; -} - -describe("the exported GPX", () => { - it("reproduces the native exporter byte-for-byte, pulled from the device", async () => { - const ride = { ...decodeRideObject(vector("ride-v6.bin")), name: TRACK_NAME }; - const { entries, source, close } = deviceWith([ride]); - try { - // The catalog is what a rider picks from, so the export starts where they do. - const listed = await source.listRides(); - expect(listed.map((entry) => entry.objectId)).toEqual([entries[0].objectId]); - - const exported = await exportRide(source, listed[0], context()); - const expected = new TextDecoder().decode(vector("track-export.gpx")); - expect(exported.gpx).toBe(expected); - expect(exported.points).toBe(3); - expect(BigInt(exported.bytes)).toBe(entries[0].payloadLength); - } finally { - await close(); - } - }); - - it("is UTF-8 bytes, so the saved file is what was compared", async () => { - // The comparison above is on a string; what reaches a Blob is bytes. An em dash or a - // non-ASCII ride name is the case where those two stop agreeing if anything re-encodes. - const log = vector("track-log.obct"); - const ride = rideFromTrackLog(log, "Höhenweg — Schauinsland", 1_783_598_400); - const { source, close } = deviceWith([ride]); - try { - const exported = await exportRide(source, (await source.listRides())[0], context()); - const bytes = new TextEncoder().encode(exported.gpx); - expect(new TextDecoder("utf-8", { fatal: true }).decode(bytes)).toBe(exported.gpx); - expect(exported.gpx).toContain("Höhenweg — Schauinsland"); - } finally { - await close(); - } - }); -}); - -describe("the ride object", () => { - it("decodes and re-encodes the cross-language vector byte-for-byte", () => { - const bytes = vector("ride-v6.bin"); - const ride = decodeRideObject(bytes); - expect(ride).toMatchObject({ - version: 6, - isDemo: true, - name: "Sensor Ride", - startTime: 1_751_460_000, - distanceM: 12_345, - movingTimeS: 3_600, - avgSpeedCms: 343, - climbM: 120, - descentM: 95, - avgHr: 142, - maxHr: 176, - avgCadence: 85, - avgPower: 210, - maxPower: 480, - energyKj: 756, - bikeType: 1, - trip: { key: 0x0123_4567_89ab_cdefn, dayIndex: 1, dayCount: 3, name: "Alpen Traverse" }, - effortLimits: { maxHrBpm: 185, ftpW: 250 }, - }); - expect(ride.points).toHaveLength(3); - expect(ride.points[0]).toMatchObject({ - lonMicrodegrees: 7_800_000, - latMicrodegrees: 48_000_000, - elevationM: 214, - segmentStart: true, - tMs: 0, - hrBpm: 140, - cadenceRpm: 84, - powerW: 205, - }); - expect(encodeRideObject(ride)).toEqual(bytes); - }); - - it("keeps ordinary rides unmarked and rejects reserved footer flags", () => { - const bytes = encodeRideObject(longRide(1)); - const flags = bytes.length - 154 + 33; - expect(bytes[flags]).toBe(0); - expect(decodeRideObject(bytes).isDemo).toBe(false); - for (const reserved of [2, 0x80, 0xff]) { - bytes[flags] = reserved; - expect(() => decodeRideObject(bytes)).toThrow("non-canonical summary footer"); - } - }); - - it("keeps a zero elevation as the device's 'no barometer yet' value", () => { - const ride: RideObject = { - ...longRide(1), - points: [{ tMs: 0, latMicrodegrees: 47_995_000, lonMicrodegrees: 7_842_000, elevationM: 0, segmentStart: true, hrBpm: null, cadenceRpm: null, powerW: null }], - }; - const bytes = encodeRideObject(ride); - expect(new DataView(bytes.buffer).getInt16(8, true)).toBe(0); - }); -}); - -// The browser does not send a possession acknowledgement on the cable: an acknowledgement changes no -// object and so has no store meaning. It keeps the BLE control surface it had. What survives is the -// narrowing itself, which is still load-bearing because `PUT` and `REMOVE` *are* on this cable. - -describe("what the export path can reach", () => { - it("hands the export path a device it cannot write to", async () => { - const { client, source, close } = deviceWith([]); - try { - expect(Object.keys(source).sort()).toEqual(["downloadRide", "listRides"]); - for (const forbidden of ["put", "remove", "arm", "cancel", "close", "get", "list"]) { - expect(source, `\`${forbidden}\` must not be reachable from the export path`).not.toHaveProperty( - forbidden, - ); - } - // A type is a compile-time fact and a cast defeats it, so the narrowing is real at - // runtime too: the object does not *have* the method, and the cast throws. - expect(() => (source as unknown as FlatStoreClient).remove({ objectId: 1n, revision: 1n })).toThrow( - TypeError, - ); - expect(Object.isFrozen(source), "and it cannot be grown back").toBe(true); - // The client itself still has it — this is a narrowing at the seam, not a removal. - expect(typeof client.remove).toBe("function"); - // A `FlatStoreClient` is deliberately *not* a `RideSource` — `downloadRide` exists - // nowhere else — so `rideAccess` is the only way to obtain one, and there is no - // "pass the client straight in" shortcut for a call site to take. - const notASource: Partial = client as unknown as Partial; - expect(notASource.downloadRide).toBeUndefined(); - } finally { - await close(); - } - }); -}); - -describe("when the export cannot finish", () => { - /** A host link that flips one byte on its way in, once armed — a wire error the device's declared - * whole-payload CRC has to catch before anything is handed to a rider. */ - function corruptible(link: DeviceLink): { link: DeviceLink; arm: () => void } { - const stream = link.stream; - let armed = false; - let flipped = false; - const wrapped: BytePipe = { - transport: stream.transport, - get open() { - return stream.open; - }, - async read(signal) { - const slice = await stream.read(signal); - if (!armed || flipped || slice.length === 0) return slice; - flipped = true; - const damaged = slice.slice(); - // The middle byte lies in the payload; the record's tail can be alignment padding. - damaged[damaged.length >> 1] ^= 0xff; - return damaged; - }, - write: (bytes, signal) => stream.write(bytes, signal), - reset: () => stream.reset(), - close: () => stream.close(), - }; - return { - link: { control: link.control, stream: wrapped, vendorIn: link.vendorIn, close: () => link.close() }, - arm: () => (armed = true), - }; - } - - it("refuses to offer a file whose bytes did not survive the cable", async () => { - const raw = loopbackLink(); - const device = new FlatDevice(raw.device); - void device.run(); - const wire = corruptible(raw.host); - const client = new FlatStoreClient(wire.link); - const ride = rideFromTrackLog(vector("track-log.obct"), TRACK_NAME, 1_783_598_400); - device.seed({ kind: ObjectKind.Ride, displayName: ride.name, bytes: encodeRideObject(ride) }); - try { - const source = rideAccess(client); - const entry = (await source.listRides())[0]; - wire.arm(); // the catalog arrived intact; damage the ride itself - const failure = await exportRide(source, entry, context()).catch((e: unknown) => e); - expect(failure).toBeInstanceOf(DeviceError); - expect((failure as DeviceError).code).toBe("checksum"); - expect((failure as DeviceError).message).toMatch(/checksum/i); - } finally { - device.stop(); - await client.close(); - await raw.device.close(); - } - }); - - it("reports an unplug mid-pull instead of leaving a spinner", async () => { - // 30 000 points is about 540 KB on the wire — long enough that the cable can be pulled - // while bytes are still moving, which is the state a stuck spinner comes from. - const harness = deviceWith([longRide(30_000)], { packetSize: 4096, streamHighWaterMark: 8 * 1024 }); - const ctx = context({ - at: (done, phase) => { - if (phase === "downloading" && done > 64 * 1024) void harness.link.device.close(); - }, - }); - const failure = await exportRide(harness.source, harness.entries[0], ctx).catch((e: unknown) => e); - expect(failure).toBeInstanceOf(DeviceError); - expect((failure as DeviceError).code).toBe("link"); - expect(ctx.phases).toEqual(["downloading"]); // it never reached the conversion - await harness.close(); - }, 30_000); - - it("cancels mid-pull, and the next export on the same link is an ordinary one", async () => { - const harness = deviceWith([longRide(30_000)], { packetSize: 4096, streamHighWaterMark: 8 * 1024 }); - const controller = new AbortController(); - try { - // Cancelled from inside the progress callback, not after a timer: the loopback moves - // half a megabyte in microtasks, so a wall-clock delay races the transfer it interrupts. - const ctx = context({ - signal: controller.signal, - at: (done) => { - if (done > 64 * 1024) controller.abort(); - }, - }); - await expect(exportRide(harness.source, harness.entries[0], ctx)).rejects.toMatchObject({ - code: "aborted", - }); - // The cancel is bilateral, so the device released its transfer slot while this side reset - // its channel — the retry is the first path again, not a repair path. - const again = await exportRide(harness.source, harness.entries[0], context()); - expect(again.points).toBe(30_000); - } finally { - await harness.close(); - } - }, 60_000); - - it("says the ride is gone when it was deleted on the device between listing and exporting", async () => { - const ride = rideFromTrackLog(vector("track-log.obct"), TRACK_NAME, 1_783_598_400); - const { source, entries, close } = deviceWith([ride]); - try { - const stale: CatalogEntry = { ...entries[0], objectId: 99n }; - const failure = await exportRide(source, stale, context()).catch((e: unknown) => e); - expect((failure as DeviceError).code).toBe("not-found"); - } finally { - await close(); - } - }); - - it("is refused by the device for a ride it is still recording", async () => { - // A `RECORDING` entry's length and CRC are zero until the commit that ends it, so serving one - // would report success over an empty payload. `recordedRides` is the filter that keeps a - // caller away from it; this pins that the device refuses anyway. - const { device, source, close } = deviceWith([]); - try { - const live = device.seed({ kind: ObjectKind.Ride, displayName: "In progress", flags: EntryFlags.Recording }); - const failure = await exportRide(source, live, context()).catch((e: unknown) => e); - expect(failure).toBeInstanceOf(DeviceError); - expect((failure as DeviceError).code).toBe("invalid-request"); - } finally { - await close(); - } - }); - - it("tells 'this page is behind the device' from 'the transfer broke'", async () => { - // A ride object version this build does not decode arrives with a *matching* CRC — the - // bytes are fine, the two ends disagree about the layout. Reporting that as a transfer - // failure would send the rider to re-plug a cable that is working. - const ride = rideFromTrackLog(vector("track-log.obct"), TRACK_NAME, 1_783_598_400); - const { device, source, close } = deviceWith([]); - try { - const future = encodeRideObject(ride); - future[future.length - 150] = 7; - device.seed({ kind: ObjectKind.Ride, displayName: ride.name, bytes: future }); - const failure = await exportRide(source, (await source.listRides())[0], context()).catch( - (e: unknown) => e, - ); - expect(failure).toMatchObject({ name: "RideExportError", code: "unreadable-ride" }); - expect((failure as Error).message).toMatch(/newer firmware/); - } finally { - await close(); - } - }); - - it("explains an empty ride rather than failing inside the converter", async () => { - const { source, close } = deviceWith([{ ...longRide(1), points: [] }]); - try { - const failure = await exportRide(source, (await source.listRides())[0], context()).catch( - (e: unknown) => e, - ); - expect(failure).toMatchObject({ name: "RideExportError", code: "empty-ride" }); - expect((failure as Error).message).toMatch(/no recorded points/); - } finally { - await close(); - } - }); -}); - -describe("listing", () => { - it("pages the whole catalog, because §3.3 drops nothing", async () => { - // The listing pages: the client walks the `(ObjectId, Revision)` cursor to the end, so a page - // size small enough to force three round trips must still produce every ride. - const harness = deviceWith([], { controlCeiling: controlCeilingFor(2) }); - try { - const ride = rideFromTrackLog(vector("track-log.obct"), TRACK_NAME, 1_783_598_400); - const bytes = encodeRideObject(ride); - const seeded = [1, 2, 3, 4, 5].map(() => - harness.device.seed({ kind: ObjectKind.Ride, displayName: ride.name, bytes }), - ); - const listed = await harness.source.listRides(); - expect(listed.map((entry) => entry.objectId)).toEqual(seeded.map((entry) => entry.objectId)); - } finally { - await harness.close(); - } - }); - - it("offers every ride except the one being recorded", async () => { - const harness = deviceWith([]); - try { - const ride = rideFromTrackLog(vector("track-log.obct"), TRACK_NAME, 1_783_598_400); - const done = harness.device.seed({ kind: ObjectKind.Ride, bytes: encodeRideObject(ride) }); - const live = harness.device.seed({ kind: ObjectKind.Ride, flags: EntryFlags.Recording }); - const listed = await harness.source.listRides(); - expect(listed.map((entry) => entry.objectId), "the listing itself hides nothing").toEqual([ - done.objectId, - live.objectId, - ]); - expect(recordedRides(listed).map((entry) => entry.objectId)).toEqual([done.objectId]); - } finally { - await harness.close(); - } - }); -}); - -describe("ride identity", () => { - it("keys the complete card identity and decimal u64 object id", () => { - const before = { serial: "OBC-24-000317", storeId: "a1b2c3d4000000000000000000000000" }; - const after = { ...before, storeId: "a1b2c3d4000000000000000000000001" }; - expect(rideKey(before, 4n)).not.toBe(rideKey(after, 4n)); - expect(scopeKey(before)).not.toBe(scopeKey(after)); - for (const id of [65536n, 9007199254740993n, 18446744073709551615n]) { - expect(rideKey(before, id)).toBe(`OBC-24-000317:a1b2c3d4000000000000000000000000:${id}`); - } - expect(scopeKey({ serial: "x", storeId: null })).not.toBe( - scopeKey({ serial: "x", storeId: "00000000000000000000000000000000" }), - ); - }); - - it("takes the full StoreId and device serial", () => { - const info = { firmwareRevision: "0.4.0", hardwareRevision: "obc-lm20-r1", serialNumber: "AABB" }; - expect(rideScope(info, { storeId: CARD, commitSequence: 3n })).toEqual({ - serial: "AABB", - storeId: CARD, - }); - expect(rideScope(info, null)).toEqual({ serial: "AABB", storeId: null }); - expect(rideScope(null, null)).toEqual({ serial: "", storeId: null }); - }); - - it("names the file by date then ride, taking the date from the payload", () => { - // An 88-byte catalog entry is id, revision, length, CRC, kind, flags and a display name — - // there is no start time in it. So a caller naming a file before it has downloaded the ride - // gets the name alone, which is the honest half rather than a fabricated day. - const entry: CatalogEntry = { - objectId: 4n, - revision: 1n, - payloadLength: 140n, - payloadCrc32: 0, - kind: ObjectKind.Ride, - flags: 0, - displayName: TRACK_NAME, - }; - const ride = { ...longRide(1), name: TRACK_NAME, startTime: 1_783_598_400 }; - expect(rideFilename(entry)).toBe("schauinsland-back.gpx"); - expect(rideFilename(entry, ride)).toBe("2026-07-09-schauinsland-back.gpx"); - expect(rideFilename(entry, { ...ride, startTime: 0 })).toBe("schauinsland-back.gpx"); - expect(rideFilename({ ...entry, displayName: "" }, { ...ride, name: "" })).toBe("2026-07-09-ride-4.gpx"); - // UTC, not the visitor's zone: the ride object's start_time is UTC seconds, and a local - // rendering would file a late ride under the wrong day west of Greenwich. - expect(rideDate(1_783_598_400)).toBe("2026-07-09"); - expect(rideDate(0)).toBeNull(); - }); -}); - -/** The panel's flow, once: list, pick, export — with the phases a progress bar renders. */ -describe("the panel's flow", () => { - it("reports downloading then converting, and ends with a file to save", async () => { - const ride = rideFromTrackLog(vector("track-log.obct"), TRACK_NAME, 1_783_598_400); - const { source, close } = deviceWith([ride]); - try { - const ctx = context(); - const listed = await source.listRides(); - const exported = await exportRide(source, listed[0], ctx); - expect(ctx.phases).toEqual(["downloading", "converting"]); - expect(exported.filename).toBe("2026-07-09-schauinsland-back.gpx"); - expect(exported.gpx).toContain("; - downloadRide(entry: CatalogEntry, options?: TransferOptions): Promise; -} - -/** - * The read-only view of a client that the export path is handed. - * - * The narrowing is real at runtime as well as in the type: the returned object owns two bound - * functions and nothing else, so a cast back to `FlatStoreClient` throws rather than quietly - * working. Frozen so it cannot be grown in place either. - */ -export function rideAccess(client: FlatStoreClient): RideSource { - return Object.freeze({ - listRides: async (signal?: AbortSignal) => - (await client.list({ kind: ObjectKind.Ride, signal })).entries, - // The entry's own `(ObjectId, Revision)` pair rather than the head, so a listing and the - // download that follows it name the same bytes even if the card moved in between. The - // entry's length rides along as the progress bar's denominator: the answer only states one - // at the end, and a ride arriving with no total would report nothing until it was over. - downloadRide: async (entry: CatalogEntry, options?: TransferOptions) => - ( - await client.get( - { objectId: entry.objectId, revision: entry.revision }, - { ...options, expectedLength: Number(entry.payloadLength) }, - ) - ).bytes, - }); -} - -/** - * The rides a client may actually fetch: everything the catalog holds except what is being recorded. - * - * A `GET` of an entry carrying `RECORDING` is refused, because the store has not committed its - * length or CRC yet. Filtering here is not politeness, it is the only listing a caller can act on. - */ -export function recordedRides(entries: readonly CatalogEntry[]): CatalogEntry[] { - return entries.filter((entry) => (entry.flags & EntryFlags.Recording) === 0); -} - -/** The device and full card identity. A missing card has no usable scope. */ -export interface RideScope { - readonly serial: string; - readonly storeId: string | null; -} - -/** Identity from the device information and the first catalog page. */ -export function rideScope(info: DeviceInfo | null, store: StoreIdentity | null): RideScope { - return { serial: info?.serialNumber ?? "", storeId: store?.storeId ?? null }; -} - -/** Changes when either the device or its card changes. */ -export function scopeKey(scope: RideScope): string { - return `${scope.serial}:${scope.storeId ?? "no-store"}`; -} - -/** 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}`; -} - -/** - * Why an export failed on this side of the wire. Transport and conversion failures keep their own - * codes; this covers what only a ride can be. - * - * - `empty-ride` — a recording with no points, usually stopped before the first fix. - * - `unreadable-ride` — the object arrived intact and this build cannot decode it. In practice that - * means firmware newer than the page, which must not be reported as a broken transfer. - */ -export type RideExportErrorCode = "empty-ride" | "unreadable-ride"; - -export class RideExportError extends Error { - readonly code: RideExportErrorCode; - - constructor(code: RideExportErrorCode, message: string, options?: { cause?: unknown }) { - super(message, options); - this.name = "RideExportError"; - this.code = code; - } -} - -function describe(cause: unknown): string { - return cause instanceof Error ? cause.message : String(cause); -} - -/** A ride, converted and ready to hand to the browser. Nothing here is written anywhere by this - * module — the caller saves it, or does not. */ -interface ExportedRide { - /** What the file should be called in a Downloads folder. */ - readonly filename: string; - /** The GPX 1.1 document, exactly as the native exporter would have written it. */ - readonly gpx: string; - /** Points in the track — what the rider is actually getting. */ - readonly points: number; - /** Bytes pulled off the device (the ride object, not the GPX). */ - readonly bytes: number; -} - -/** - * Pull one ride and convert it to GPX. The device is not touched in any other way. - * - * The CRC is not this function's job to check and is checked all the same: the client verifies the - * whole-payload CRC before returning, so there is no path from a corrupt transfer to a file offered - * to the rider. - */ -export async function exportRide(source: RideSource, entry: CatalogEntry, ctx: JobContext): Promise { - ctx.phase("downloading", Number(entry.payloadLength)); - const bytes = await source.downloadRide(entry, { - signal: ctx.signal, - onProgress: (done, total) => ctx.progress(done, total), - }); - - ctx.phase("converting", bytes.length); - // The bytes are known good — `download` verified the whole-object CRC — so a decode failure here - // is a *format* disagreement, not a broken transfer, and the rider needs the other sentence: - // this page is behind the device. - let ride: RideObject; - try { - ride = decodeRideObject(bytes); - } catch (cause) { - throw new RideExportError( - "unreadable-ride", - `The ride arrived intact but this page cannot read it (${describe(cause)}). That usually ` + - "means the device is running newer firmware than this page — reload and try again.", - { cause }, - ); - } - if (ride.points.length === 0) { - throw new RideExportError( - "empty-ride", - "That ride has no recorded points — there is nothing to put in a GPX file. It was " + - "probably stopped before the device had a fix.", - ); - } - const gpx = await trackToGpx(bytes, ride.name); - ctx.progress(bytes.length, bytes.length); - return { filename: rideFilename(entry, ride), gpx, points: ride.points.length, bytes: bytes.length }; -} - -/** - * What the saved file is called: the ride's start date, then its name. - * - * The date leads because a Downloads folder sorts by name and rides are read in order; the name - * follows because the rider chose it. The date is formatted in **UTC**, because the ride object's - * `start_time` is UTC seconds and rendering it locally would put a late evening ride on the wrong - * day for anyone west of Greenwich. A device that has never had a trusted clock reports `0` and - * gets no date at all rather than 1970. - */ -export function rideFilename(entry: CatalogEntry, ride?: RideObject): string { - const name = slug(ride?.name || entry.displayName) || `ride-${entry.objectId}`; - // The start date comes from the ride **payload**, because a `LIST` entry does not carry one. A - // caller naming a file before it has downloaded the ride gets the name alone. - const date = rideDate(ride?.startTime ?? 0); - return `${date ? `${date}-` : ""}${name}.gpx`; -} - -/** The ride's start day as `YYYY-MM-DD` in UTC, or null when the device's clock was never set. */ -export function rideDate(startTime: number): string | null { - if (!startTime) return null; - return new Date(startTime * 1000).toISOString().slice(0, 10); -} - -/** A filename-safe form of a ride name: ASCII-ish, no separators, no runs of punctuation. */ -function slug(name: string): string { - return name - .normalize("NFKD") - .replace(/[^A-Za-z0-9]+/g, "-") - .replace(/^-+|-+$/g, "") - .slice(0, 48) - .toLowerCase(); -} - -/** A ride's moving time as `h:mm` / `m:ss` — the shape a rider reads on a computer, not prose. */ -export function rideDuration(seconds: number): string { - const hours = Math.floor(seconds / 3600); - const minutes = Math.floor((seconds % 3600) / 60); - if (hours > 0) return `${hours}:${String(minutes).padStart(2, "0")} h`; - return `${minutes}:${String(Math.floor(seconds % 60)).padStart(2, "0")} min`; -} - -/** A ride's distance in kilometres, at the precision the figure deserves. */ -export function rideDistance(metres: number): string { - return `${(metres / 1000).toFixed(1)} km`; -} diff --git a/builder/web/src/lib/device/write.ts b/builder/web/src/lib/device/write.ts index 08285eaaf4..2b5e0c6886 100644 --- a/builder/web/src/lib/device/write.ts +++ b/builder/web/src/lib/device/write.ts @@ -50,10 +50,10 @@ export function displayName(name: string, fallback: string): string { // with the transport that pays for it: `DEFAULT_BATCH_BYTES` / `UPLOAD_WINDOW` in `../usb/client`. /** - * Send a `.obcm` Blob, either selected by the rider or produced by the assembler. + * Send the `.obcm` Blob that the assembler built. * - * No second staging copy: a picked `File` and the assembler's Blob are read twice in bounded chunks, - * once for the CRC and once to send. That is what `blobSource` is for. + * No second staging copy: the Blob is read twice in bounded chunks, once for the CRC and once to + * send. That is what `blobSource` is for. * * Replaces the map the device will select: the active (non-retained) `MapShard` with the lowest * `ObjectId`. That is the firmware's deterministic selection rule, so a second send moves the map the @@ -147,11 +147,6 @@ async function sendMapSource( ); } -/** Send a `.obcm` the rider selected from disk. */ -export function sendMapFile(client: FlatStoreClient, file: File, ctx: JobContext): Promise { - return sendMapBlob(client, file, file.name, ctx); -} - /** * Send a converted route. * diff --git a/builder/web/src/lib/palette.ts b/builder/web/src/lib/palette.ts deleted file mode 100644 index f112e9cde7..0000000000 --- a/builder/web/src/lib/palette.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { platform, type Palette } from "./platform"; - -export type { Palette }; - -// An empty grid makes the popover fall back to the OS color picker, which is -// also the right answer on a host that serves no palette at all. -const OS_PICKER: Palette = { columns: 8, colors: [] }; - -let cached: Promise | null = null; - -/** - * The device's 64-color gamut for the picker grid (fetched once, shared). - * - * The palette is present exactly on the maintainer editor host, and the color - * control that calls this sits inside the editor's code-split chunk — so on - * every host that can reach this module the call is there. The null arm is - * unreachable rather than a real fallback path, and takes the OS picker instead - * of throwing because a missing swatch grid is not worth failing a render over. - */ -export function getPalette(): Promise { - const fetchPalette = platform.styleEditor?.palette; - cached ??= fetchPalette - ? fetchPalette() - .then((p) => ({ columns: p.columns > 0 ? p.columns : 8, colors: p.colors ?? [] })) - .catch(() => OS_PICKER) - : Promise.resolve(OS_PICKER); - return cached; -} diff --git a/builder/web/src/lib/platform/bundle.test.ts b/builder/web/src/lib/platform/bundle.test.ts index 643e23cbd8..baf1dbe060 100644 --- a/builder/web/src/lib/platform/bundle.test.ts +++ b/builder/web/src/lib/platform/bundle.test.ts @@ -2,8 +2,7 @@ // Vite actually emits is asserted here, against what Rollup put in the emitted // output rather than against source imports or a grep of them. // -// One file, because Vitest isolates by file and not by test. Two builds, -// because `web` and `production` (the dev host) are two different module graphs. +// One file, because Vitest isolates by file and not by test: the product is built once. import { build } from "vite"; import { describe, expect, it } from "vitest"; @@ -61,12 +60,10 @@ function product(mode: string, env: Record = {}): Promise return next; } -/** The static web tier as `.github/workflows/deploy-site.yml` builds it, and the - * maintainer dev host. `VITE_SITE_BASE` only sets the link - * prefix in `lib/constants.ts`, so the deployed build stands for `npm run build:web` - * too. */ -const web = () => product("web", { VITE_SITE_BASE: "../" }); -const dev = () => product("production"); +/** The product as `.github/workflows/deploy-site.yml` builds it. `VITE_SITE_BASE` only sets the + * link prefix in `lib/constants.ts`, so the deployed build stands for `npm run build` too. + * Vitest sets `NODE_ENV=test`, which would make it a development build with the pretend device. */ +const web = () => product("planner", { VITE_SITE_BASE: "../", NODE_ENV: "production" }); /** Every source module in every emitted chunk of one product, and only the ones * Rollup put in an entry chunk. */ @@ -87,45 +84,6 @@ function textFiles(b: Built): Map { return files; } -/** Source modules the static web tier must not contain: only the dev host has them. */ -const DEV_ONLY = { - "the FastAPI client": /\/src\/lib\/api\/client\.ts$/, - "the dev host": /\/src\/lib\/platform\/dev\.ts$/, - "the style editor route": /\/src\/routes\/Advanced\.svelte/, - "the style editor components": /\/src\/components\/advanced\//, -}; - -describe("bundle split", () => { - it("keeps build and style-editor code out of the web target", async () => { - const modules = modulesOf(await web()); - // An empty build, or one that quietly picked another host, would pass - // every assertion below. - expect(modules.some((id) => id.endsWith("/src/lib/platform/web.ts"))).toBe(true); - expect(modules.some((id) => id.includes("/src/routes/Home.svelte"))).toBe(true); - - const found = Object.entries(DEV_ONLY).flatMap(([what, re]) => - modules.filter((id) => re.test(id)).map((id) => `${what}: ${id}`), - ); - expect(found).toEqual([]); - - expect(modules.some((id) => id.includes("/src/components/coverage/CoverageHome.svelte"))).toBe( - true, - ); - }, 180_000); - - it("ships the maintainer style editor only in the dev target", async () => { - const modules = modulesOf(await dev()); - const missing = Object.entries(DEV_ONLY) - .filter(([, re]) => !modules.some((id) => re.test(id))) - .map(([what]) => what); - expect(missing).toEqual([]); - - // Localhost is a secure WebUSB context, so this build keeps the same lazy - // browser transport. - expect(modules.some((id) => id.endsWith("/src/lib/usb/webusb.ts"))).toBe(true); - }, 180_000); -}); - // Whatever the bundler puts in the bundle, its licence text has to ship beside // it. A list of `dependencies` would prove nothing: Svelte is a devDependency // compiled into every chunk. @@ -197,17 +155,18 @@ function offenders(files: Map, needle: string | RegExp): string[ const ROOTED_SITE_PATH = /["'`(=,]\/OpenBikeComputer\//; /** - * The site's own origin, which a portable bundle must never contain. + * The site's own origin at the start of a string, which a portable bundle must never contain. * `updates.openbikecomputer.com` is the firmware-update host: an endpoint the * app fetches a manifest from, not a self-reference, and moving the site does - * not move it. + * not move it. The planner names the site inside its user agent for Wikipedia, + * which is not a link. */ -const SITE_ORIGIN = /https?:\/\/(?:www\.)?openbikecomputer\.com/; +const SITE_ORIGIN = /["'`]https?:\/\/(?:www\.)?openbikecomputer\.com/; describe("deployment portability", () => { it("references its own assets relatively", async () => { - const html = textFiles(await web()).get("index.html") ?? ""; - // The build produced an index.html with script/style refs at all… + const html = textFiles(await web()).get("planner.html") ?? ""; + // The build produced a page with script/style refs at all… expect(html).toMatch(/]+src="/); // …and every local ref in it is relative, not rooted at "/". const refs = [...html.matchAll(/(?:src|href)="([^"]+)"/g)].map((m) => m[1]); @@ -256,10 +215,11 @@ describe("the USB stack's chunk", () => { ); expect(shipped).toEqual([]); const wasm = built.filter((item) => item.type === "asset" && item.fileName.endsWith(".wasm")); - expect(wasm).toHaveLength(1); - const source = wasm[0].source; - expect(source).toBeInstanceOf(Uint8Array); - const exports = WebAssembly.Module.exports(new WebAssembly.Module(source as Uint8Array)); - expect(exports.some((entry) => /flatdevice|devicereaction/.test(entry.name))).toBe(false); + expect(wasm.length).toBeGreaterThan(0); + for (const { source } of wasm) { + expect(source).toBeInstanceOf(Uint8Array); + const exports = WebAssembly.Module.exports(new WebAssembly.Module(source as Uint8Array)); + expect(exports.some((entry) => /flatdevice|devicereaction/.test(entry.name))).toBe(false); + } }, 180_000); }); diff --git a/builder/web/src/lib/platform/dev.ts b/builder/web/src/lib/platform/dev.ts deleted file mode 100644 index d840debcbc..0000000000 --- a/builder/web/src/lib/platform/dev.ts +++ /dev/null @@ -1,32 +0,0 @@ -// The dev host: `python -m builder.server` on :8000, which is what local -// development has always talked to. This file is a thin adapter — every call -// below adapts the local tools to the same coverage composer the shipped web -// target uses. - -import { api } from "../api/client"; -import { LINKS } from "../constants"; -import type { Platform } from "./types"; - -async function catalog({ refresh = false }: { refresh?: boolean } = {}): Promise<{ url: string; body: string }> { - return api.publishedCatalog(refresh); -} - -export const platform: Platform = { - name: "dev", - - styleEditor: { - load: () => import("../../routes/Advanced.svelte"), - presets: () => api.presets(), - schema: () => api.schema(), - palette: () => api.palette(), - preview: { - status: () => api.previewStatus(), - pack: (config, signal) => api.packPreview(config, signal), - }, - }, - catalog, - catalogFetch: (input, init) => api.catalogFetch(input, init), - - // A localhost stand-in for the hosted site keeps the site's chrome. - siteNav: LINKS, -}; diff --git a/builder/web/src/lib/platform/dev.wire.test.ts b/builder/web/src/lib/platform/dev.wire.test.ts deleted file mode 100644 index d718605e2c..0000000000 --- a/builder/web/src/lib/platform/dev.wire.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -// The maintainer dev host keeps only the schema-editor HTTP seam. Product map -// building consumes the same published catalog as the web host. - -import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { platform } from "./dev"; - -interface Recorded { - url: string; - method: string; -} - -let calls: Recorded[]; -const realFetch = globalThis.fetch; - -beforeEach(() => { - calls = []; - globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { - calls.push({ url: String(input), method: init?.method ?? "GET" }); - return new Response("{}", { status: 200, headers: { "Content-Type": "application/json" } }); - }) as typeof fetch; -}); - -afterEach(() => { - globalThis.fetch = realFetch; -}); - -describe("dev host requests", () => { - const editor = platform.styleEditor!; - - it.each([ - ["presets", () => editor.presets(), "/api/presets"], - ["schema", () => editor.schema(), "/api/schema"], - ["palette", () => editor.palette(), "/api/palette"], - ["preview status", () => editor.preview.status(), "/api/schema-preview/status"], - ])("%s GETs %s", async (_name, call, url) => { - await call(); - expect(calls).toEqual([{ url, method: "GET" }]); - }); - - it("reads the configured published catalog through the runtime host instead of baking it into Vite", async () => { - globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { - const url = String(input); - calls.push({ url, method: init?.method ?? "GET" }); - return new Response("catalog-body", { - status: 200, - headers: { "X-OBC-Catalog-Url": "https://maps.example.test/live/catalog.json" }, - }); - }) as typeof fetch; - - await expect(platform.catalog()).resolves.toEqual({ - url: "https://maps.example.test/live/catalog.json", - body: "catalog-body", - }); - expect(calls).toEqual([{ url: "/api/catalog/root", method: "GET" }]); - }); - - it("moves satellites and cells through the same-origin bounded proxy", async () => { - globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { - calls.push({ url: String(input), method: init?.method ?? "GET" }); - return new Response(new Uint8Array([1, 2, 3]), { status: 200 }); - }) as typeof fetch; - const object = "https://maps.example.test/live/cells/12/3/4.obcm"; - const response = await platform.catalogFetch(object); - expect(new Uint8Array(await response.arrayBuffer())).toEqual(new Uint8Array([1, 2, 3])); - expect(calls).toEqual([{ - url: `/api/catalog/object?url=${encodeURIComponent(object)}`, - method: "GET", - }]); - }); - - it("posts only config JSON and propagates cancellation", async () => { - const controller = new AbortController(); - globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { - calls.push({ url: String(input), method: init?.method ?? "GET" }); - expect(init?.body).toBe(JSON.stringify({ lods: [], features: {} })); - expect(init?.signal).toBe(controller.signal); - return new Response(new Uint8Array([79, 66, 67, 77]), { - status: 200, - headers: { "X-OBC-Pack-Duration-Ms": "42" }, - }); - }) as typeof fetch; - - await expect( - editor.preview.pack({ lods: [], features: {} }, controller.signal), - ).resolves.toEqual({ bytes: new Uint8Array([79, 66, 67, 77]), packDurationMs: 42, diagnostics: [] }); - expect(calls).toEqual([{ url: "/api/schema-preview", method: "POST" }]); - }); -}); diff --git a/builder/web/src/lib/platform/hosts.test.ts b/builder/web/src/lib/platform/hosts.test.ts deleted file mode 100644 index 0083f05595..0000000000 --- a/builder/web/src/lib/platform/hosts.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -// The hosts are imported directly, not through `$host`, because the point is -// to check both in one run. - -import { describe, expect, it } from "vitest"; -import * as dev from "./dev"; -import * as web from "./web"; - -const HOSTS = { web, dev }; - -describe.each(Object.entries(HOSTS))("%s host", (name, host) => { - it("names itself", () => { - expect(host.platform.name).toBe(name); - }); -}); - -describe("the hosts as a set", () => { - it("loads the style editor only on the dev host", () => { - // The web host consumes published cells; only the dev host loads the - // maintainer schema editor. - expect(web.platform.styleEditor).toBeNull(); - expect(dev.platform.styleEditor).not.toBeNull(); - }); -}); diff --git a/builder/web/src/lib/platform/index.ts b/builder/web/src/lib/platform/index.ts index 9b7f1b1917..7846e52d13 100644 --- a/builder/web/src/lib/platform/index.ts +++ b/builder/web/src/lib/platform/index.ts @@ -1,12 +1,5 @@ -// The one place the app reaches its host. `$host` is a Vite alias resolved at -// build time (see vite.config.ts) to exactly one of web.ts / dev.ts, so this -// is a static re-export, not a dispatch: the host you did not build has no path -// into the module graph. That, rather than any dead-code elimination, is what -// keeps maintainer-only code out of the static web bundle. -// -// Type-checking resolves `$host` to dev.ts (tsconfig `paths`) — the mode -// `npm run dev` and `npm run build` use. Both hosts are still checked as -// files, each against `Platform`. +// The one place the app reaches its host. `$host` is a Vite alias (see vite.config.ts) that +// names the web host, `web.ts`, in every mode. export { platform } from "$host"; export * from "./types"; diff --git a/builder/web/src/lib/platform/types.ts b/builder/web/src/lib/platform/types.ts index b829463054..c6d331f832 100644 --- a/builder/web/src/lib/platform/types.ts +++ b/builder/web/src/lib/platform/types.ts @@ -1,54 +1,8 @@ -import type { Component } from "svelte"; -import type { Preset, SchemaEnvelope } from "../config/model"; - -export type PlatformName = "web" | "dev"; - -export interface Palette { - columns: number; - colors: string[]; -} - -export interface SchemaPreviewStatus { - available: boolean; - label: string; - configured: boolean; - detail: string; - bbox: string; -} - -export interface SchemaPreviewMap { - bytes: Uint8Array; - packDurationMs: number; - diagnostics: string[]; -} - -export interface SchemaPreviewService { - status(): Promise; - pack(config: Record, signal: AbortSignal): Promise; -} - -export type StyleEditorModule = { default: Component> }; - -export interface StyleEditorService { - load(): Promise; - presets(): Promise; - schema(): Promise; - palette(): Promise; - readonly preview: SchemaPreviewService; -} - -/** - * Host services used by the shared app. Build-time aliases select one platform, - * so absent hosts do not enter the bundle. `null` means unavailable by design. - */ +/** Host services used by the shared app. */ export interface Platform { - readonly name: PlatformName; - /** Resolved catalog URL and its raw root document. */ catalog(options?: { refresh?: boolean }): Promise<{ url: string; body: string }>; readonly catalogFetch: typeof fetch; - readonly styleEditor: StyleEditorService | null; - readonly siteNav: { readonly home: string; readonly docs: string; readonly blog: string; readonly github: string }; } diff --git a/builder/web/src/lib/platform/web.ts b/builder/web/src/lib/platform/web.ts index 2bb2508a64..cdeeb8947d 100644 --- a/builder/web/src/lib/platform/web.ts +++ b/builder/web/src/lib/platform/web.ts @@ -60,13 +60,9 @@ async function releaseCatalog(): Promise<{ url: string; body: string }> { } export const platform: Platform = { - name: "web", - catalog: fetchCatalog, catalogFetch: globalThis.fetch, - styleEditor: null, - // This host *is* the site, so its header links back out to the rest of it. siteNav: LINKS, }; diff --git a/builder/web/src/lib/schema/lods.test.ts b/builder/web/src/lib/schema/lods.test.ts deleted file mode 100644 index 4221f4eb02..0000000000 --- a/builder/web/src/lib/schema/lods.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { previewLadder, representativeMpp } from "./lods"; - -describe("schema preview LOD scales", () => { - const lods = [null, 400, 120, 30, 16, 10, 5, 3, 1.2].map((max_mpp) => ({ max_mpp, simplify: 0 })); - - it("covers the complete shipped ladder at exact production thresholds", () => { - expect(lods.map((_lod, index) => representativeMpp(lods, index))).toEqual([ - 480, 400, 120, 30, 16, 10, 5, 3, 1.2, - ]); - }); - - it("keeps malformed custom ladders within the renderer bridge bounds", () => { - const malformed = [{ max_mpp: null, simplify: 0 }, { max_mpp: null, simplify: 0 }]; - expect(representativeMpp(malformed, 0)).toBe(40); - expect(representativeMpp(malformed, 1)).toBeGreaterThanOrEqual(0.5); - }); - - it("does not hide a valid custom coarse threshold behind a display-only clamp", () => { - const custom = [{ max_mpp: null, simplify: 0 }, { max_mpp: 500, simplify: 0 }]; - expect(representativeMpp(custom, 0)).toBe(600); - }); -}); - -describe("previewLadder", () => { - const editing = [null, 400, 120, 30].map((max_mpp) => ({ max_mpp, simplify: 0 })); - const packed = [null, 30, 16].map((max_mpp) => ({ max_mpp, simplify: 0 })); - - it("shows the editable ladder before anything is packed", () => { - expect(previewLadder(null, editing)).toEqual(editing); - }); - - it("shows the ladder the DISPLAYED map was packed with, not the one being edited", () => { - // Adding two far-zoom tiers must not put two chips on screen that the loaded map has no - // tiers for — clicking one would only dispatch the renderer to some other LOD. - expect(previewLadder(packed, editing, 3)).toEqual(packed); - }); - - it("lets the loaded map's own table decide how many chips there are", () => { - const trimmed = previewLadder(packed, editing, 2); - expect(trimmed).toHaveLength(2); - expect(trimmed[1].max_mpp).toBe(30); - // And a tier the map carries that neither ladder describes still gets a chip. - expect(previewLadder(packed, editing, 4)).toHaveLength(4); - }); -}); diff --git a/builder/web/src/lib/schema/lods.ts b/builder/web/src/lib/schema/lods.ts deleted file mode 100644 index 5fe117f201..0000000000 --- a/builder/web/src/lib/schema/lods.ts +++ /dev/null @@ -1,30 +0,0 @@ -import type { LodTier } from "../config/model"; - -/** - * The ladder the LOD chips must describe: the one the **displayed** map was packed with, not - * the one being edited. The two differ for the whole debounce-plus-pack window (seconds), and a - * chip for a tier the loaded map does not carry can never light — clicking it just dispatches the - * renderer to some other tier. `lodCount` is the loaded map's own table size, read straight off - * the render stats, and is the tiebreak when the two disagree for any other reason. - * - * `packed` is null before the first successful pack, and then the editable config is all there is - * to show. - */ -export function previewLadder(packed: LodTier[] | null, editing: LodTier[], lodCount?: number): LodTier[] { - const source = packed ?? editing; - if (lodCount === undefined || lodCount === source.length) return source; - // The loaded map's own table wins on how many tiers exist; a tier it carries that neither - // ladder describes falls back to the bridge's default scale rather than disappearing. - return Array.from({ length: lodCount }, (_, i) => source[i] ?? { max_mpp: null, simplify: 0 }); -} - -/** A stable scale that dispatches to `index` under Reader::select_lod_for_mpp. */ -export function representativeMpp(lods: LodTier[], index: number): number { - if (index <= 0) { - const next = lods[1]?.max_mpp; - return typeof next === "number" && Number.isFinite(next) ? next + Math.max(1, next * 0.2) : 40; - } - const ceiling = lods[index]?.max_mpp; - if (typeof ceiling === "number" && Number.isFinite(ceiling) && ceiling > 0) return ceiling; - return Math.max(0.5, 40 / 2 ** index); -} diff --git a/builder/web/src/lib/schema/previewController.test.ts b/builder/web/src/lib/schema/previewController.test.ts deleted file mode 100644 index 5fda7f133e..0000000000 --- a/builder/web/src/lib/schema/previewController.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; -import { PreviewController, type PreviewPhase } from "./previewController"; - -function deferred() { - let resolve!: (value: T) => void; - let reject!: (reason: unknown) => void; - const promise = new Promise((yes, no) => { - resolve = yes; - reject = no; - }); - return { promise, resolve, reject }; -} - -afterEach(() => vi.useRealTimers()); - -describe("PreviewController", () => { - it("debounces rapid edits and packs only the last config", async () => { - vi.useFakeTimers(); - const calls: string[] = []; - const phases: PreviewPhase[] = []; - const preview = new PreviewController( - async (input: string) => { - calls.push(input); - return input.toUpperCase(); - }, - (phase) => phases.push(phase), - 100, - ); - - preview.schedule("old"); - await vi.advanceTimersByTimeAsync(50); - preview.schedule("new"); - await vi.advanceTimersByTimeAsync(100); - - expect(calls).toEqual(["new"]); - expect(phases.at(-1)).toEqual({ kind: "ready", value: "NEW" }); - }); - - it("aborts an in-flight pack and suppresses a stale result even when it ignores abort", async () => { - vi.useFakeTimers(); - const old = deferred(); - const fresh = deferred(); - const signals: AbortSignal[] = []; - const phases: PreviewPhase[] = []; - const preview = new PreviewController( - (input: string, signal) => { - signals.push(signal); - return input === "old" ? old.promise : fresh.promise; - }, - (phase) => phases.push(phase), - 10, - ); - - preview.schedule("old"); - await vi.advanceTimersByTimeAsync(10); - preview.schedule("new"); - expect(signals[0].aborted).toBe(true); - await vi.advanceTimersByTimeAsync(10); - fresh.resolve("fresh-map"); - await Promise.resolve(); - old.resolve("stale-map"); - await Promise.resolve(); - - expect(phases.filter((phase) => phase.kind === "ready")).toEqual([ - { kind: "ready", value: "fresh-map" }, - ]); - }); - - it("surfaces only a current pack failure", async () => { - vi.useFakeTimers(); - const phases: PreviewPhase[] = []; - const preview = new PreviewController( - async () => { - throw new Error("packer rejected min_lod"); - }, - (phase) => phases.push(phase), - 1, - ); - preview.schedule("bad"); - await vi.advanceTimersByTimeAsync(1); - expect(phases.at(-1)).toEqual({ kind: "error", message: "packer rejected min_lod" }); - }); - - it("cancels timers and requests on disposal", async () => { - vi.useFakeTimers(); - const calls: string[] = []; - const preview = new PreviewController( - async (input: string) => { - calls.push(input); - return input; - }, - () => {}, - 20, - ); - preview.schedule("never"); - preview.dispose(); - await vi.advanceTimersByTimeAsync(20); - expect(calls).toEqual([]); - }); -}); diff --git a/builder/web/src/lib/schema/previewController.ts b/builder/web/src/lib/schema/previewController.ts deleted file mode 100644 index 74936cc6f5..0000000000 --- a/builder/web/src/lib/schema/previewController.ts +++ /dev/null @@ -1,65 +0,0 @@ -export type PreviewPhase = - | { kind: "idle" } - | { kind: "waiting" } - | { kind: "packing" } - | { kind: "ready"; value: T } - | { kind: "displayed" } - | { kind: "error"; message: string }; - -/** - * Latest-edit-wins orchestration for the semi-live schema preview. - * - * Debouncing avoids launching a native pack per number-input keystroke. A new - * edit aborts an in-flight HTTP request, while the generation check remains the - * correctness boundary for servers or test doubles that ignore AbortSignal. - */ -export class PreviewController { - private timer: ReturnType | undefined; - private active: AbortController | undefined; - private generation = 0; - private disposed = false; - - constructor( - private readonly run: (input: I, signal: AbortSignal) => Promise, - private readonly update: (phase: PreviewPhase) => void, - private readonly delayMs = 650, - ) {} - - schedule(input: I) { - if (this.disposed) return; - const generation = ++this.generation; - clearTimeout(this.timer); - this.active?.abort(); - this.active = undefined; - this.update({ kind: "waiting" }); - this.timer = setTimeout(() => void this.start(input, generation), this.delayMs); - } - - private async start(input: I, generation: number) { - if (this.disposed || generation !== this.generation) return; - const controller = new AbortController(); - this.active = controller; - this.update({ kind: "packing" }); - try { - const value = await this.run(input, controller.signal); - if (!this.disposed && generation === this.generation) this.update({ kind: "ready", value }); - } catch (cause) { - if (this.disposed || generation !== this.generation || controller.signal.aborted) return; - this.update({ - kind: "error", - message: cause instanceof Error ? cause.message : String(cause), - }); - } finally { - if (this.active === controller) this.active = undefined; - } - } - - dispose() { - this.disposed = true; - ++this.generation; - clearTimeout(this.timer); - this.active?.abort(); - this.active = undefined; - this.update({ kind: "idle" }); - } -} diff --git a/builder/web/src/lib/schema/render.ts b/builder/web/src/lib/schema/render.ts deleted file mode 100644 index 0e2d97606d..0000000000 --- a/builder/web/src/lib/schema/render.ts +++ /dev/null @@ -1,80 +0,0 @@ -import type { InitInput } from "../core/pkg/obc_builder_bridge.js"; -import { initCore } from "../core/bridge"; - -type Bridge = typeof import("../core/pkg/obc_builder_bridge.js"); -type WasmSchemaPreview = InstanceType; - -export interface SchemaRenderStats { - metersPerPixel: number; - lodIndex: number; - lodCount: number; - chunksVisited: number; - featuresTried: number; - featuresDrawn: number; - featuresDropped: number; - pointsTried: number; - pointsDrawn: number; - spansUsed: number; - ringsUsed: number; - featureDecodeCapacityDrops: number; - malformedFeatures: number; - mapErrors: number; -} - -export interface SchemaRenderLimits { - maxFeaturePoints: number; - maxFeatureRings: number; - maxSpans: number; - maxFramePoints: number; - maxFrameRings: number; -} - -export interface SchemaRenderer { - readonly width: number; - readonly height: number; - setMetersPerPixel(value: number): void; - readonly limits: SchemaRenderLimits; - frame(): Uint8ClampedArray; - stats(): SchemaRenderStats; - free(): void; -} - - -function module(source?: InitInput): Promise { - return initCore(source); -} - -export async function openSchemaRenderer(bytes: Uint8Array, wasm?: InitInput): Promise { - const mod = await module(wasm); - const preview: WasmSchemaPreview = new mod.SchemaPreview(bytes); - return { - width: preview.width, - height: preview.height, - limits: { - maxFeaturePoints: preview.max_feature_points, - maxFeatureRings: preview.max_feature_rings, - maxSpans: preview.max_spans, - maxFramePoints: preview.max_frame_points, - maxFrameRings: preview.max_frame_rings, - }, - setMetersPerPixel: (value) => preview.set_meters_per_pixel(value), - frame: () => preview.frame(), - stats: () => ({ - metersPerPixel: preview.meters_per_pixel, - lodIndex: preview.lod_index, - lodCount: preview.lod_count, - chunksVisited: preview.chunks_visited, - featuresTried: preview.features_tried, - featuresDrawn: preview.features_drawn, - featuresDropped: preview.features_dropped, - pointsTried: preview.points_tried, - pointsDrawn: preview.points_drawn, - spansUsed: preview.spans_used, - ringsUsed: preview.rings_used, - featureDecodeCapacityDrops: preview.feature_decode_capacity_drops, - malformedFeatures: preview.malformed_features, - mapErrors: preview.map_errors, - }), - free: () => preview.free(), - }; -} diff --git a/builder/web/src/lib/ui/confirm.svelte.test.ts b/builder/web/src/lib/ui/confirm.svelte.test.ts deleted file mode 100644 index 1fbfe8bf98..0000000000 --- a/builder/web/src/lib/ui/confirm.svelte.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -/** - * The app's confirmation (see the module docs). Two things are worth pinning: - * - * - every way of declining resolves `false`, so a caller never has to tell "no" from "went away"; - * - a second question while one is open is declined rather than queued, because the only way to - * reach it is a click that got through while a modal was up. - */ - -import { describe, expect, it } from "vitest"; - -import { confirmAction, confirmQueue } from "./confirm.svelte"; - -describe("confirmAction", () => { - it("resolves true only when the affirmative button is pressed", async () => { - const answered = confirmAction({ title: "Re-apply “Bikepacking”?" }); - expect(confirmQueue.pending?.title).toBe("Re-apply “Bikepacking”?"); - confirmQueue.pending!.answer(true); - expect(await answered).toBe(true); - expect(confirmQueue.pending, "the dialog closes as soon as it is answered").toBeNull(); - }); - - it("resolves false on any way of declining", async () => { - const declined = confirmAction({ title: "Delete 950 MB?" }); - confirmQueue.pending!.answer(false); - expect(await declined).toBe(false); - expect(confirmQueue.pending).toBeNull(); - }); - - it("declines a second question rather than stacking two modals", async () => { - const first = confirmAction({ title: "first" }); - // Not queued: whatever asked this was not something the rider could see or aim at. - expect(await confirmAction({ title: "second" })).toBe(false); - expect(confirmQueue.pending?.title, "the open question is untouched").toBe("first"); - confirmQueue.pending!.answer(true); - expect(await first).toBe(true); - }); - - it("carries the copy the dialog renders", async () => { - const asked = confirmAction({ - title: "Remove the “water” category?", - body: "All 12 of its feature types go with it.", - confirmLabel: "Remove", - destructive: true, - }); - expect(confirmQueue.pending).toMatchObject({ - body: "All 12 of its feature types go with it.", - confirmLabel: "Remove", - destructive: true, - }); - confirmQueue.pending!.answer(false); - await asked; - }); -}); - diff --git a/builder/web/src/lib/ui/confirm.svelte.ts b/builder/web/src/lib/ui/confirm.svelte.ts deleted file mode 100644 index 580fb62968..0000000000 --- a/builder/web/src/lib/ui/confirm.svelte.ts +++ /dev/null @@ -1,59 +0,0 @@ -/** - * "Are you sure?", asked by the app rather than by the browser. - * - * The app owns the dialog, so the affirmative button names its action and a destructive one looks - * destructive, which `window.confirm()` cannot do. - * - * One question at a time, held here rather than in whichever component asked, so the markup is - * mounted once at the app root. The promise resolves `false` for every way of declining — Cancel, - * Escape, a click outside — because a caller should never have to tell "no" from "went away". - */ - -/** What a confirmation says. Plain data, so the asking site reads as one call. */ -export interface ConfirmRequest { - /** The question, as a sentence. */ - readonly title: string; - /** What saying yes costs, where that is not obvious from the title. */ - readonly body?: string; - /** The affirmative button's label. A verb, not "OK": the button should say what it does. */ - readonly confirmLabel?: string; - /** Colours the affirmative button as a destructive action. */ - readonly destructive?: boolean; -} - -/** A question waiting for an answer, as the dialog component renders it. */ -export interface PendingConfirm extends ConfirmRequest { - readonly answer: (yes: boolean) => void; -} - -class ConfirmQueue { - /** Null when nothing is being asked. Read by `components/ConfirmDialog.svelte`. */ - pending = $state(null); - - /** - * Ask, and resolve with the answer. - * - * A second question while one is open resolves `false` immediately rather than queueing. - * Two modals stacked over each other is never the right screen, and the only way to reach this - * is a click that got through while a dialog was up — which is exactly the click to decline. - */ - ask(request: ConfirmRequest): Promise { - if (this.pending) return Promise.resolve(false); - return new Promise((resolve) => { - this.pending = { - ...request, - answer: (yes: boolean) => { - this.pending = null; - resolve(yes); - }, - }; - }); - } -} - -export const confirmQueue = new ConfirmQueue(); - -/** The one call a surface makes. `await confirmAction({...})`, in place of `confirm(...)`. */ -export function confirmAction(request: ConfirmRequest): Promise { - return confirmQueue.ask(request); -} diff --git a/builder/web/src/main.ts b/builder/web/src/main.ts deleted file mode 100644 index 70742799f5..0000000000 --- a/builder/web/src/main.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { mount } from "svelte"; -import "leaflet/dist/leaflet.css"; -import "./styles/app.css"; -import { initCore } from "./lib/core/bridge"; - -void initCore().then(async () => { - const { default: App } = await import("./App.svelte"); - mount(App, { target: document.getElementById("app")! }); -}).catch((cause: unknown) => { - document.getElementById("app")!.textContent = `The builder core could not be loaded. Reload the page to retry. ${String(cause)}`; -}); diff --git a/builder/web/src/pages/Device.svelte b/builder/web/src/pages/Device.svelte index dd6a0d2cff..5d3247e959 100644 --- a/builder/web/src/pages/Device.svelte +++ b/builder/web/src/pages/Device.svelte @@ -47,7 +47,7 @@ const device = $derived(remembered.device); const raw = $derived(deviceHolder.error ?? (status === 'error' ? session?.error : null)); // Chrome names `claimInterface` when another page holds the device. - const error = $derived(raw && /claim/i.test(raw) ? 'Another tab or the map builder uses the device. Close it, then connect again.' : raw); + const error = $derived(raw && /claim/i.test(raw) ? 'Another tab uses the device. Close it, then connect again.' : raw); const view = $derived( status === 'unsupported' ? 'cannot' : !session && !deviceHolder.error ? 'loading' @@ -231,11 +231,10 @@ {/if}
- {#if !connected && (other || released || error)} + {#if !connected && (other || error)} {@const problem = error ?? (other && !other.formatted ? formatProblem : '')}

- {problem || (!other ? 'The map builder can use the device now. Connect takes it back.' - : other.formatted ? `${other.name} is on the cable.` : `The memory card of ${other.name} needs a format.`)} + {problem || (other?.formatted ? `${other.name} is on the cable.` : `The memory card of ${other?.name} needs a format.`)}

{/if} diff --git a/builder/web/src/routes/Advanced.svelte b/builder/web/src/routes/Advanced.svelte deleted file mode 100644 index 831d1d3398..0000000000 --- a/builder/web/src/routes/Advanced.svelte +++ /dev/null @@ -1,283 +0,0 @@ - - -
- ← Maps -

Advanced editor

- {#if env} - - {#if !env.modified}Preset: {basedOnName} - {:else if basedOnName}Custom — based on {basedOnName} - {:else}Custom{/if} - - {/if} - - {#if env?.modified && env?.based_on} - - {/if} - - - { - importPicked(e.currentTarget.files); - e.currentTarget.value = ""; - }} - /> - -
- -{#if importError} -

{importError}

-{/if} - -{#if !env} -
- {#if !presetsLoaded} -

Loading the maintainer schema preset…

- {:else if presetsError} -

- The maintainer schema presets could not be loaded: {presetsError} - Restart obc web, or import a complete packer config above. -

- {:else} -

- Automatic first-use setup requires exactly one buildable schema preset, but this host provided - {buildablePresetCount}. Import a complete packer config above. -

- {/if} -
-{:else} - -
- - - - -
- - {#if tab === "features"} -
- (activeCat = c)} - /> - {#if activeCat} - {#key activeCat} - ][]} - schemaRoot={schema?.schema ?? {}} - catalogValues={catalog.keys[activeCat] ?? []} - ondeleted={() => (activeCat = "")} - /> - {/key} - {/if} -
- {:else if tab === "lods"} - - {:else if tab === "routing"} - - {:else} - - {/if} -{/if} - - diff --git a/builder/web/src/routes/Advanced.svelte.test.ts b/builder/web/src/routes/Advanced.svelte.test.ts deleted file mode 100644 index 975b217d6a..0000000000 --- a/builder/web/src/routes/Advanced.svelte.test.ts +++ /dev/null @@ -1,170 +0,0 @@ -// @vitest-environment happy-dom - -import { mount, unmount } from "svelte"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { Preset, SchemaEnvelope } from "../lib/config/model"; - -const host = vi.hoisted(() => ({ - presets: vi.fn(), - schema: vi.fn(), - previewStatus: vi.fn(), - previewPack: vi.fn(), -})); - -vi.mock("../lib/platform", () => ({ - platform: { - styleEditor: { - presets: host.presets, - schema: host.schema, - preview: { status: host.previewStatus, pack: host.previewPack }, - }, - }, -})); - -import { working, type WorkingEnvelope } from "../lib/config/storage.svelte"; -import Advanced from "./Advanced.svelte"; - -// Node 22 exposes an opt-in `localStorage` global that shadows happy-dom's -// storage unless the process receives a file flag. The route contract needs -// ordinary browser storage, so keep this test hermetic with the same API. -const storageValues = new Map(); -const memoryStorage: Storage = { - get length() { - return storageValues.size; - }, - clear: () => storageValues.clear(), - getItem: (key) => storageValues.get(key) ?? null, - key: (index) => [...storageValues.keys()][index] ?? null, - removeItem: (key) => storageValues.delete(key), - setItem: (key, value) => storageValues.set(key, String(value)), -}; -Object.defineProperty(globalThis, "localStorage", { configurable: true, value: memoryStorage }); - -const schema: SchemaEnvelope = { - schema_version: 1, - format_version: 10, - source: "binary", - schema: { $defs: { style: { properties: {} } } }, -}; - -const bikepacking: Preset = { - id: "bikepacking", - name: "Bikepacking", - description: "The shipped schema", - version: 3, - config: { - lods: [{ max_mpp: null, simplify: 0 }], - features: {}, - marker: { color: "0xF800" }, - }, -}; - -function existingEnvelope(): WorkingEnvelope { - return { - schema_version: 1, - based_on: { id: "my-schema", version: 7 }, - modified: true, - config: { - lods: [{ max_mpp: null, simplify: 17 }], - features: {}, - marker: { color: "0x1234" }, - }, - disabled: [], - }; -} - -const mounted: ReturnType[] = []; - -function render() { - const target = document.createElement("div"); - document.body.append(target); - mounted.push(mount(Advanced, { target })); - return target; -} - -beforeEach(() => { - localStorage.clear(); - working.envelope = null; - host.presets.mockReset(); - host.schema.mockReset().mockResolvedValue(schema); - host.previewStatus.mockReset().mockResolvedValue({ - available: false, - label: "unavailable", - configured: false, - detail: "", - bbox: "", - }); - host.previewPack.mockReset(); - globalThis.fetch = vi.fn(async () => Response.json({ keys: {} })) as typeof fetch; -}); - -afterEach(async () => { - while (mounted.length) await unmount(mounted.pop()!); - working.envelope = null; - localStorage.clear(); - document.body.replaceChildren(); - vi.restoreAllMocks(); -}); - -describe("Advanced first-use schema initialization", () => { - it("copies the sole buildable maintainer preset on fresh storage", async () => { - host.presets.mockResolvedValue([bikepacking]); - const target = render(); - - await vi.waitFor(() => { - expect(working.envelope?.based_on).toEqual({ id: "bikepacking", version: 3 }); - }); - - expect(working.envelope?.modified).toBe(false); - expect(working.envelope?.config.marker.color).toBe("0xF800"); - expect(target.textContent).toContain("Preset: Bikepacking"); - expect(JSON.parse(localStorage.getItem("obcm.working") ?? "null").based_on).toEqual({ - id: "bikepacking", - version: 3, - }); - }); - - it("restores and preserves an existing working config before presets load", async () => { - const existing = existingEnvelope(); - localStorage.setItem("obcm.working", JSON.stringify(existing)); - host.presets.mockResolvedValue([bikepacking]); - const target = render(); - - await vi.waitFor(() => expect(host.presets).toHaveBeenCalledOnce()); - await vi.waitFor(() => expect(target.textContent).toContain("Custom — based on my-schema")); - - expect(working.envelope?.based_on).toEqual(existing.based_on); - expect(working.envelope?.config.marker.color).toBe("0x1234"); - expect(JSON.parse(localStorage.getItem("obcm.working") ?? "null")).toEqual(existing); - }); - - it("does not replace an imported config while the preset request is in flight", async () => { - let resolvePresets!: (presets: Preset[]) => void; - host.presets.mockReturnValue(new Promise((resolve) => (resolvePresets = resolve))); - const target = render(); - await vi.waitFor(() => expect(host.presets).toHaveBeenCalledOnce()); - - const imported = existingEnvelope(); - working.adopt(imported); - resolvePresets([bikepacking]); - await vi.waitFor(() => expect(target.textContent).toContain("Custom — based on my-schema")); - - expect(working.envelope?.based_on).toEqual(imported.based_on); - expect(working.envelope?.config.marker.color).toBe("0x1234"); - }); - - it("does not choose arbitrarily when multiple buildable schemas are served", async () => { - host.presets.mockResolvedValue([ - bikepacking, - { ...bikepacking, id: "experimental", name: "Experimental", version: 1 }, - ]); - const target = render(); - - await vi.waitFor(() => { - expect(target.textContent?.replace(/\s+/g, " ")).toContain( - "Automatic first-use setup requires exactly one buildable schema preset, but this host provided 2.", - ); - }); - expect(working.envelope).toBeNull(); - }); -}); diff --git a/builder/web/src/routes/Home.svelte b/builder/web/src/routes/Home.svelte deleted file mode 100644 index 2cda694913..0000000000 --- a/builder/web/src/routes/Home.svelte +++ /dev/null @@ -1,55 +0,0 @@ - - -{#if catalog} - loadCatalog(true)} /> -{:else if error} - - -{:else} -

Loading the map catalog…

-{/if} - - diff --git a/builder/web/src/styles/app.css b/builder/web/src/styles/app.css deleted file mode 100644 index 5c38b601bc..0000000000 --- a/builder/web/src/styles/app.css +++ /dev/null @@ -1,299 +0,0 @@ -@import "./tokens.css"; - -* { - box-sizing: border-box; -} - -html, -body { - margin: 0; - height: 100%; -} - -body { - font-family: var(--sans); - color: var(--ink); - background: var(--parchment); - font-size: 15px; - line-height: 1.5; -} - -/* The app owns the viewport and the page never scrolls: `main` is the scroll - container, and the builder locks itself further so only its steps column - moves (Home.svelte). On narrow screens the lock is traded back for ordinary - page scrolling — a phone-width window has no room for a fixed map pane. */ -#app { - height: 100dvh; - display: flex; - flex-direction: column; -} - -@media (max-width: 940px) { - #app { - height: auto; - min-height: 100dvh; - } -} - -h1, -h2, -h3 { - font-family: var(--serif); - font-weight: 600; - color: var(--ink); - margin: 0; -} - -a { - color: var(--forest); - text-decoration: none; -} - -a:hover { - color: var(--forest-deep); - text-decoration: underline; -} - -button { - font-family: var(--sans); - font-size: 14px; - cursor: pointer; -} - -input, -select { - font-family: var(--sans); - font-size: 14px; - color: var(--ink); - background: var(--parchment); - border: 1px solid var(--parchment-3); - border-radius: 8px; - padding: 7px 10px; -} - -input:focus, -select:focus { - outline: 2px solid var(--forest); - outline-offset: 2px; -} - -/* Shared surfaces and controls. */ - -.card { - background: var(--panel); - border: 1px solid var(--parchment-3); - border-radius: 10px; - padding: 16px; -} - -.btn { - display: inline-flex; - align-items: center; - justify-content: center; - gap: 8px; - border-radius: 6px; - padding: 9px 16px; - font-weight: 600; - background: var(--panel); - color: var(--ink); - border: 1px solid var(--line-strong); - transition: background 0.15s, color 0.15s, border-color 0.15s; -} - -.btn:hover:not(:disabled) { - background: var(--parchment-2); - border-color: var(--wood); -} - -.btn:disabled { - opacity: 0.55; - cursor: default; -} - -.btn.primary { - background: var(--amber); - color: var(--on-amber); - border-color: transparent; -} - -.btn.primary:hover:not(:disabled) { - background: color-mix(in srgb, var(--amber) 85%, white); -} - -.btn.primary:disabled { - box-shadow: none; -} - -.btn.ghost { - background: transparent; - color: var(--ink); - border-color: var(--wood); -} - -.btn.ghost:hover:not(:disabled) { - background: var(--parchment-2); -} - -/* A small square control — the tiles' pull arrow and ⋯ trigger (device page, ride library). */ -.iconbtn { - display: inline-flex; - align-items: center; - justify-content: center; - width: 30px; - height: 30px; - padding: 0; - flex: none; - border-radius: 9px; - border: 1px solid var(--line-strong); - background: var(--panel); - color: var(--ink-soft); - font-size: 15px; - line-height: 1; - transition: color 0.15s, border-color 0.15s; -} - -.iconbtn:hover:not(:disabled) { - color: var(--ink); - border-color: var(--wood); -} - -/* The gallery grid the device page's tiles sit in (~3 columns at the page's 920px width). */ -.tilegrid { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); - gap: 12px; -} - -.chip { - display: inline-flex; - align-items: center; - gap: 6px; - background: var(--parchment); - border: 1px solid var(--parchment-3); - border-radius: 999px; - padding: 4px 10px; - font-size: 13px; - color: var(--ink); -} - -.chip button { - background: none; - border: none; - color: var(--ink-faint); - padding: 0 2px; - font-size: 14px; - line-height: 1; -} - -.chip button:hover { - color: var(--coral); -} - -.muted { - color: var(--ink-soft); -} - -.faint { - color: var(--ink-faint); -} - -.small { - font-size: 12.5px; -} - -.mono { - font-family: var(--mono); -} - -/* Segmented toggle (Regions | Draw box) */ -.seg { - display: inline-flex; - border: 1px solid var(--parchment-3); - border-radius: 999px; - overflow: hidden; - background: var(--parchment); -} - -.seg button { - border: none; - background: transparent; - color: var(--ink-soft); - padding: 6px 14px; - font-size: 13px; -} - -.seg button.active { - background: var(--ink); - color: var(--parchment); -} - -:focus-visible { outline: 2px solid var(--forest); outline-offset: 3px; } -input { accent-color: var(--forest); } -::selection { background: var(--amber); color: var(--on-amber); } - -.region-popup { - display: flex; - flex-direction: column; - gap: 4px; - max-height: 220px; - overflow: auto; -} - -.region-popup button { - text-align: left; - background: transparent; - border: 1px solid transparent; - border-radius: 7px; - padding: 5px 9px; - font-size: 13px; - color: var(--ink); -} - -.region-popup button:hover { - background: var(--parchment-2); -} - -.region-popup button.selected { - border-color: var(--forest); - color: var(--forest-deep); - font-weight: 600; -} - -/* Catalog states in the click popup: a baked region carries a forest dot, one - the catalog doesn't have (or the device can't read) carries the reason. */ -.region-popup button.tone-available::before { - content: ""; - display: inline-block; - width: 7px; - height: 7px; - margin-right: 7px; - border-radius: 50%; - background: var(--forest); -} - -.region-popup button .tag { - margin-left: 8px; - font-size: 11.5px; - color: var(--ink-faint); -} - -.region-popup button.tone-unsupported .tag { - color: #8a6410; -} - -.bbox-handle { - background: var(--parchment); - border: 2px solid var(--coral); - border-radius: 4px; -} - -.bbox-handle-nw, -.bbox-handle-se { - cursor: nwse-resize; -} - -.bbox-handle-ne, -.bbox-handle-sw { - cursor: nesw-resize; -} - diff --git a/builder/web/test-support/coverage/Selection.svelte b/builder/web/test-support/coverage/Selection.svelte deleted file mode 100644 index d10d502cb6..0000000000 --- a/builder/web/test-support/coverage/Selection.svelte +++ /dev/null @@ -1,7 +0,0 @@ - - - -

Catalog: {store.client.baseUrl}

diff --git a/builder/web/tests/browser/assemble-download.test.js b/builder/web/tests/browser/assemble-download.test.js deleted file mode 100644 index 255f5cc006..0000000000 --- a/builder/web/tests/browser/assemble-download.test.js +++ /dev/null @@ -1,138 +0,0 @@ -/** - * The builder's download journey, in a real browser, on the shipped `dist/web` build. - * - * Pick the fixture region from a digest-pinned loopback catalog, let the app fetch and verify the - * cells into OPFS, assemble them in the real worker through the real wasm bridge, and save the - * `.obcm`. The downloaded bytes must be the checked-in `expected/map.obcm` — the file - * `cargo run -p obcm-assemble` wrote from the same cells — so this is the third host held to those - * bytes, after the native test and the Node bridge test, and the only one that runs the worker, - * OPFS and the download path that ship. - * - * Nothing leaves loopback. The basemap is presentational and is answered with a local pixel; any - * other off-origin request is aborted and fails the test. - */ - -import { expect, test } from '@playwright/test'; -import { createHash } from 'node:crypto'; -import { mkdir, readFile, writeFile } from 'node:fs/promises'; -import { dirname, join } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { BASEMAP, basemapResponse } from './basemap-stub.js'; - -const REPO = join(dirname(fileURLToPath(import.meta.url)), '../../../..'); -const EXPECTED = join(REPO, 'builder/wasm/tests/fixture/expected/map.obcm'); -const CATALOG_LOG = join(REPO, '.artifacts/web-builder/catalog.jsonl'); -const REGION = 'Bridge Fixture'; - -const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex'); - -test('assembles the fixture region in the tab and downloads the pinned map', async ({ page }, testInfo) => { - const diagnostics = [`browser: ${page.context().browser().version()}`]; - const errors = []; - const offOrigin = []; - const downloads = []; - page.on('download', (download) => downloads.push(download)); - page.on('console', (message) => { - diagnostics.push(`${message.type()}: ${message.text()}`); - if (message.type() === 'error') errors.push(message.text()); - }); - page.on('pageerror', (error) => { - diagnostics.push(`pageerror: ${error.stack}`); - errors.push(error.message); - }); - page.on('worker', (worker) => diagnostics.push(`worker: ${worker.url()}`)); - - await page.route('**/*', (route) => { - const url = new URL(route.request().url()); - if (url.hostname === '127.0.0.1' || url.hostname === 'localhost') return route.continue(); - offOrigin.push(url.href); - if (url.hostname === BASEMAP) return route.fulfill(basemapResponse(url)); - return route.abort(); - }); - - let failure; - try { - await page.goto('/'); - - // The region tool is armed when the page opens. - const search = page.getByLabel('Search regions'); - await expect(search).toBeVisible(); - await search.fill('Bridge'); - // The price is in the label and the formatter owns its spelling, so match the prefix. - await page.locator(`[aria-label^="Add ${REGION} ("]`).click(); - await expect(page.locator(`[aria-label="${REGION} is already in the map"]`)).toBeVisible(); - - await expect(page.locator('.ledger .total')).toContainText('estimated total'); - const originalTotal = await page.locator('.ledger .total').innerText(); - await page.getByRole('button', { name: 'Draw a box' }).click(); - const map = page.locator('.leaflet-container'); - const bounds = await map.boundingBox(); - expect(bounds).not.toBeNull(); - const x = bounds.x + bounds.width / 2; - const y = bounds.y + bounds.height / 2; - await page.mouse.move(x - 30, y - 30); - await page.mouse.down(); - await page.mouse.move(x + 30, y + 30, { steps: 8 }); - await page.mouse.up(); - const boxPart = page.locator('.parts li').filter({ hasText: 'Box' }); - await expect(boxPart).toBeVisible(); - await expect(page.locator('.ledger .total')).toContainText('estimated total'); - await expect(page.locator('.ledger .total')).not.toHaveText(/^0 B/); - await boxPart.getByRole('button', { name: /^Remove Box/ }).click(); - await expect(boxPart).toHaveCount(0); - await expect(page.locator('.ledger .total')).toHaveText(originalTotal); - - const styles = page.locator('.style-options'); - await expect(styles).not.toHaveAttribute('open'); - await styles.locator('summary').click(); - await expect(styles.getByRole('button', { name: 'Edit the colours' })).toBeVisible(); - await styles.locator('summary').click(); - await expect(styles).not.toHaveAttribute('open'); - - const download = page.getByRole('button', { name: 'Download map' }); - // Enabled only once the ledger is final and the memory projection has been admitted. - await expect(download).toBeEnabled(); - const [saved] = await Promise.all([page.waitForEvent('download'), download.click()]); - - await expect(page.locator('.done')).toBeVisible(); - // The shipped path, not the fallback: cells read out of OPFS through sync access handles and - // the map written into OPFS from inside the wasm call. A browser without them buffers both, - // which is a different code path and would pass every other assertion here. - await expect(page.locator('.done')).toContainText(/cells streamed\s*·\s*map disk/); - expect(saved.suggestedFilename()).toBe(`${REGION}.obcm`); - - const want = await readFile(EXPECTED); - const got = await readFile(await saved.path()); - diagnostics.push(`downloaded ${got.byteLength} B, sha256 ${sha256(got)}`); - expect(got.byteLength).toBe(want.byteLength); - expect(sha256(got)).toBe(sha256(want)); - - // Nothing in the catalog, ledger or parts list reported a failure it recovered from. - await expect(page.locator('.catalog-error, .ledger .error, .parts .retry')).toHaveCount(0); - - // The server's log: its first record names what it published, the rest are the requests. - const records = (await readFile(CATALOG_LOG, 'utf8')).trim().split('\n').map((l) => JSON.parse(l)); - const requested = new Set(records.slice(1).filter((r) => r.kind === 'object').map((r) => r.path)); - // The standalone schema is reference metadata; this client reads the root's inline schema. - expect(records[0].served).toContain('/catalog/schema.json'); - const required = records[0].served.filter((path) => path !== '/catalog/schema.json'); - expect(required.filter((path) => !requested.has(path))).toEqual([]); - expect(records.slice(1).filter((r) => r.kind === 'missing' && r.path.startsWith('/catalog/'))).toEqual([]); - await page.waitForTimeout(500); - expect(downloads).toEqual([saved]); - } catch (error) { - failure = error; - } - - await mkdir(testInfo.outputDir, { recursive: true }); - const path = testInfo.outputPath('browser-diagnostics.log'); - await writeFile(path, diagnostics.join('\n')); - await testInfo.attach('browser-diagnostics', { path, contentType: 'text/plain' }); - if (failure) throw failure; - - // Last, after every other await in this test, because these two accumulate: an off-origin request - // or a console error raised while the page settled after the download is still a failure, and - // asserting them mid-journey would only cover what had happened by then. - expect([...new Set(offOrigin.map((href) => new URL(href).hostname))].filter((h) => h !== BASEMAP)).toEqual([]); - expect(errors).toEqual([]); -}); diff --git a/builder/web/tests/browser/basemap-config.json b/builder/web/tests/browser/basemap-config.json deleted file mode 100644 index fc52563ed5..0000000000 --- a/builder/web/tests/browser/basemap-config.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "basemap": "https://basemap.test/basemap.json", - "glyphs": "https://basemap.test/fonts/{fontstack}/{range}.pbf", - "sprites": "https://basemap.test/sprites", - "attribution": "Basemap test data", - "landcover_attribution": "Land cover test data" -} diff --git a/builder/web/tests/browser/basemap-stub.js b/builder/web/tests/browser/basemap-stub.js deleted file mode 100644 index f44fbe2688..0000000000 --- a/builder/web/tests/browser/basemap-stub.js +++ /dev/null @@ -1,25 +0,0 @@ -/** The host the journeys build the planner basemap against (see `basemap-config.json`). It is decoration; no journey needs a tile. */ -export const BASEMAP = 'basemap.test'; - -/** One transparent pixel, so the sprite sheet loads without a failure. */ -const PIXEL = Buffer.from( - 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', - 'base64', -); - -/** The response for a request to `BASEMAP`: a TileJSON, an empty sprite sheet, and no tiles. */ -export function basemapResponse(url) { - const headers = { 'access-control-allow-origin': '*' }; - switch (url.pathname) { - case '/basemap.json': - return { headers, json: { tilejson: '3.0.0', tiles: [`https://${BASEMAP}/{z}/{x}/{y}.mvt`], maxzoom: 14 } }; - case '/sprites/light.json': - case '/sprites/dark.json': - return { headers, json: {} }; - case '/sprites/light.png': - case '/sprites/dark.png': - return { headers, contentType: 'image/png', body: PIXEL }; - default: - return { headers, status: 204 }; - } -} diff --git a/builder/web/tests/browser/basemap.test.js b/builder/web/tests/browser/basemap.test.js deleted file mode 100644 index b59007a7ad..0000000000 --- a/builder/web/tests/browser/basemap.test.js +++ /dev/null @@ -1,56 +0,0 @@ -import { expect, test } from '@playwright/test'; -import { BASEMAP, basemapResponse } from './basemap-stub.js'; - -async function stubMap(page, fail = false) { - const external = []; - await page.route('**/*', (route) => { - const url = new URL(route.request().url()); - if (url.hostname === '127.0.0.1') return route.continue(); - external.push(url.href); - if (url.hostname !== BASEMAP) return route.abort(); - return fail ? route.fulfill({ status: 503 }) : route.fulfill(basemapResponse(url)); - }); - return external; -} - -test('loads the shared basemap and changes its theme without public tiles', async ({ page }) => { - const external = await stubMap(page); - const light = page.waitForResponse(`https://${BASEMAP}/sprites/light.json`); - await page.goto('/'); - await light; - await expect(page.locator('.leaflet-gl-layer canvas')).toBeVisible(); - const dark = page.waitForResponse(`https://${BASEMAP}/sprites/dark.json`); - await page.evaluate(() => { document.documentElement.dataset.theme = 'dark'; }); - await dark; - await expect(page.locator('.basemap-warning')).toHaveCount(0); - expect(external.length).toBeGreaterThan(0); - expect(external.every((url) => new URL(url).hostname === BASEMAP)).toBe(true); -}); - -test('keeps selection available when the basemap is unreachable', async ({ page }) => { - const external = await stubMap(page, true); - await page.goto('/'); - await expect(page.getByRole('status').filter({ hasText: 'Map background unavailable.' })).toBeVisible(); - await expect(page.getByLabel('Search regions')).toBeVisible(); - await page.getByLabel('Search regions').fill('Bridge'); - await page.getByRole('button', { name: /^Add Bridge Fixture \(/ }).click(); - await expect(page.getByRole('button', { name: 'Bridge Fixture is already in the map' })).toBeVisible(); - expect(external.every((url) => new URL(url).hostname === BASEMAP)).toBe(true); -}); - -test('reports missing WebGL2 without requesting public tiles', async ({ page }) => { - const external = await stubMap(page); - const errors = []; - page.on('pageerror', (error) => errors.push(error.message)); - await page.addInitScript(() => { - const original = HTMLCanvasElement.prototype.getContext; - HTMLCanvasElement.prototype.getContext = function (type, ...args) { - return type === 'webgl2' ? null : original.call(this, type, ...args); - }; - }); - await page.goto('/'); - await expect(page.locator('.basemap-warning')).toHaveText('Map background unavailable.'); - await expect(page.locator('.leaflet-gl-layer')).toHaveCount(0); - expect(external).toEqual([]); - expect(errors).toEqual([]); -}); diff --git a/builder/web/tests/browser/live-memory.test.ts b/builder/web/tests/browser/live-memory.test.ts deleted file mode 100644 index b54abaddf5..0000000000 --- a/builder/web/tests/browser/live-memory.test.ts +++ /dev/null @@ -1,232 +0,0 @@ -/** - * The browser memory gate: a country-scale assembly must not hold more wasm memory than the - * projection it was admitted on. - * - * The builder refuses a selection whose projected peak does not fit a tab. That projection is - * arithmetic, and arithmetic cannot fail when the assembler buffers a whole map anyway — the - * estimator would still return its number and the preflight would still admit the run. This suite - * is the measurement that can fail: it assembles the largest published region in the shipped - * `dist/web` build, reads the linear memory the worker reports at `done`, and holds it against the - * same estimate's `peakBytes` for that selection and that sort budget. - * - * `peakBytes` is the right side of that comparison because both sides are whole-memory figures. - * The reported number is all of linear memory; `peakBytes` is the estimator's bottom line for all - * of it — engine, resident input and resident output — and it is the number `fits` is decided on - * and the download admitted on. The engine term alone would be a component: the terrain squares - * the bridge copies in and the engine's block caches are priced in `inputBytes`, and they are in - * linear memory too. Held to the bottom line the gate needs no margin, and it loses no power, - * because what it exists to catch is not small — a buffered map is the whole map, and buffered - * cells are the whole selection. - * - * It reads a figure; it does not re-fit one. An earlier measurement of the same selection, taken - * on a differently staged page, read less linear memory than this journey does. Nothing here - * isolates the engine term from the rest of the projection, so that difference stays unattributed - * and the estimator's own constants are not moved on the strength of it. - * - * It needs the live catalogue, so it is `live`: the published objects are the only input large - * enough that buffering one would show. The fixture region in `assemble-download.test.js` is five - * cells; a run that buffered all of it would still sit under the estimate. - * - * Two things about the browser are not the runner's defaults, and both are about the runner rather - * than the product. Chromium runs with CORS off, because the catalogue's CDN answers - * `Access-Control-Allow-Origin` for the deployed origins only and this page is served from - * loopback. And the run gets an ordinary browser profile instead of the runner's throwaway - * context, because Chromium caps an incognito context's storage at 3 GiB while a profile on the - * same machine is given several times that, and a country-scale run holds its cells, its map and - * its spill on disk at once. Nothing else is changed: the build, the worker, the wasm engine, the - * OPFS seams and the verify pass are the shipping ones, and `assemble-download.test.js` covers the - * same journey under an enforcing browser. - */ - -import { chromium, expect, test } from '@playwright/test'; -import { createHash } from 'node:crypto'; -import { createReadStream } from 'node:fs'; -import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { dirname, join } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -import { estimateMemory, initAssemble } from '../../src/lib/assemble/bridge'; -import { BASEMAP, basemapResponse } from './basemap-stub.js'; - -const HERE = dirname(fileURLToPath(import.meta.url)); -const WASM = join(HERE, '../../src/lib/core/pkg/obc_builder_bridge_bg.wasm'); -const DOWNLOAD_STEP = join(HERE, '../../src/components/coverage/DownloadStep.svelte'); - -/** The host the catalogue must come from: a loopback fixture would make this gate meaningless. */ -const LIVE_HOST = 'maps.openbikecomputer.com'; - -/** Below this the gate cannot fail, because buffering the whole selection would still fit. */ -const MEANINGFUL_BYTES = 512 * 1024 * 1024; - -/** …and above this the suite is a 9 GB download rather than a measurement. A publish that crosses - * it needs a deliberate choice of region, not this one. */ -const AFFORDABLE_BYTES = 4 * 1024 * 1024 * 1024; - -/** The engine's sort budget the download screen runs with, read from it so the two cannot drift. */ -async function sortBudgetBytes(): Promise { - const source = await readFile(DOWNLOAD_STEP, 'utf8'); - const match = /SORT_BUDGET_BYTES = (\d+) \* 1024 \* 1024/.exec(source); - expect(match, 'DownloadStep.svelte no longer states SORT_BUDGET_BYTES the way this suite reads it').toBeTruthy(); - return Number(match![1]) * 1024 * 1024; -} - -function sha256(path: string): Promise { - const hash = createHash('sha256'); - return new Promise((resolve, reject) => { - createReadStream(path).on('error', reject).on('data', (c) => hash.update(c)).on('end', () => resolve(hash.digest('hex'))); - }); -} - -interface Band { - id: string; - role: string; -} - -interface Region { - name: string; - bytes: number; - bytes_by_band: Record; - terrain?: { bytes: number }; -} - -test('holds a country-scale assembly to the memory its estimate promised', async ({}, testInfo) => { - const options = testInfo.project.use; - const profileDir = await mkdtemp(join(tmpdir(), 'obc-live-memory-')); - const context = await chromium.launchPersistentContext(profileDir, { - args: options.launchOptions?.args, - viewport: options.viewport, - }); - const page = context.pages()[0] ?? (await context.newPage()); - page.setDefaultTimeout(options.actionTimeout ?? 30_000); - - const notes: string[] = []; - const errors: string[] = []; - page.on('console', (m) => { - notes.push(`${m.type()}: ${m.text()}`); - if (m.type() === 'error') errors.push(m.text()); - }); - page.on('pageerror', (e) => { - notes.push(`pageerror: ${e.stack}`); - errors.push(e.message); - }); - // Only the basemap is intercepted. Everything else, the catalogue objects above all, reaches - // the network untouched: routing them would put 890 MB through the test protocol. - await page.route(`https://${BASEMAP}/**`, (route) => - route.fulfill(basemapResponse(new URL(route.request().url()))), - ); - - // Both subscribed before the page loads, because each is posted once and the catalogue lands - // while `goto` is still resolving. - const profile = page - .waitForEvent('console', { - predicate: (m) => m.text().startsWith('[assemble] run'), - timeout: testInfo.timeout, - }) - .then((m) => m.args()[1].jsonValue() as Promise<{ wasmMemoryBytes: number }>); - // The catalogue the tab actually read, taken from its own response: the suite never names a URL, - // so it cannot measure a different catalogue than the one the build points at. - const rootResponse = page.waitForResponse((r) => r.url().endsWith('/catalog.json') && r.ok()); - - let failure: unknown; - try { - await page.goto(String(options.baseURL)); - notes.push(`browser: ${await page.evaluate(() => navigator.userAgent)}`); - - const root = await rootResponse; - expect(new URL(root.url()).hostname, 'this build is not pointed at the published catalogue').toBe(LIVE_HOST); - const catalog = JSON.parse(await root.text()) as { - generated_at: string; - schema: { bands: Band[] }; - regions: Region[]; - }; - notes.push(`catalog: ${root.url()} generated_at ${catalog.generated_at}`); - - // The largest published region, priced the way `ledger.ts` prices one. - const region = catalog.regions.reduce((a, b) => (b.bytes > a.bytes ? b : a)); - const core = catalog.schema.bands.find((b) => b.role === 'core')!; - const terrainBytes = region.terrain?.bytes ?? 0; - const totalCellBytes = region.bytes + terrainBytes; - expect(totalCellBytes, 'the published catalogue is too small for this gate to be able to fail').toBeGreaterThan( - MEANINGFUL_BYTES, - ); - expect(totalCellBytes, 'the published catalogue is larger than this suite is willing to download').toBeLessThan( - AFFORDABLE_BYTES, - ); - - await initAssemble(await readFile(WASM)); - const estimate = await estimateMemory( - region.bytes_by_band[core.id], - totalCellBytes, - terrainBytes, - await sortBudgetBytes(), - { inputOnDisk: true, outputSunk: true }, - ); - notes.push( - `selection: ${region.name}, ${totalCellBytes} B (${terrainBytes} B terrain)`, - `estimate: engine ${estimate.engineBytes} B, input ${estimate.inputBytes} B, ` + - `output ${estimate.outputBytes} B, peak ${estimate.peakBytes} B, fits ${estimate.fits}`, - ); - - const search = page.getByLabel('Search regions'); - await expect(search).toBeVisible(); - await search.fill(region.name); - await page.locator(`[aria-label^="Add ${region.name} ("]`).click(); - await expect(page.locator(`[aria-label="${region.name} is already in the map"]`)).toBeVisible(); - - const download = page.getByRole('button', { name: 'Download map' }); - // Enabled only once the ledger is final and the memory projection has been admitted. - await expect(download).toBeEnabled(); - const saving = page.waitForEvent('download', { timeout: testInfo.timeout }); - await download.click(); - // A refused or failed run never produces a download, so the failure is read off the screen - // rather than waited out. `.line.warn` is the download screen's own error paragraph. - const saved = await Promise.race([ - saving, - page - .locator('.line.warn') - .waitFor({ state: 'visible', timeout: testInfo.timeout }) - .then(async () => { - throw new Error(`the run failed: ${await page.locator('.line.warn').innerText()}`); - }), - ]); - - await expect(page.locator('.done')).toBeVisible(); - // The shipped path. A browser that buffered the cells or the map instead would be measuring a - // mode the estimate was not taken for. - await expect(page.locator('.done')).toContainText(/cells streamed\s*·\s*map disk/); - - // The engine verifies the sealed map by reading it back, and refuses the run when it disagrees. - // Reaching `.done` with no error is that verdict; nothing else here re-checks the bytes. - const path = (await saved.path())!; - notes.push(`map: ${saved.suggestedFilename()}, ${(await stat(path)).size} B, sha256 ${await sha256(path)}`); - await saved.delete(); - - const { wasmMemoryBytes } = await profile; - notes.push( - `wasm linear memory: ${wasmMemoryBytes} B, ` + - `${(wasmMemoryBytes / estimate.peakBytes).toFixed(3)} x the projected peak`, - ); - expect(wasmMemoryBytes).toBeGreaterThan(0); - expect(wasmMemoryBytes, 'the assembly held more memory than its estimate priced').toBeLessThanOrEqual( - estimate.peakBytes, - ); - expect(errors).toEqual([]); - } catch (error) { - failure = error; - await mkdir(testInfo.outputDir, { recursive: true }); - await page.screenshot({ path: testInfo.outputPath('failure.png'), fullPage: true }).catch(() => {}); - } finally { - await context.close(); - // The profile holds the cells, the map and the spill — gigabytes that mean nothing outside - // this run. - await rm(profileDir, { recursive: true, force: true }); - } - - // The numbers are the point of the run, so they are recorded whether it passed or not. - await mkdir(testInfo.outputDir, { recursive: true }); - const log = testInfo.outputPath('live-memory.log'); - await writeFile(log, notes.join('\n')); - await testInfo.attach('live-memory', { path: log, contentType: 'text/plain' }); - if (failure) throw failure; -}); diff --git a/builder/web/tests/browser/package.json b/builder/web/tests/browser/package.json index 2999b73288..f1467d438b 100644 --- a/builder/web/tests/browser/package.json +++ b/builder/web/tests/browser/package.json @@ -3,10 +3,6 @@ "private": true, "type": "module", "scripts": { - "pretest": "node -e \"require('node:fs').rmSync('../../../../.artifacts/web-builder', { recursive: true, force: true })\" && VITE_PLANNER_CONFIG=\"$(cat basemap-config.json)\" VITE_CATALOG_URL=/catalog/catalog.json npm run build:web --prefix ../..", - "test": "playwright test", - "pretest:live": "node -e \"require('node:fs').rmSync('../../../../.artifacts/web-builder-live', { recursive: true, force: true })\" && VITE_PLANNER_CONFIG=\"$(cat basemap-config.json)\" VITE_CATALOG_URL=https://maps.openbikecomputer.com/cell-catalog/catalog.json npm run build:web --prefix ../..", - "test:live": "playwright test --config playwright.live.config.js", "pretest:planner": "VITE_FAKE_DEVICE=1 VITE_PLANNER_CONFIG=\"$(cat planner/config.json)\" npm run build:planner --prefix ../..", "test:planner": "playwright test --config playwright.planner.config.js", "pretest:data": "npm run build:data --prefix ../..", diff --git a/builder/web/tests/browser/planner/area.test.js b/builder/web/tests/browser/planner/area.test.js index c563468cfe..94fe894941 100644 --- a/builder/web/tests/browser/planner/area.test.js +++ b/builder/web/tests/browser/planner/area.test.js @@ -2,6 +2,7 @@ import { expect, test } from '@playwright/test'; import { spawn } from 'node:child_process'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { HOSTS, respond } from './stubs.js'; const REPO = join(dirname(fileURLToPath(import.meta.url)), '../../../../..'); const PLANNER_CATALOG = 'https://maps.openbikecomputer.com/planner/catalog.json'; @@ -27,13 +28,23 @@ const device = { bytes: { map: 9_000_000, routes: 0, rides: 0, other: 0 }, came: null, skipped: [], }; -/** Answers the planner catalogue with the fixture catalog as the device catalog, and nothing else outside the machine. */ -async function open(page, hash) { +/** + * Answers the planner catalogue with the fixture catalog as the device catalog, and nothing else outside the machine. + * `tiles: 'answer'` answers the tile host with the stubs, and `tiles: 'fail'` with 503. `outside` collects each other request + * that leaves the machine. + */ +async function open(page, hash, { tiles, outside = [] } = {}) { const errors = []; page.on('pageerror', error => errors.push(error.message)); - await page.route(url => url.hostname !== '127.0.0.1', route => route.request().url() === PLANNER_CATALOG - ? route.fulfill({ headers: CORS, json: { format: 1, active: { id: 'test', device_catalog: `${origin}/catalog/catalog.json` } } }) - : route.abort()); + await page.route(url => url.hostname !== '127.0.0.1', route => { + const request = route.request(); + if (request.url() === PLANNER_CATALOG) { + return route.fulfill({ headers: CORS, json: { format: 1, active: { id: 'test', device_catalog: `${origin}/catalog/catalog.json` } } }); + } + outside.push(request.url()); + if (!tiles || new URL(request.url()).hostname !== HOSTS.tiles) return route.abort(); + return route.fulfill(tiles === 'fail' ? { headers: CORS, status: 503 } : respond(request) ?? { headers: CORS, status: 204 }); + }); // The catalog has another port than the page, so its answers need the header that the real host sends. await page.route(url => url.origin === origin, async route => { const response = await route.fetch(); @@ -125,6 +136,44 @@ test('the window Colours opens the colour editor over it, and Cancel goes back t expect(errors).toEqual([]); }); +test('the base map loads in the light and the dark look, from the tile host only', async ({ page }) => { + const outside = []; + const light = page.waitForResponse(`https://${HOSTS.tiles}/sprites/light.json`); + const errors = await open(page, '#/device/area', { tiles: 'answer', outside }); + await light; + await expect(page.locator('.leaflet-gl-layer canvas')).toBeVisible(); + const dark = page.waitForResponse(`https://${HOSTS.tiles}/sprites/dark.json`); + await page.evaluate(() => { document.documentElement.dataset.theme = 'dark'; }); + await dark; + await expect(page.locator('.basemap-warning')).toHaveCount(0); + expect(outside.length).toBeGreaterThan(0); + expect(outside.every(url => new URL(url).hostname === HOSTS.tiles)).toBe(true); + expect(errors).toEqual([]); +}); + +test('when the base map does not load, the map says so and a click still adds a region', async ({ page }) => { + const errors = await open(page, '#/device/area', { tiles: 'fail' }); + await expect(page.getByRole('status').filter({ hasText: 'Map background unavailable.' })).toBeVisible(); + await page.locator('.leaflet-container').click(); + await expect(page.locator('.parts li')).toHaveText(['Bridge Fixture']); + expect(errors).toEqual([]); +}); + +test('a browser with no WebGL2 gets the note and asks the tile host for nothing', async ({ page }) => { + await page.addInitScript(() => { + const original = HTMLCanvasElement.prototype.getContext; + HTMLCanvasElement.prototype.getContext = function (type, ...args) { + return type === 'webgl2' ? null : original.call(this, type, ...args); + }; + }); + const outside = []; + const errors = await open(page, '#/device/area', { tiles: 'answer', outside }); + await expect(page.locator('.basemap-warning')).toHaveText('Map background unavailable.'); + await expect(page.locator('.leaflet-gl-layer')).toHaveCount(0); + expect(outside).toEqual([]); + expect(errors).toEqual([]); +}); + test('"Send the map" builds the map that waits and puts it on the device; Stop in the middle keeps it waiting', async ({ page }) => { await library(page, () => window.coverTest.library.setState('nextMap', { regions: ['bridge-fixture'], boxes: [], light: 'default', dark: 'dusk', bytes: 16_000 })); const errors = await open(page, '?fake-device#/device'); diff --git a/builder/web/tests/browser/playwright.config.js b/builder/web/tests/browser/playwright.config.js deleted file mode 100644 index d7e68d9174..0000000000 --- a/builder/web/tests/browser/playwright.config.js +++ /dev/null @@ -1,46 +0,0 @@ -import { defineConfig } from '@playwright/test'; -import { loopbackPort } from '../../../../tools/loopback_port.mjs'; - -// One origin serves the shipped `dist/web` build and the pinned fixture catalog, so the tab fetches -// cells the way a same-origin deployment does — no CORS, and nothing outside loopback to reach. -// `pretest` builds `dist/web` with `VITE_CATALOG_URL=/catalog/catalog.json`, which is root-relative, -// so the port lives here and only here. -const PORT = await loopbackPort('OBC_BROWSER_PORT'); - -export default defineConfig({ - testDir: '.', - testMatch: '*.test.js', - testIgnore: ['planner/**', 'data/**', 'trailview/**'], - // The journey downloads five cells and three terrain squares, assembles them in wasm and reads - // the map back out of OPFS. Generous, because a timeout here is a failure, never a retry. - timeout: 120_000, - expect: { timeout: 15_000 }, - workers: 1, - retries: 0, - forbidOnly: true, - outputDir: '../../../../.artifacts/web-builder/browser', - reporter: [ - ['list'], - ['junit', { outputFile: '../../../../.artifacts/web-builder/junit.xml' }], - ], - use: { - browserName: 'chromium', - baseURL: `http://127.0.0.1:${PORT}`, - viewport: { width: 1440, height: 1100 }, - reducedMotion: 'no-preference', - actionTimeout: 15_000, - navigationTimeout: 15_000, - screenshot: 'only-on-failure', - trace: 'retain-on-failure', - }, - webServer: { - command: - `python3 ../../../../tools/fixture_catalog.py --catalog web-assemble --port ${PORT}` + - ' --static ../../dist/web --log ../../../../.artifacts/web-builder/catalog.jsonl', - url: `http://127.0.0.1:${PORT}/catalog/catalog.json`, - reuseExistingServer: false, - timeout: 10_000, - stdout: 'pipe', - stderr: 'pipe', - }, -}); diff --git a/builder/web/tests/browser/playwright.live.config.js b/builder/web/tests/browser/playwright.live.config.js deleted file mode 100644 index 291f112349..0000000000 --- a/builder/web/tests/browser/playwright.live.config.js +++ /dev/null @@ -1,41 +0,0 @@ -import { defineConfig } from '@playwright/test'; -import { loopbackPort } from '../../../../tools/loopback_port.mjs'; - -// The memory gate's own run. Loopback serves only the shipped `dist/web`; the catalogue and its -// objects come from the live CDN, which is why this is a `live` suite. -const PORT = await loopbackPort('OBC_BROWSER_PORT'); - -export default defineConfig({ - testDir: '.', - testMatch: 'live-memory.test.ts', - // Downloads about 890 MB, assembles it and reads the map back. Generous, because a timeout here - // is a failure, never a retry. - timeout: 30 * 60_000, - expect: { timeout: 60_000 }, - workers: 1, - retries: 0, - forbidOnly: true, - outputDir: '../../../../.artifacts/web-builder-live/browser', - reporter: [ - ['list'], - ['junit', { outputFile: '../../../../.artifacts/web-builder-live/junit.xml' }], - ], - // The test launches its own persistent context (see its header), so these are the settings it - // reads rather than fixture options the runner applies. - use: { - // The CDN's `Access-Control-Allow-Origin` names the deployed origins, and this page is on - // loopback. The suite measures memory, not the same-origin policy. - launchOptions: { args: ['--disable-web-security'] }, - baseURL: `http://127.0.0.1:${PORT}`, - viewport: { width: 1440, height: 1100 }, - actionTimeout: 30_000, - }, - webServer: { - command: `python3 serve.py ${PORT} ../../dist/web`, - url: `http://127.0.0.1:${PORT}`, - reuseExistingServer: false, - timeout: 10_000, - stdout: 'pipe', - stderr: 'pipe', - }, -}); diff --git a/builder/web/tsconfig.json b/builder/web/tsconfig.json index 7ec63cfc31..8a7acb5079 100644 --- a/builder/web/tsconfig.json +++ b/builder/web/tsconfig.json @@ -13,12 +13,9 @@ "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, - // The platform alias vite.config.ts rewrites per build target. Type - // checking pins it to the dev host — the one `npm run dev` and - // `npm run build` use; the web host is still checked as a file, against - // the `Platform` interface it annotates itself with. + // The platform alias of vite.config.ts, which names the web host in every mode. "paths": { - "$host": ["./src/lib/platform/dev.ts"] + "$host": ["./src/lib/platform/web.ts"] } }, // `test-support/` holds what the suites need and the app must not have: the loader for the wasm diff --git a/builder/web/vite.config.ts b/builder/web/vite.config.ts index 9c31f2c3b7..ba88a4dbc8 100644 --- a/builder/web/vite.config.ts +++ b/builder/web/vite.config.ts @@ -7,57 +7,27 @@ import { thirdPartyLicenses } from "./vite/third-party-licenses"; import { plannerConfig } from "./src/lib/planner/config"; import { testConfig } from "./test-support/planner/config"; -// One frontend, two hosts. Which host `$host` resolves to is decided here, at -// build time — a conditional alias, not a runtime `if` — so the host you did not -// build has no path into the module graph at all. That is what keeps the dev -// server's client out of the static web bundle, rather than trusting a bundler to -// notice that a branch is unreachable. src/lib/platform/bundle.test.ts asserts it -// against the real emitted chunks. -const HOSTS = { - // The local FastAPI server, and the only one `python -m builder.server` - // serves — hence the outDir it already mounts. - dev: { module: "dev", outDir: "../server/static/dist" }, - web: { module: "web", outDir: "dist/web" }, -} as const; - -type HostName = keyof typeof HOSTS; - -// Modes that build one page of their own, into `dist/MODE`: the route planner, the operator page +// Modes that build one page of their own, into `dist/MODE`: the product, the operator page // of `obc data ui` and the TrailView 3D view. const PAGES: Record = { planner: "planner.html", data: "data.html", trailview: "trailview.html" }; -// `vite`/`vite build` default to development/production, and vitest to test — all -// three are the dev host. `--mode web` opts into the other. Anything else is -// a typo, and quietly building the dev host for a mistyped deploy target is the one -// outcome worth failing over. -function hostFor(mode: string): HostName { - if (mode in PAGES) return "web"; - if (mode in HOSTS) return mode as HostName; - if (mode === "development" || mode === "production" || mode === "test") return "dev"; - throw new Error( - `unknown --mode "${mode}": expected one of ${[...Object.keys(HOSTS), ...Object.keys(PAGES)].join(", ")} ` + - "(or development/production/test, which build the dev host)", - ); +// `vite` adds the mode development and vitest the mode test. Anything else is a typo, and +// quietly building a mistyped deploy target is the one outcome worth failing over. +function checkMode(mode: string): void { + if (mode in PAGES || mode === "development" || mode === "test") return; + throw new Error(`unknown --mode "${mode}": expected one of ${Object.keys(PAGES).join(", ")} (or development/test)`); } export default defineConfig(({ mode }) => { - const host = HOSTS[hostFor(mode)]; + checkMode(mode); // A preview config that the planner cannot use fails the build. Without one, the planner reads the live catalogue. const preview = loadEnv(mode, process.cwd(), "VITE_PLANNER_CONFIG").VITE_PLANNER_CONFIG; if ((mode === "planner" || mode === "trailview") && preview) plannerConfig(JSON.parse(preview)); - // Dev mode: `python -m builder.server --no-browser` on :8000 serves - // the API; Vite proxies it (plain http-proxy streams SSE fine). - // `vite --mode data` sends the page's `/api/cli` to `obc data ui` instead. It keeps the Host: + // `vite --mode data` sends the page's `/api/cli` to `obc data ui`. It keeps the Host: // `obc data ui` refuses an Origin that is not `http://` and the Host. - const proxy: Record = mode === "data" ? { - "/api": { target: "http://127.0.0.1:8700", changeOrigin: false }, - } : { - "/api": `http://127.0.0.1:${process.env.OBC_BUILDER_PORT || "8000"}`, - }; + const proxy = mode === "data" ? { "/api": { target: "http://127.0.0.1:8700", changeOrigin: false } } : undefined; return { - // base "./" keeps every asset URL relative, so the built app works mounted at - // "/" (local FastAPI) or under a sub-path (a future single-server deployment - // serving landing + docs + builder behind one reverse proxy). + // base "./" keeps every asset URL relative, so a built page works under any sub-path. base: "./", // The licence notices ride along with the bundle, which is a distribution. plugins: [svelte(), thirdPartyLicenses(), stampVersion(), bundleVersions()], @@ -66,15 +36,16 @@ export default defineConfig(({ mode }) => { resolve: { // Root-relative rather than an absolute path so the config needs no // node: builtins (and so no @types/node just to type-check itself). - alias: { $host: `/src/lib/platform/${host.module}.ts` }, + alias: { $host: "/src/lib/platform/web.ts" }, // Component tests run through Vitest's SSR transform even when their // per-file environment supplies a DOM. Select Svelte's client runtime // there so mounted tests exercise the real browser lifecycle. ...(mode === "test" ? { conditions: ["browser"] } : {}), }, build: { - outDir: mode in PAGES ? `dist/${mode}` : host.outDir, - ...(mode in PAGES ? { copyPublicDir: false, rollupOptions: { input: PAGES[mode] } } : {}), + outDir: `dist/${mode}`, + copyPublicDir: false, + rollupOptions: { input: PAGES[mode] }, emptyOutDir: true, }, worker: { @@ -84,8 +55,8 @@ export default defineConfig(({ mode }) => { // // Module workers are Chrome 80, Safari 15, Firefox 114 — comfortably below // what the app already needs elsewhere. A browser under that floor loses the - // in-browser assembly, not the site: the worker only spawns from the - // download step. + // in-browser assembly, not the site: the worker only spawns when a map is + // built. format: "es", // Workers bundle their imports with plugins of their own. plugins: () => [stampVersion()], diff --git a/docs/build_docs.py b/docs/build_docs.py index 9f0a3e6a3a..7988d64ffa 100644 --- a/docs/build_docs.py +++ b/docs/build_docs.py @@ -714,7 +714,7 @@ def site_head(site_root, crumb, nav_toggle=""): of the markup, so a nav change can't drift between the docs and blog shells.""" return fill(SITEHEAD_TEMPLATE.read_text(), {"site_root": site_root, "crumb": crumb, "nav_toggle": nav_toggle, - "builder_link": 'Maps' % esc(site_root), + "builder_link": 'Maps' % esc(site_root), "planner_link": 'Route planner' % esc(site_root), "docs_current": ' aria-current="page"' if crumb == "/ docs" else "", "blog_current": ' aria-current="page"' if crumb == "/ log" else ""}) diff --git a/docs/design/README.md b/docs/design/README.md index 34f723a8cb..523439b32e 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -91,8 +91,8 @@ flowchart LR | --- | --- | --- | --- | --- | | [host-runtime](host-runtime.md) | Runs the device core on a computer or phone instead of the board. | draft | card-storage, device-runtime, foundations, map-reading, navigation, rendering-display | map-assembly, simulators | | [library](library.md) | Keeps the rider's routes, rides and settings in the browser, each route and ride with a summary, and saves and loads them as one backup file. | draft | | route-planning, web-planner | -| [map-assembly](map-assembly.md) | Assembles a device map from published cells. | draft | card-storage, device-link, device-map-baking, device-map-builder, foundations, host-runtime, map-reading, map-style, navigation, rendering-display, route-planning | device-link, device-map-builder, map-style, obc-data, route-planning, web-planner | -| [map-style](map-style.md) | Defines how map features look on the device. | draft | device-map-builder, map-assembly | device-map-builder, map-assembly, web-planner | +| [map-assembly](map-assembly.md) | Assembles a device map from published cells. | draft | card-storage, device-link, device-map-baking, device-map-builder, foundations, host-runtime, map-reading, map-style, navigation, rendering-display, route-planning | device-link, map-style, obc-data, route-planning, web-planner | +| [map-style](map-style.md) | Defines how map features look on the device. | draft | device-map-builder, map-assembly | map-assembly, web-planner | | [route-planning](route-planning.md) | Lets a rider plan a route on a map, in the browser or on the phone. | draft | device-map-builder, library, map-assembly, trailview | device-map-builder, map-assembly, obc-data, trailview, trailview-page, web-planner | ### Data and services @@ -146,17 +146,17 @@ flowchart LR | --- | --- | --- | --- | --- | | [companion-ios](companion-ios.md) | Runs the iPhone app that plans routes, sends them to the device and gets rides back. | approved | | | | [device-firmware](device-firmware.md) | Builds the nRF54L board image from the device systems. | approved | board-inputs, card-storage, device-link, device-runtime, firmware-update, foundations, map-reading, navigation, rendering-display | | -| [device-map-builder](device-map-builder.md) | Runs the map builder, where a rider builds a device map and manages the device, in the browser. | approved | device-link, firmware-update, map-assembly, map-style, route-planning, trailview, website | device-link, map-assembly, map-style, obc-data, route-planning, search, web-planner | +| [device-map-builder](device-map-builder.md) | Holds the build configuration of the web app and the code that its pages share. | approved | device-link, firmware-update, route-planning, trailview | device-link, map-assembly, map-style, obc-data, route-planning, search, web-planner | | [obc-data](obc-data.md) | Runs the `obc data` command and its operator page. | approved | data-engine, device-map-baking, device-map-builder, foundations, map-assembly, route-planning, routing, search, source-preparation, trailview | | | [planner-tile-server](planner-tile-server.md) | Serves the map tiles of a planner release from the storage bucket or from a local folder. | approved | | | | [simulators](simulators.md) | Runs the device core on a computer, a phone or a web page, and sends test input to a real board. | approved | board-inputs, card-storage, data-engine, device-link, device-runtime, firmware-update, foundations, host-runtime, map-reading, navigation, rendering-display, repository-tooling | | | [trailview-page](trailview-page.md) | Opens TrailView, the 3-D view of a region, as its own page in the browser. | approved | route-planning, trailview | | | [web-planner](web-planner.md) | Opens the app at /plan/: the top bar, the pages, and the route planner as one page. | approved | device-link, device-map-builder, firmware-update, library, map-assembly, map-style, route-planning, trailview | | -| [website](website.md) | Publishes the project site, the guide and the blog. | approved | | device-map-builder | +| [website](website.md) | Publishes the project site, the guide and the blog. | approved | | | ## Tangles -- A cycle between card-storage, device-link, device-map-builder, firmware-update, host-runtime, map-assembly, map-style, route-planning, trailview: card-storage -> device-link, device-link -> card-storage, device-link -> device-map-builder, device-link -> firmware-update, device-link -> map-assembly, device-map-builder -> device-link, device-map-builder -> firmware-update, device-map-builder -> map-assembly, device-map-builder -> map-style, device-map-builder -> route-planning, device-map-builder -> trailview, firmware-update -> device-link, host-runtime -> card-storage, map-assembly -> card-storage, map-assembly -> device-link, map-assembly -> device-map-builder, map-assembly -> host-runtime, map-assembly -> map-style, map-assembly -> route-planning, map-style -> device-map-builder, map-style -> map-assembly, route-planning -> device-map-builder, route-planning -> map-assembly, route-planning -> trailview, trailview -> route-planning +- A cycle between card-storage, device-link, device-map-builder, firmware-update, host-runtime, map-assembly, map-style, route-planning, trailview: card-storage -> device-link, device-link -> card-storage, device-link -> device-map-builder, device-link -> firmware-update, device-link -> map-assembly, device-map-builder -> device-link, device-map-builder -> firmware-update, device-map-builder -> route-planning, device-map-builder -> trailview, firmware-update -> device-link, host-runtime -> card-storage, map-assembly -> card-storage, map-assembly -> device-link, map-assembly -> device-map-builder, map-assembly -> host-runtime, map-assembly -> map-style, map-assembly -> route-planning, map-style -> device-map-builder, map-style -> map-assembly, route-planning -> device-map-builder, route-planning -> map-assembly, route-planning -> trailview, trailview -> route-planning - A cycle between content, device-map-baking, map-reading, source-preparation: content -> device-map-baking, content -> map-reading, device-map-baking -> content, device-map-baking -> map-reading, device-map-baking -> source-preparation, map-reading -> device-map-baking, source-preparation -> map-reading - route-planning -> planner-map-baking (test) is not in the doc of route-planning - search -> device-map-builder is not in the doc of search diff --git a/docs/design/device-map-builder.md b/docs/design/device-map-builder.md index 24b432fed0..c87b1e481c 100644 --- a/docs/design/device-map-builder.md +++ b/docs/design/device-map-builder.md @@ -1,7 +1,7 @@ --- system: device-map-builder kind: shell -purpose: "Runs the map builder, where a rider builds a device map and manages the device, in the browser." +purpose: "Holds the build configuration of the web app and the code that its pages share." owns: - builder/web/vite.config.ts - builder/web/svelte.config.js @@ -48,20 +48,14 @@ status: approved ## What it does -In the map builder, a rider selects an area, builds a map for the device, and downloads it or sends it to the device over the USB cable. The rider can also send routes, export recorded rides as GPX, format the card and install firmware updates. - -One Svelte frontend runs in two hosts: the public web site and a development server for maintainers. The entry point [`main.ts`](../../builder/web/src/main.ts) loads the shared WebAssembly core, then shows [`App.svelte`](../../builder/web/src/App.svelte) and its pages. - -The shell puts together map assembly, map style, route planning, TrailView, the device link and firmware update. It owns the pages, the host layer [`platform/`](../../builder/web/src/lib/platform/index.ts) and the build configuration [`vite.config.ts`](../../builder/web/vite.config.ts). Map assembly owns the WebAssembly core. +This document holds the code that the pages of the web app share: the host layer [`platform/`](../../builder/web/src/lib/platform/index.ts), the build configuration [`vite.config.ts`](../../builder/web/vite.config.ts), the shared parts in `lib/ui` and the loader of the shared WebAssembly core. The web app itself is the web planner. Map assembly owns the WebAssembly core. ## Rules that must hold | Rule | Check | | --- | --- | -| The web site's bundle contains no server client and no style editor. | `keeps build and style-editor code out of the web target` in [`bundle.test.ts`](../../builder/web/src/lib/platform/bundle.test.ts) | | The built app refers to its files with relative paths, so it works under any path of a server. | `references its own assets relatively` in [`bundle.test.ts`](../../builder/web/src/lib/platform/bundle.test.ts); the step `Mountable at any prefix` in [`deploy-site.yml`](../../.github/workflows/deploy-site.yml) | ## Decisions -- **The build selects the host.** An alias (`$host`) in [`vite.config.ts`](../../builder/web/vite.config.ts) points at the module of one host, so the code of the other host is not in the bundle. We rejected a test at run time, because then the bundle depends on the bundler to remove code that cannot run. -- **A browser with no WebUSB gets one sentence.** The device session has the state `unsupported` for such a browser, and the device step shows the sentence of the session in place of the Connect button ([`webusb.ts`](../../builder/web/src/lib/usb/webusb.ts)). The download of the map works in each browser. +- **A browser with no WebUSB gets one sentence.** The device session has the state `unsupported` for such a browser, and the Device page shows a sentence in place of the Connect button ([`webusb.ts`](../../builder/web/src/lib/usb/webusb.ts)). diff --git a/docs/design/map.json b/docs/design/map.json index 896a1942d7..0ec453d7f6 100644 --- a/docs/design/map.json +++ b/docs/design/map.json @@ -195,7 +195,7 @@ "map-reading" ], "violations": 9, - "lines": 36239, + "lines": 35082, "problems": [ { "rule": "cycle", @@ -207,7 +207,7 @@ }, { "rule": "cycle", - "message": "device-link -> device-map-builder closes a cycle: builder/web/src/lib/device/flows.test.ts -> builder/web/test-support/bytes.ts (test), builder/web/src/lib/device/flows.test.ts -> builder/web/test-support/flat-device/load.ts (test), builder/web/src/lib/device/rides.test.ts -> builder/web/test-support/flat-device/load.ts (test), and 10 more" + "message": "device-link -> device-map-builder closes a cycle: builder/web/src/lib/device/flows.test.ts -> builder/web/test-support/bytes.ts (test), builder/web/src/lib/device/flows.test.ts -> builder/web/test-support/flat-device/load.ts (test), builder/web/src/lib/device/route.ts -> builder/web/src/lib/format.ts, and 9 more" }, { "rule": "cycle", @@ -215,11 +215,11 @@ }, { "rule": "cycle", - "message": "device-link -> map-assembly closes a cycle: builder/web/src/lib/device/flows.test.ts -> builder/web/src/lib/convert/bridge.ts (test), builder/web/src/lib/device/rides.test.ts -> builder/web/src/lib/convert/bridge.ts (test), builder/web/src/lib/device/rides.ts -> builder/web/src/lib/convert/bridge.ts, and 1 more" + "message": "device-link -> map-assembly closes a cycle: builder/web/src/lib/device/flows.test.ts -> builder/web/src/lib/convert/bridge.ts (test), builder/web/src/lib/device/route.ts -> builder/web/src/lib/convert/bridge.ts" }, { "rule": "cycle", - "message": "device-map-builder -> device-link closes a cycle: builder/web/src/components/UpdatePrompt.svelte -> builder/web/src/lib/device/job.svelte.ts, builder/web/src/components/UpdatePrompt.svelte -> builder/web/src/lib/device/session.svelte.ts, builder/web/src/components/device/CardFormat.svelte -> builder/web/src/lib/usb/client.ts, and 46 more" + "message": "device-map-builder -> device-link closes a cycle: builder/web/test-support/device-smoke/smoke.test.ts -> builder/web/src/lib/usb/client.ts (test), builder/web/test-support/device-smoke/smoke.test.ts -> builder/web/src/lib/usb/flat-device.ts (test), builder/web/test-support/device-smoke/smoke.test.ts -> builder/web/src/lib/usb/protocol.ts (test), and 15 more" }, { "rule": "cycle", @@ -227,7 +227,7 @@ }, { "rule": "cycle", - "message": "map-assembly -> device-link closes a cycle: obc-builder-bridge -> obc-flat-device, obc-builder-bridge -> obc-link, obc-builder-bridge -> obc-vectors (test), and 12 more" + "message": "map-assembly -> device-link closes a cycle: obc-builder-bridge -> obc-flat-device, obc-builder-bridge -> obc-link, obc-builder-bridge -> obc-vectors (test), and 4 more" }, { "rule": "R1", @@ -290,7 +290,7 @@ "name": "device-map-builder", "kind": "shell", "area": "Shells", - "purpose": "Runs the map builder, where a rider builds a device map and manages the device, in the browser.", + "purpose": "Holds the build configuration of the web app and the code that its pages share.", "status": "approved", "depends_on": [ "device-link", @@ -304,28 +304,20 @@ "test_depends_on": [ "repository-tooling" ], - "violations": 10, - "lines": 12271, + "violations": 8, + "lines": 9011, "problems": [ { "rule": "cycle", - "message": "device-link -> device-map-builder closes a cycle: builder/web/src/lib/device/flows.test.ts -> builder/web/test-support/bytes.ts (test), builder/web/src/lib/device/flows.test.ts -> builder/web/test-support/flat-device/load.ts (test), builder/web/src/lib/device/rides.test.ts -> builder/web/test-support/flat-device/load.ts (test), and 10 more" - }, - { - "rule": "cycle", - "message": "device-map-builder -> device-link closes a cycle: builder/web/src/components/UpdatePrompt.svelte -> builder/web/src/lib/device/job.svelte.ts, builder/web/src/components/UpdatePrompt.svelte -> builder/web/src/lib/device/session.svelte.ts, builder/web/src/components/device/CardFormat.svelte -> builder/web/src/lib/usb/client.ts, and 46 more" + "message": "device-link -> device-map-builder closes a cycle: builder/web/src/lib/device/flows.test.ts -> builder/web/test-support/bytes.ts (test), builder/web/src/lib/device/flows.test.ts -> builder/web/test-support/flat-device/load.ts (test), builder/web/src/lib/device/route.ts -> builder/web/src/lib/format.ts, and 9 more" }, { "rule": "cycle", - "message": "device-map-builder -> firmware-update closes a cycle: builder/web/src/components/UpdatePrompt.svelte -> builder/web/src/lib/firmware/check.svelte.ts, builder/web/src/components/device/FirmwareCard.svelte -> builder/web/src/lib/firmware/check.svelte.ts, builder/web/src/components/device/FirmwareCard.svelte -> builder/web/src/lib/firmware/release.ts, and 1 more" + "message": "device-map-builder -> device-link closes a cycle: builder/web/test-support/device-smoke/smoke.test.ts -> builder/web/src/lib/usb/client.ts (test), builder/web/test-support/device-smoke/smoke.test.ts -> builder/web/src/lib/usb/flat-device.ts (test), builder/web/test-support/device-smoke/smoke.test.ts -> builder/web/src/lib/usb/protocol.ts (test), and 15 more" }, { "rule": "cycle", - "message": "device-map-builder -> map-assembly closes a cycle: builder/web/src/components/device/DeviceStep.svelte -> builder/web/src/lib/catalog/ledger.ts, builder/web/src/components/device/DeviceSurfaces.svelte -> builder/web/src/lib/catalog/ledger.ts, builder/web/src/components/device/MapSend.svelte -> builder/web/src/lib/catalog/ledger.ts, and 7 more" - }, - { - "rule": "cycle", - "message": "device-map-builder -> map-style closes a cycle: builder/web/src/lib/api/client.ts -> builder/web/src/lib/config/model.ts, builder/web/src/lib/platform/types.ts -> builder/web/src/lib/config/model.ts, builder/web/src/routes/Advanced.svelte -> builder/web/src/components/advanced/CategoryRail.svelte, and 10 more" + "message": "device-map-builder -> firmware-update closes a cycle: builder/web/test-support/device-sync/fake-device.ts -> builder/web/src/lib/firmware/check.svelte.ts" }, { "rule": "cycle", @@ -337,11 +329,11 @@ }, { "rule": "cycle", - "message": "map-assembly -> device-map-builder closes a cycle: builder/web/src/components/coverage/CoverageHome.svelte -> builder/web/src/components/device/DeviceStep.svelte, builder/web/src/components/coverage/CoverageHome.svelte.test.ts -> builder/web/src/routes/Home.svelte (test), builder/web/src/components/coverage/CoverageHome.svelte.test.ts -> builder/web/test-support/coverage/Selection.svelte (test), and 28 more" + "message": "map-assembly -> device-map-builder closes a cycle: builder/web/src/components/coverage/CoverageMap.svelte -> builder/web/src/lib/core/grid.ts, builder/web/src/components/coverage/CoverageMap.svelte -> builder/web/src/lib/format.ts, builder/web/src/components/coverage/SkinStep.svelte -> builder/web/src/lib/ui/Window.svelte, and 21 more" }, { "rule": "cycle", - "message": "map-style -> device-map-builder closes a cycle: builder/web/src/components/advanced/ColorControl.svelte -> builder/web/src/lib/palette.ts, builder/web/src/components/advanced/ProfilesTab.svelte -> builder/web/src/lib/ui/confirm.svelte.ts, builder/web/src/components/advanced/SchemaLab.svelte -> builder/web/src/lib/platform/types.ts, and 4 more" + "message": "map-style -> device-map-builder closes a cycle: builder/web/src/lib/skin/preview.test.ts -> builder/web/src/lib/core/bridge.ts (test), builder/web/src/lib/skin/preview.ts -> builder/web/src/lib/core/bridge.ts" }, { "rule": "cycle", @@ -440,7 +432,7 @@ }, { "rule": "cycle", - "message": "device-map-builder -> firmware-update closes a cycle: builder/web/src/components/UpdatePrompt.svelte -> builder/web/src/lib/firmware/check.svelte.ts, builder/web/src/components/device/FirmwareCard.svelte -> builder/web/src/lib/firmware/check.svelte.ts, builder/web/src/components/device/FirmwareCard.svelte -> builder/web/src/lib/firmware/release.ts, and 1 more" + "message": "device-map-builder -> firmware-update closes a cycle: builder/web/test-support/device-sync/fake-device.ts -> builder/web/src/lib/firmware/check.svelte.ts" }, { "rule": "cycle", @@ -520,7 +512,7 @@ "depends_on": [], "test_depends_on": [], "violations": 0, - "lines": 2276, + "lines": 2308, "problems": [] }, { @@ -542,16 +534,12 @@ "test_depends_on": [ "content" ], - "violations": 10, - "lines": 24646, + "violations": 9, + "lines": 21998, "problems": [ { "rule": "cycle", - "message": "device-link -> map-assembly closes a cycle: builder/web/src/lib/device/flows.test.ts -> builder/web/src/lib/convert/bridge.ts (test), builder/web/src/lib/device/rides.test.ts -> builder/web/src/lib/convert/bridge.ts (test), builder/web/src/lib/device/rides.ts -> builder/web/src/lib/convert/bridge.ts, and 1 more" - }, - { - "rule": "cycle", - "message": "device-map-builder -> map-assembly closes a cycle: builder/web/src/components/device/DeviceStep.svelte -> builder/web/src/lib/catalog/ledger.ts, builder/web/src/components/device/DeviceSurfaces.svelte -> builder/web/src/lib/catalog/ledger.ts, builder/web/src/components/device/MapSend.svelte -> builder/web/src/lib/catalog/ledger.ts, and 7 more" + "message": "device-link -> map-assembly closes a cycle: builder/web/src/lib/device/flows.test.ts -> builder/web/src/lib/convert/bridge.ts (test), builder/web/src/lib/device/route.ts -> builder/web/src/lib/convert/bridge.ts" }, { "rule": "cycle", @@ -559,11 +547,11 @@ }, { "rule": "cycle", - "message": "map-assembly -> device-link closes a cycle: obc-builder-bridge -> obc-flat-device, obc-builder-bridge -> obc-link, obc-builder-bridge -> obc-vectors (test), and 12 more" + "message": "map-assembly -> device-link closes a cycle: obc-builder-bridge -> obc-flat-device, obc-builder-bridge -> obc-link, obc-builder-bridge -> obc-vectors (test), and 4 more" }, { "rule": "cycle", - "message": "map-assembly -> device-map-builder closes a cycle: builder/web/src/components/coverage/CoverageHome.svelte -> builder/web/src/components/device/DeviceStep.svelte, builder/web/src/components/coverage/CoverageHome.svelte.test.ts -> builder/web/src/routes/Home.svelte (test), builder/web/src/components/coverage/CoverageHome.svelte.test.ts -> builder/web/test-support/coverage/Selection.svelte (test), and 28 more" + "message": "map-assembly -> device-map-builder closes a cycle: builder/web/src/components/coverage/CoverageMap.svelte -> builder/web/src/lib/core/grid.ts, builder/web/src/components/coverage/CoverageMap.svelte -> builder/web/src/lib/format.ts, builder/web/src/components/coverage/SkinStep.svelte -> builder/web/src/lib/ui/Window.svelte, and 21 more" }, { "rule": "cycle", @@ -629,20 +617,16 @@ "status": "draft", "depends_on": [], "test_depends_on": [], - "violations": 4, - "lines": 6923, + "violations": 3, + "lines": 1998, "problems": [ - { - "rule": "cycle", - "message": "device-map-builder -> map-style closes a cycle: builder/web/src/lib/api/client.ts -> builder/web/src/lib/config/model.ts, builder/web/src/lib/platform/types.ts -> builder/web/src/lib/config/model.ts, builder/web/src/routes/Advanced.svelte -> builder/web/src/components/advanced/CategoryRail.svelte, and 10 more" - }, { "rule": "cycle", "message": "map-assembly -> map-style closes a cycle: builder/web/src/components/coverage/SkinStep.svelte -> builder/web/src/components/skin/SkinEditor.svelte, builder/web/src/components/coverage/SkinStep.svelte -> builder/web/src/components/skin/SkinPreviewThumbnail.svelte, builder/web/src/components/coverage/SkinStep.svelte -> builder/web/src/lib/skin/custom.ts, and 4 more" }, { "rule": "cycle", - "message": "map-style -> device-map-builder closes a cycle: builder/web/src/components/advanced/ColorControl.svelte -> builder/web/src/lib/palette.ts, builder/web/src/components/advanced/ProfilesTab.svelte -> builder/web/src/lib/ui/confirm.svelte.ts, builder/web/src/components/advanced/SchemaLab.svelte -> builder/web/src/lib/platform/types.ts, and 4 more" + "message": "map-style -> device-map-builder closes a cycle: builder/web/src/lib/skin/preview.test.ts -> builder/web/src/lib/core/bridge.ts (test), builder/web/src/lib/skin/preview.ts -> builder/web/src/lib/core/bridge.ts" }, { "rule": "cycle", @@ -708,7 +692,7 @@ }, { "rule": "R1", - "message": "crate obc-data-steps (obc-data) holds 4 file(s) of planner-map-baking" + "message": "crate obc-data-steps (obc-data) holds 2 file(s) of planner-map-baking" }, { "rule": "R1", @@ -729,7 +713,7 @@ "problems": [ { "rule": "R1", - "message": "crate obc-data-steps (obc-data) holds 4 file(s) of planner-map-baking" + "message": "crate obc-data-steps (obc-data) holds 2 file(s) of planner-map-baking" }, { "rule": "R4", @@ -780,7 +764,7 @@ ], "test_depends_on": [], "violations": 0, - "lines": 18954, + "lines": 18943, "problems": [] }, { @@ -828,7 +812,7 @@ ], "test_depends_on": [], "violations": 7, - "lines": 27428, + "lines": 27585, "problems": [ { "rule": "cycle", @@ -945,7 +929,7 @@ "repository-tooling" ], "violations": 4, - "lines": 18734, + "lines": 18928, "problems": [ { "rule": "cycle", @@ -976,7 +960,7 @@ ], "test_depends_on": [], "violations": 5, - "lines": 101940, + "lines": 103131, "problems": [ { "rule": "cycle", @@ -1045,7 +1029,7 @@ ], "test_depends_on": [], "violations": 0, - "lines": 11044, + "lines": 12088, "problems": [] }, { @@ -1296,18 +1280,6 @@ "test": false, "undeclared": false }, - { - "from": "device-map-builder", - "to": "map-assembly", - "test": false, - "undeclared": false - }, - { - "from": "device-map-builder", - "to": "map-style", - "test": false, - "undeclared": false - }, { "from": "device-map-builder", "to": "repository-tooling", @@ -1326,12 +1298,6 @@ "test": false, "undeclared": false }, - { - "from": "device-map-builder", - "to": "website", - "test": false, - "undeclared": false - }, { "from": "device-runtime", "to": "data-engine", diff --git a/docs/design/web-planner.md b/docs/design/web-planner.md index e8abb26239..cd50167277 100644 --- a/docs/design/web-planner.md +++ b/docs/design/web-planner.md @@ -121,9 +121,9 @@ A sync never builds a map. Only `deviceSync.sendMap()` does, and only the button `sendMap` ([`sync.ts`](../../builder/web/src/lib/device-sync/sync.ts)) reads the library state `nextMap` and calls the build. The build of the app is `buildMap` ([`map.svelte.ts`](../../builder/web/src/lib/device-sync/map.svelte.ts)). It makes the selection of map assembly from `nextMap`, waits until the run is ready (the catalog indices, the cell lists of the regions and the memory check of the assembly worker), and then downloads the cells, assembles the map in this tab and puts it on the device as one run (`MapRun.sendToDevice`). The build makes exactly the map of `nextMap` or nothing: when a region, a box or a map style of it is not there any more, the build ends with one sentence, as it does for an area with no map data, a refusal of the memory check and a failed memory check. Stop and a pulled cable also end each wait before the run. While the build runs, the browser asks before it closes the tab. -After the put, `sendMap` remembers the map object with its area and its colours (`built` of the remembered device), and sets `nextMap` to `null`. The build sends the colours that the two map styles have at that moment and gives their versions, so `built` names what is on the device, also when a style changed after "Done". When the rider chose another map during the build, that map still waits. A send that does not end keeps `nextMap`, and the card keeps its old map, because the device replaces the old map only at the end of the put. The next send downloads the cells again, unless the map builder page is set to keep downloaded map data. After the last byte the device stores the map, and Stop is not available any more. A card with no room for both maps refuses the put. +After the put, `sendMap` remembers the map object with its area and its colours (`built` of the remembered device), and sets `nextMap` to `null`. The build sends the colours that the two map styles have at that moment and gives their versions, so `built` names what is on the device, also when a style changed after "Done". When the rider chose another map during the build, that map still waits. A send that does not end keeps `nextMap`, and the card keeps its old map, because the device replaces the old map only at the end of the put. The next send downloads the cells again. After the last byte the device stores the map, and Stop is not available any more. A card with no room for both maps refuses the put. -The run holds the Web Lock `obc-map-work` ([`workBarrier.ts`](../../builder/web/src/lib/cells/workBarrier.ts)) while it uses the working files of map assembly in the browser storage. The map builder page takes the same lock before it deletes or uses these files, so the page and the map send do not delete the files of each other. `deviceSync.map` gives the step of the send and its percent; `wait` means that another map build holds the lock. +The run holds the Web Lock `obc-map-work` ([`workBarrier.ts`](../../builder/web/src/lib/cells/workBarrier.ts)) while it uses the working files of map assembly in the browser storage. A run in another tab takes the same lock, so two runs do not delete the files of each other. `deviceSync.map` gives the step of the send and its percent; `wait` means that another map build holds the lock. ## Device page diff --git a/docs/index.html b/docs/index.html index d9398c110e..56c7659ecc 100644 --- a/docs/index.html +++ b/docs/index.html @@ -641,7 +641,7 @@ @@ -869,9 +869,9 @@

Completely cloud-free

diff --git a/docs/testing.md b/docs/testing.md index b405aff4ec..2886447e8b 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -103,25 +103,17 @@ and a missing expected file fails the upload. Download with | Artifact | Holds | | --- | --- | | `rust-test-ATTEMPT`, `rust-fixtures-ATTEMPT` | nextest JUnit XML for the fast and fixture tiers; the fast artifact also holds `doctests.log` and `formats-default.log` | -| `python-repository-tools-ATTEMPT`, `python-firmware-tools-ATTEMPT`, `python-builder-ATTEMPT` | unittest and pytest XML | +| `python-repository-tools-ATTEMPT`, `python-firmware-tools-ATTEMPT` | unittest and pytest XML | | `web-builder-ATTEMPT` | Vitest JUnit XML | -| `web-builder-browser-ATTEMPT`, `web-demo-browser-ATTEMPT` | the two Chromium journeys, with a screenshot and trace on failure | +| `web-builder-browser-ATTEMPT`, `web-demo-browser-ATTEMPT` | the Chromium journeys of the web app and of the landing page, with a screenshot and trace on failure | | `ios-tests-coverage-ATTEMPT`, `ios-screenshots-ATTEMPT`, `ios-application-ATTEMPT` | `.xcresult` bundles; restore the suffix and open in Xcode | The exit status and the CI log stay authoritative; an artifact does not prove a passing run. ## Browser journeys -`web.builder-browser` runs the map builder in Chromium against a digest-pinned loopback catalog, -assembles a map through the real WebAssembly bridge and requires the bytes to equal -`expected/map.obcm`. `web.demo-browser` drives the landing page's save, view, reset and reload +`web.planner-requests` runs the web app in Chromium. Its area and Device journeys build a map in +the tab from a digest-pinned loopback catalog, through the real WebAssembly bridge, and send it to +the pretend device. `web.demo-browser` drives the landing page's save, view, reset and reload controls. Each browser suite serves on a free loopback port, so separate worktrees run it at the same time; `OBC_BROWSER_PORT` and the other `OBC_*_BROWSER_PORT` variables set one. - -`live.builder-memory` is the same builder against the **published** catalogue, and it is the one -`live` suite with a browser in it. It assembles the largest published region and holds the wasm -linear memory the worker reports at the end of the run against the peak the estimate that admitted -the run projected. It is the measurement the projection cannot make: an assembler that buffers a -whole map passes every arithmetic test of the estimator. It downloads about 890 MB, needs about -3 GB of free disk and takes minutes, so run it by hand before a release and after a change to the -assembler or the estimator. diff --git a/pyproject.toml b/pyproject.toml index e043d28e7d..60af9fb212 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,8 +26,6 @@ trailview-sky = [{ include-group = "planner-maps" }, "numpy==2.5.3", "openexr==3 planner-search = ["orjson==3.12.0", "pyyaml==6.0.2", "shapely==2.1.2", "zstandard==0.25.0"] dev = ["unittest-xml-reporting==4.0.0", "PyYAML==6.0.2"] -builder = ["fastapi>=0.110.0", "uvicorn[standard]>=0.27.0"] -builder-test = [{ include-group = "builder" }, "pytest>=8.0.0", "httpx>=0.27.0"] search-runtime = [ "orjson==3.12.0", "shapely==2.1.2", diff --git a/tools/check_data_sources.py b/tools/check_data_sources.py index d0c1dedcc7..d8944a307f 100644 --- a/tools/check_data_sources.py +++ b/tools/check_data_sources.py @@ -3,7 +3,7 @@ The registry is the one list of external data, and its licence and attribution are only as complete as that list. URL literals in justfile, host/, planner/, sim/, tools/, fixtures/, -builder/server/, builder/usb/ and data/archive/ name a host. That host is the host of a source's `fetch.url`, one of its +builder/usb/ and data/archive/ name a host. That host is the host of a source's `fetch.url`, one of its `hosts`, or one of the non-bake hosts in `NOT_SOURCES`. The check is per host, not per URL: a new download from a host that a source already declares (api.github.com, for one) passes. Tests and reserved example domains are not checked. A host built at run time (`https://{site}/…`) @@ -15,8 +15,8 @@ from __future__ import annotations -GOVERNS = ['justfile', 'host/**', 'planner/**', 'sim/**', 'tools/**', 'fixtures/**', 'builder/server/**', 'builder/usb/**', 'data/archive/**', 'data/sources.toml'] -RULE = 'Every host that code in justfile, host/, planner/, sim/, tools/, fixtures/, builder/server/ and builder/usb/, or a dataset of data/archive/, fetches from is a source in data/sources.toml or a listed non-bake host, and each source names what reads it, what for and where its kept copy is.' +GOVERNS = ['justfile', 'host/**', 'planner/**', 'sim/**', 'tools/**', 'fixtures/**', 'builder/usb/**', 'data/archive/**', 'data/sources.toml'] +RULE = 'Every host that code in justfile, host/, planner/, sim/, tools/, fixtures/ and builder/usb/, or a dataset of data/archive/, fetches from is a source in data/sources.toml or a listed non-bake host, and each source names what reads it, what for and where its kept copy is.' import re import subprocess @@ -25,7 +25,7 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[1] -SCOPE = ("justfile", "host/", "planner/", "sim/", "tools/", "fixtures/", "builder/server/", "builder/usb/", "data/archive/") +SCOPE = ("justfile", "host/", "planner/", "sim/", "tools/", "fixtures/", "builder/usb/", "data/archive/") CODE = (".rs", ".py", ".sh", ".mjs", ".js", ".ts", ".toml", "justfile") TEST = re.compile(r"(^|/)(tests?/|test_[^/]*\.py$|[^/]*_tests?\.(rs|py)$|tests\.rs$)") URL = re.compile(r"https?://((?:\{[^{}\s]*\}|[A-Za-z0-9.-])+)") diff --git a/tools/fixture_catalog.py b/tools/fixture_catalog.py index 28900a2152..462470daba 100644 --- a/tools/fixture_catalog.py +++ b/tools/fixture_catalog.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""A digest-pinned catalog fixture on loopback, for the builder browser journey. +"""A digest-pinned catalog fixture on loopback, for the browser journeys of the web app. `web_assemble()` is the journey's catalog, where every artifact is real, so a region download from it assembles the checked-in cells into the checked-in map. @@ -7,10 +7,9 @@ Every `bytes`, `sha256` and `url` is computed from the bytes this module serves, never copied from a document. -Run it as a server for a browser test: +Run it as a server for a browser test; it prints its origin first: - python3 tools/fixture_catalog.py --catalog web-assemble --port 4180 \\ - --static builder/web/dist/web --log .artifacts/web-builder/catalog.jsonl + python3 tools/fixture_catalog.py --catalog web-assemble """ from __future__ import annotations @@ -60,7 +59,7 @@ def _document(objects: dict[str, bytes], path: str, document: object) -> dict: return pin(objects, path, json.dumps(document).encode()) -# The builder browser journey's catalog. +# The catalog of the browser journeys. # # The bridge fixture's own cut numbers its feature types in config order. A hosted catalog names the # feature types and the schema assigns the ids, so the assignment is restated here in the catalog's @@ -313,7 +312,7 @@ def main() -> None: if args.static and not (args.static / "index.html").is_file(): raise SystemExit( f"{args.static}/index.html is missing. Build it first:\n" - " cd builder/web && npm run build:web" + " cd builder/web && npm run build" ) server = CatalogServer(CATALOGS[args.catalog](), args.port, args.static, args.log) print(f"{server.origin} serving {len(server.objects)} pinned objects", flush=True) diff --git a/tools/justfile b/tools/justfile index 1df2269378..3fc1b86cf4 100644 --- a/tools/justfile +++ b/tools/justfile @@ -441,37 +441,6 @@ bake *args: _say "bake tree: $tree — verify with: obc bake verify" ;; esac -# Run the web map builder at http://localhost:8000 (bootstraps the venv, obc-pack, -# and the frontend on first run). Extra args pass through (e.g. --no-browser). -[doc("Run the web map builder on :8000 (bootstraps venv/frontend on first run)")] -[group('run')] -web *args: - #!/usr/bin/env bash - set -euo pipefail - source "{{lib}}"; obc_init; ensure_geos - cd "$OBC_ROOT" - export OBC_PACK_BIN="${CARGO_TARGET_DIR:-$OBC_ROOT/target}/release/obc-pack" - _run uv sync --locked --inexact --group builder - if [[ "${1:-}" == preview-source ]]; then - shift - (( $# == 0 )) || { _err "usage: obc web preview-source"; exit 1; } - _say "preparing the small reference-complete source for the Teningen schema lab…" - _run uv run --locked --group builder python -m builder.server.schema_preview --download-source - exit 0 - fi - # This is the maintainer schema host: a present binary may still predate the - # config/parser source the editor is showing. Cargo's no-op rebuild is cheap - # and makes the served schema and every preview use this checkout exactly. - _say "refreshing obc-pack…"; ( cd "$OBC_ROOT" && _run cargo build --release -p obc-bake --bin obc-pack ) - [[ -d builder/web/node_modules ]] || { _say "installing frontend dependencies…"; ( cd builder/web && _run npm ci ); } - # Generated bindings are gitignored; existence cannot prove that any bridge - # matches its Rust source. Warm wasm-pack builds are incremental. - _say "refreshing the wasm bridges…"; ( cd builder/web && _run npm run build:wasm ) - # Always rebuild this small local bundle: tools/obc.local is runtime state, - # but a source checkout must never keep serving yesterday's platform adapter. - _say "building the maintainer frontend…"; ( cd builder/web && _run npm run build ) - _run uv run --locked --group builder python -m builder.server "$@" - [doc("Pack the iOS host as target/OBCHost.xcframework, in release. Args: [--sim-only|--mac-only]")] [group('ios')] ios-host *args: @@ -535,14 +504,12 @@ cairn *args: cd "$OBC_ROOT" _run python3 "$OBC_TOOLS/cairn/cairn.py" "$@" -# Serve the static hosted tier — the no-backend site (phase C of #894), as deployed. -# Builds and serves it on :4173. Args: [PORT]. It reads the device catalogue of the -# active planner release, as deployed; OBC_CATALOG_URL=… points it at another one. -# Two deliberate differences from the deploy: this mounts the builder at the server -# root rather than at /builder/ (nothing else is being served beside it), and it leaves -# VITE_SITE_BASE unset, so the Docs/Home links point at the published site instead of +# Builds the web app as the deploy builds it and serves it on :4173 at /planner.html. Args: [PORT]. +# It reads the device catalogue of the active planner release, as deployed; +# OBC_CATALOG_URL=… points it at another one. One deliberate difference from the deploy: it +# leaves VITE_SITE_BASE unset, so the Docs/Home links point at the published site instead of # at siblings that aren't here. -[doc("Build & serve the static hosted tier (no backend) on :4173. Args: [PORT]")] +[doc("Build & serve the web app (no backend) on :4173. Args: [PORT]")] [group('run')] site *args: #!/usr/bin/env bash @@ -557,13 +524,13 @@ site *args: # vite/esbuild strips types without checking them; svelte-check is what # fails loudly when the app drifts from a bridge's generated bindings. _say "type-checking the frontend…"; ( cd "$fe" && _run npm run check ) - _say "building the static web tier…" - ( cd "$fe" && export VITE_CATALOG_URL="${OBC_CATALOG_URL:-}" && _run npm run build:web ) + _say "building the web app…" + ( cd "$fe" && export VITE_CATALOG_URL="${OBC_CATALOG_URL:-}" && _run npm run build ) cd "$OBC_ROOT" - _say "serving http://localhost:$port (Ctrl-C to stop)" + _say "serving http://localhost:$port/planner.html (Ctrl-C to stop)" # `--directory` rather than `cd` + a relative path: the relative form resolved against the # *serving* directory and vanished the moment we left the repo root. - _run python3 -m http.server "$port" --directory "$fe/dist/web" + _run python3 -m http.server "$port" --directory "$fe/dist/planner" # A scope is required: `obc test -p obc-pack` runs nextest and then the same scope's doctests; # `--lib` runs the library target alone and no doctests. @@ -915,7 +882,7 @@ doctor *args: ck probe "probe-rs (flashing)" 'command -v probe-rs' 'obc doctor --install' ck node "node + npm (web builder)" 'command -v node && command -v npm' 'install Node 22+ (system package — needs sudo)' ck uv "uv (Python groups)" 'command -v uv' 'install uv, then run obc doctor --install' - ck venv "python venv (web builder)" '[[ -x "$OBC_ROOT/.venv/bin/python" ]]' 'obc doctor --install (or run obc web)' + ck venv "python venv" '[[ -x "$OBC_ROOT/.venv/bin/python" ]]' 'obc doctor --install' if python3 "$OBC_TOOLS/fixtures.py" exists grimsel; then _ok "default sim scenario → grimsel" else _err "fixture catalog has no grimsel scenario"; MISSING+=(fixtures); fi @@ -932,7 +899,7 @@ doctor *args: probe) _run cargo install probe-rs-tools --locked ;; riscv) _run bash "$OBC_TOOLS/install-riscv.sh" ;; geos) _run bash "$OBC_TOOLS/install-geos.sh" ;; - venv) _run uv sync --locked --inexact --project "$OBC_ROOT" --group builder ;; + venv) _run uv sync --locked --inexact --project "$OBC_ROOT" ;; uv) _err "install uv via your system package manager" ;; cargo) _err "install Rust yourself: https://rustup.rs" ;; node) _err "install Node 22+ via your system package manager (needs sudo)" ;; diff --git a/tools/obc.local.example b/tools/obc.local.example index e1e768a55d..bd9c114b37 100644 --- a/tools/obc.local.example +++ b/tools/obc.local.example @@ -31,12 +31,6 @@ OBC_BAKE_TREE="$HOME/obc-bake" OBC_MAPS_BASE_URL="https://maps.openbikecomputer.com/cell-catalog" OBC_CATALOG_URL="$OBC_MAPS_BASE_URL/catalog.json" OBC_R2_PREFIX="cell-catalog" -# Local maintainer schema-lab source. Leave unset: `obc web preview-source` -# downloads/reuses Freiburg-regbez and prepares a small, reference-complete -# Teningen PBF under ~/.cache/obcm/schema-preview. An override means an -# already-prepared absolute .osm.pbf and is never downloaded to or overwritten; -# the browser can never supply a source path. -#OBC_SCHEMA_PREVIEW_PBF="$HOME/maps/teningen-reference-complete.osm.pbf" #OBC_R2_ACCOUNT_ID="..." #OBC_R2_BUCKET="..." # OBC_R2_ACCESS_KEY_ID and OBC_R2_SECRET_ACCESS_KEY go in credentials.env (see above). diff --git a/tools/test_plan.py b/tools/test_plan.py index acec3bdb2b..6ef7add147 100644 --- a/tools/test_plan.py +++ b/tools/test_plan.py @@ -54,7 +54,6 @@ class Job: "clippy": Job(needs=("selection",), roots=(ROOT_WORKSPACE,)), "test": Job(needs=("selection",), roots=(ROOT_WORKSPACE,), script="tools/ci/test.sh"), "ui-snapshots": Job(needs=("selection",), packages=("obc-sim",)), - "builder-python": Job(needs=("selection",), packages=("obc-bake", "obc-pack")), "embedded": Job(needs=("selection",), roots=("firmware/obc-fw-nrf54l", "firmware/obc-sensor-sim")), "boot": Job(needs=("selection",), roots=("firmware/obc-boot",)), "device": Job(needs=("selection",), packages=("obc-app", "obc-link")), @@ -1012,7 +1011,6 @@ def validate_workflow(root: Path) -> list[str]: ".cargo/config.toml", "specs/vectors/obcm-v2.json", "tools/test_plan.py", - "builder/server/nested/handler.py", "fixtures/catalog.toml", ".github/workflows/bake.yml", "tools/testing/suites.toml", diff --git a/tools/testing/suites.toml b/tools/testing/suites.toml index 0707db814a..9daf188ea8 100644 --- a/tools/testing/suites.toml +++ b/tools/testing/suites.toml @@ -223,8 +223,7 @@ triggers = [ # bins.test.ts checks the stamp profiles of the road classes and the cross-section tables. "data/trailview/roads.json", "data/trailview/finishes.json", - "builder/web/vite.config.ts", - "host/obc-map-core/schema/config.schema.json", + "builder/web/vite.config.ts", "builder/web/tsconfig.json", "specs/vectors/**", "sim/flat-device/**", "planner/search/query/contract.json", @@ -242,15 +241,6 @@ jobs = ["verification"] platforms = ["linux", "macos"] triggers = ["tools/verification/**"] -[[suite]] -id = "web.builder-browser" -route = "ordinary" -command = "npm test --prefix builder/web/tests/browser" -jobs = ["web-browser"] -fixtures = ["checked-in-web-fixtures"] -platforms = ["linux", "macos"] -triggers = ["docs/assets/theme.css", "docs/assets/fonts/**", "builder/web/**", "builder/wasm/**", "tools/fixture_catalog.py", "tools/loopback_port.mjs"] - [[suite]] id = "web.planner-requests" route = "ordinary" @@ -259,20 +249,11 @@ jobs = ["web-browser"] platforms = ["linux", "macos"] triggers = [ "planner/search/place-kinds.json", - "builder/web/src/components/planner/**", - "builder/web/src/lib/planner/**", - "builder/web/src/planner.ts", - "builder/web/src/Shell.svelte", - "builder/web/src/pages/**", - "builder/web/src/lib/library/**", - "builder/web/src/lib/core/gpx.ts", - "builder/web/src/lib/core/fit.ts", - "builder/wasm/src/gpx.rs", - "builder/web/src/components/TopBar.svelte", - "builder/web/src/styles/shell.css", - "builder/web/src/lib/ui/**", - "builder/web/src/lib/routes.ts", - "builder/web/src/lib/router.svelte.ts", + "docs/assets/theme.css", "docs/assets/fonts/**", + # The area and Device journeys build a map in the tab from the fixture catalog, with the wasm core. + "builder/web/src/**", + "builder/wasm/**", + "tools/fixture_catalog.py", "builder/web/planner.html", "builder/web/tests/browser/planner/**", "builder/web/tests/browser/playwright.planner.config.js", @@ -376,7 +357,6 @@ triggers = [ "specs/vectors/trailview-features.*", # The footers that test_data_registry.py compares with the registry. "docs/templates/*.html", - "builder/web/src/App.svelte", "tools/testing/*.toml", "docs/testing.md", ".github/workflows/**", @@ -427,21 +407,6 @@ triggers = ["tools/trailview/**", "data/trailview/**", "fixtures/sources/trailvi "tools/step_pool.py", "tools/step_request.py", "tools/data_registry.py", "tools/planner_runtime.py", "data/sources.toml", "builder/web/src/lib/trailview/models/trees/**", "builder/web/src/lib/trailview/models/plants/**", "pyproject.toml", "uv.lock"] -[[suite]] -id = "python.builder" -route = "ordinary" -command = "rm -f .artifacts/python/builder.xml && PYTHONPATH=. uv run --locked --group builder-test python -m pytest builder/tests/ -v --junitxml=.artifacts/python/builder.xml" -jobs = ["builder-python"] -fixtures = ["builder-corpus"] -triggers = [ - "builder/tests/**", - "builder/presets/**", - "builder/server/*.py", - "builder/server/**/*.py", - "host/obc-map-core/schema/config.schema.json", - "pyproject.toml", "uv.lock", -] - [[suite]] id = "ios.replay-camera" scoped = true @@ -534,7 +499,7 @@ triggers = ["Cargo.toml", "Cargo.lock", "rust-toolchain.toml"] id = "ci.rust-builds" route = "ordinary" command = "obc check device board wasm" -jobs = ["boot", "builder-python", "device", "embedded", "ui-snapshots", "wasm"] +jobs = ["boot", "device", "embedded", "ui-snapshots", "wasm"] foundation = true triggers = ["Cargo.toml", "Cargo.lock", "rust-toolchain.toml", "tools/install-riscv.sh"] @@ -916,36 +881,6 @@ command = "cargo test -p obc-dem --locked --test decode --test real_tile -- --ig package = "obc-dem" targets = ["decode", "real_tile"] -# The empirical half of the memory projection. `estimateMemory` prices a selection before the -# download and the preflight refuses on it, but arithmetic cannot fail when the assembler buffers -# a whole map anyway. This suite assembles the published catalogue's largest region in Chromium -# and holds the whole linear memory the worker reports against that estimate's `peakBytes`, the -# bottom line `fits` is decided on. Both sides are whole-memory figures, so the gate needs no -# margin: a measured country-scale run lands at 0.877 of the projection, and what the gate exists -# to catch is a buffered map or a buffered selection, hundreds of megabytes either way. The -# published objects are the only input big enough for it to be able to fail, so it contacts the -# live CDN. It reads a figure and does not re-fit one: an earlier measurement of the same selection -# on a differently staged page read less, and nothing here isolates the engine term, so that -# difference stays unattributed. -# -# Run it by hand before a release, and after a change to the assembler or to the estimator. It -# moves about 890 MB over the network, needs about 3 GB of free disk and takes minutes. Needs -# `npm install` in its own directory and `npx playwright install chromium`. -[[suite]] -id = "live.builder-memory" -route = "live" -command = "npm run test:live --prefix builder/web/tests/browser" -platforms = ["linux", "macos"] -triggers = [ - "builder/web/tests/browser/live-memory.test.ts", - "builder/web/tests/browser/playwright.live.config.js", - "builder/web/tests/browser/package.json", - "builder/web/src/lib/assemble/**", - "builder/web/src/lib/cells/store.ts", - "builder/web/src/components/coverage/DownloadStep.svelte", - "builder/wasm/**", -] - # `test-weekly.yml` invokes this each Monday, and a maintainer can invoke it by hand. The # schedule belongs to that workflow; this row owns the XCUITest classes and the command. [[suite]] diff --git a/tools/tests/test_data_registry.py b/tools/tests/test_data_registry.py index 6a69c3c4f4..9af6bc1083 100644 --- a/tools/tests/test_data_registry.py +++ b/tools/tests/test_data_registry.py @@ -19,7 +19,7 @@ def test_a_credit_with_a_date_needs_the_date(self): def test_the_static_page_footers_show_the_registry_credits(self): # These pages are HTML that no step generates, so they keep the text and this compares it. footers = {"docs/index.html": ["osm-planet", "copernicus-glo-30"], "docs/templates/page.html": ["osm-planet"], - "docs/templates/blog_post.html": ["osm-planet"], "builder/web/src/App.svelte": ["osm-planet"]} + "docs/templates/blog_post.html": ["osm-planet"]} for path, sources in footers.items(): text = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", "", (data_registry.ROOT / path).read_text())) for source in sources: diff --git a/tools/tests/test_selection_plan.py b/tools/tests/test_selection_plan.py index 1898fbfc4e..9a88c42743 100644 --- a/tools/tests/test_selection_plan.py +++ b/tools/tests/test_selection_plan.py @@ -445,14 +445,6 @@ def test_the_documents_and_the_workflow_validate(self) -> None: self.assertEqual(plan.validate(self.root, self.graph, self.document, self.units), []) self.assertEqual(plan.validate_workflow(self.root), []) - def test_the_shared_config_schema_selects_its_rust_python_and_web_consumers(self) -> None: - selected = plan.select(self.units, self.graph, ["host/obc-map-core/schema/config.schema.json"]) - self.assertEqual(selected.errors, []) - self.assertLessEqual( - {"rust.obc-map-core", "python.builder", "web.builder-vitest"}, - {unit.id for unit in selected.selected}, - ) - def test_every_package_reaches_the_jobs_that_compile_it(self) -> None: expected = { "obc-crc": ["clippy", "fmt", "test"], @@ -460,8 +452,8 @@ def test_every_package_reaches_the_jobs_that_compile_it(self) -> None: "obc-boot": ["boot", "fmt"], "obc-builder-bridge": ["clippy", "fmt", "test", "wasm-bridges"], "obc-web-demo": ["clippy", "fmt", "test", "wasm"], - "obc-pack": ["builder-python", "clippy", "fmt", "test"], - "obc-bake": ["builder-python", "clippy", "fmt", "test"], + "obc-pack": ["clippy", "fmt", "test"], + "obc-bake": ["clippy", "fmt", "test"], "obc-sim": ["clippy", "fmt", "test", "ui-snapshots"], "obc-app": ["clippy", "device", "fmt", "test"], } @@ -483,7 +475,7 @@ def test_selected_job_set_per_change_class(self) -> None: ( "foundational Rust crate", ["firmware/obc-crc/src/lib.rs"], - ["boot", "builder-python", "cairn", "clippy", "device", "embedded", "fmt", "ios-app", "ios-release", "ios-unit", "test", "ui-snapshots", "wasm", "wasm-bridges"], + ["boot", "cairn", "clippy", "device", "embedded", "fmt", "ios-app", "ios-release", "ios-unit", "test", "ui-snapshots", "wasm", "wasm-bridges"], ), ( "shared vectors", @@ -499,12 +491,12 @@ def test_selected_job_set_per_change_class(self) -> None: ( "workflow", [".github/workflows/ci.yml"], - ["boot", "builder-python", "cairn", "clippy", "deny", "device", "docs", "embedded", "fmt", "ios-app", "ios-release", "ios-unit", "planner-search", "test", "ui-snapshots", "verification", "wasm", "wasm-bridges", "web", "web-browser"], + ["boot", "cairn", "clippy", "deny", "device", "docs", "embedded", "fmt", "ios-app", "ios-release", "ios-unit", "planner-search", "test", "ui-snapshots", "verification", "wasm", "wasm-bridges", "web", "web-browser"], ), ( "nextest configuration", [".config/nextest.toml"], - ["boot", "builder-python", "cairn", "clippy", "deny", "device", "docs", "embedded", "fmt", "planner-search", "test", "ui-snapshots", "verification", "wasm", "wasm-bridges", "web", "web-browser"], + ["boot", "cairn", "clippy", "deny", "device", "docs", "embedded", "fmt", "planner-search", "test", "ui-snapshots", "verification", "wasm", "wasm-bridges", "web", "web-browser"], ), ("web demo crate", ["sim/web-demo/src/lib.rs"], ["cairn", "clippy", "fmt", "test", "wasm"]), ("web demo Trunk target", ["docs/index.html"], ["docs", "wasm", "wasm-bridges"]), diff --git a/uv.lock b/uv.lock index 733dd7e670..6860cae298 100644 --- a/uv.lock +++ b/uv.lock @@ -42,22 +42,13 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/3e/30/e900b21425a860e195f32e37657aa1f7c7f2b1bfb26f03ca209b90933c06/annotated_doc-0.0.5-py3-none-any.whl", hash = "sha256:117bac03a25ede5df5440e855b32d556049ca169ead221505badf432fed4b101", size = 5302, upload-time = "2026-07-28T13:50:57.239Z" }, ] -[[package]] -name = "annotated-types" -version = "0.8.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/5f/56/a8120250d128bed162cd73c76d45f6ef9991f3e068f62a8ee060afa3104a/annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7", size = 15893, upload-time = "2026-07-23T20:16:13.995Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0", size = 13427, upload-time = "2026-07-23T20:16:12.938Z" }, -] - [[package]] name = "anyio" version = "4.15.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "idna" }, - { name = "typing-extensions", marker = "python_full_version < '3.15' or (extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-runtime') or (extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-test') or (extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-training') or (extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-runtime') or (extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-test') or (extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-training')" }, + { name = "typing-extensions", marker = "python_full_version < '3.15'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/a9/d2/f4d173e22df740bc37b1db102b386ba719b66e95b0f0d751f556b387e6d2/anyio-4.15.1.tar.gz", hash = "sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94", size = 276966, upload-time = "2026-09-05T10:42:39.44Z" } wheels = [ @@ -287,23 +278,6 @@ nvtx = [ { name = "nvidia-nvtx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] -[[package]] -name = "fastapi" -version = "0.142.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "annotated-doc" }, - { name = "opentelemetry-api" }, - { name = "pydantic" }, - { name = "starlette" }, - { name = "typing-extensions" }, - { name = "typing-inspection" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/56/4f/f7c30a73127e0a8bbffe788369b8359e530b01ae06e2757936fa35bc5e6d/fastapi-0.142.2.tar.gz", hash = "sha256:06366626f2e70576367714d9ab2fe8472e6c8456dba69b399f9f797ab5e92570", size = 466721, upload-time = "2026-09-30T09:51:11.277Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a0/b6/78aaf9141fb46742928c113f3cf6ef2259d538cb02b604b7656c1dc9883c/fastapi-0.142.2-py3-none-any.whl", hash = "sha256:bd5f4d81f1e93a88bcd77caf4dfe3c2dbffc3805407a0007e9a114c18b3a670b", size = 144409, upload-time = "2026-09-30T09:51:09.8Z" }, -] - [[package]] name = "filelock" version = "4.0.4" @@ -403,28 +377,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, ] -[[package]] -name = "httptools" -version = "0.8.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/43/e5/d471fcb0e14523fe1c3f4ba58ca52480e7bd70ad7109a3846bc75892f7fb/httptools-0.8.0.tar.gz", hash = "sha256:6b2a32f18d97e16e90827d7a819ffa8dbd8cc245fc4e1fa9d1095b54ef4bd999", size = 271342, upload-time = "2026-05-25T22:17:48.841Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1a/12/fa3fbf5f9517b273edea2dc982aa82a8c634091e67c590792b729017bc6f/httptools-0.8.0-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:de242a49b5d18e0a8776e654e9f6bf6d89f3875a5c35b425a0e7ce940feb3fd6", size = 206183, upload-time = "2026-05-25T22:17:24.004Z" }, - { url = "https://files.pythonhosted.org/packages/30/fc/5e7c4cb443370f2090a3aba0453a07384d29ff66b7435bb90e77e1037599/httptools-0.8.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:159e9ab5f701ccd42e555a12f1ad8ff69702910fc1c996cf2bb66e5fcb7a231b", size = 112079, upload-time = "2026-05-25T22:17:25.216Z" }, - { url = "https://files.pythonhosted.org/packages/ba/53/771bd891eb0f236f32145d6a1775777ec85745f3cc983a1f23d1a3b8ddfe/httptools-0.8.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:c4a9f1707e4823d54dfec6c33fa3697d302aed536ed352a7ebb5a061ddb869d0", size = 481596, upload-time = "2026-05-25T22:17:26.186Z" }, - { url = "https://files.pythonhosted.org/packages/62/42/94e15bc68ce3d423243c45d7f1b0c7561f13844f97dc52ae23182fb65628/httptools-0.8.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d76ad7b951387e3632c8716a9bb03ac5b45c5f16119aa409db0459520887944e", size = 480865, upload-time = "2026-05-25T22:17:27.542Z" }, - { url = "https://files.pythonhosted.org/packages/1c/7c/fe2980fc03723272e30f135b62360b075f513dfe7cc73aef36c7f04012bd/httptools-0.8.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a3b7387147361c3fd47a0bde763c5c91b5b4cd4dc9989b8ece84ff436c99843b", size = 463189, upload-time = "2026-05-25T22:17:28.546Z" }, - { url = "https://files.pythonhosted.org/packages/15/1b/47fc5fff68acd1bfa20b4734059c9a06cadb88119dcd5258b5b0d21d91c8/httptools-0.8.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f256d6ce930c52ca1cb2a960b7da03548c454e7d28b06059ad41bfe789036ce0", size = 466610, upload-time = "2026-05-25T22:17:29.816Z" }, - { url = "https://files.pythonhosted.org/packages/60/bd/07b13c93ffd9bec9546e0d43f8e19378dd696dbd278511406bc07371ef1f/httptools-0.8.0-cp314-cp314-win_amd64.whl", hash = "sha256:19d1ee275bb59ba2643ba9a3a1e51cc0c788caf2b8df506368e03f56fdd08527", size = 92705, upload-time = "2026-05-25T22:17:31.133Z" }, - { url = "https://files.pythonhosted.org/packages/fd/c4/121648f68ce066d7bd762d6b6d97e620847642d38d54f3d90ff11d947629/httptools-0.8.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:de1ed58a974e75d56560acc7e7fed01a454994429456f65209789992e41f2568", size = 215023, upload-time = "2026-05-25T22:17:32.401Z" }, - { url = "https://files.pythonhosted.org/packages/b9/b0/312a062ae741ae3e8baa8c8bf20be81b2e67337b259ab4349bebc7b6142e/httptools-0.8.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:e93c227b595c6926c1acee96891dd9da4be338cfbe82e5cd3bb9d8dd7dc4ac0b", size = 117405, upload-time = "2026-05-25T22:17:33.742Z" }, - { url = "https://files.pythonhosted.org/packages/fc/37/fccd705f795386bb05bf413012fecff2a33e5aa8c2f069096de3e9fd8702/httptools-0.8.0-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2a021c3a8e65cc125390d72f59b968afca3bdcaff25bd67965e0a055a14946ca", size = 558497, upload-time = "2026-05-25T22:17:34.732Z" }, - { url = "https://files.pythonhosted.org/packages/bd/39/f172e8003576de35f5ba77ff417cf0e34429d35dc014deef15afa337a72c/httptools-0.8.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:48774d39cbb70e2b1f71f88852a3087ae1d3a1eb80482bb48c13067ab080c14f", size = 571585, upload-time = "2026-05-25T22:17:35.813Z" }, - { url = "https://files.pythonhosted.org/packages/3e/b9/f5564760af99f3dbbf3f9104dc00e5da27e96cf433c6bdcf77617f70bf3f/httptools-0.8.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:88eead8ec8680a9f146c655bc88445a325bd7921cfd8194c7337e9467282427d", size = 543297, upload-time = "2026-05-25T22:17:37.08Z" }, - { url = "https://files.pythonhosted.org/packages/99/67/8d9f2c313618e161b82f3873188e7196126da1d6e29688df40eb3997c77a/httptools-0.8.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:2c032fa028f46871ec7e1fc59fc15e8023eab3e6bbe6ece786a1611719a5d081", size = 539535, upload-time = "2026-05-25T22:17:38.032Z" }, - { url = "https://files.pythonhosted.org/packages/48/63/b906c01e53f50d432c0defe43ce52764a111dc1bdd028bafbeb54dcfd008/httptools-0.8.0-cp314-cp314t-win_amd64.whl", hash = "sha256:384c17174464c8e873398b7af24f0b1f44d992c820328413951a625323155d77", size = 108209, upload-time = "2026-05-25T22:17:39.473Z" }, -] - [[package]] name = "httpx" version = "0.28.1" @@ -1037,16 +989,6 @@ version = "0" source = { virtual = "." } [package.dev-dependencies] -builder = [ - { name = "fastapi" }, - { name = "uvicorn", extra = ["standard"] }, -] -builder-test = [ - { name = "fastapi" }, - { name = "httpx" }, - { name = "pytest" }, - { name = "uvicorn", extra = ["standard"] }, -] dev = [ { name = "pyyaml", version = "6.0.2", source = { registry = "https://pypi.org/simple" } }, { name = "unittest-xml-reporting" }, @@ -1174,16 +1116,6 @@ trailview-sky = [ [package.metadata] [package.metadata.requires-dev] -builder = [ - { name = "fastapi", specifier = ">=0.110.0" }, - { name = "uvicorn", extras = ["standard"], specifier = ">=0.27.0" }, -] -builder-test = [ - { name = "fastapi", specifier = ">=0.110.0" }, - { name = "httpx", specifier = ">=0.27.0" }, - { name = "pytest", specifier = ">=8.0.0" }, - { name = "uvicorn", extras = ["standard"], specifier = ">=0.27.0" }, -] dev = [ { name = "pyyaml", specifier = "==6.0.2" }, { name = "unittest-xml-reporting", specifier = "==4.0.0" }, @@ -1328,18 +1260,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/06/44/8208e921bb52ea6253b5093364f910cd8847e7e144e1b17492c14c2be32d/openexr-3.5.2-cp314-cp314-win_arm64.whl", hash = "sha256:02ed234498a2b910975ac9e7c3a2d7a167ed045d126421c96055f10032e60e1a", size = 1358058, upload-time = "2026-10-03T04:24:14.819Z" }, ] -[[package]] -name = "opentelemetry-api" -version = "1.45.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/1f/dc/e12c1fe1ed8a7b7149777127b1a0e12ce5bd5a81d97408bedc2128c260f5/opentelemetry_api-1.45.0.tar.gz", hash = "sha256:711ede81773c8025c2c03dac0450bc89f3d30aea6eabcc815c570d4e35a963f7", size = 72115, upload-time = "2026-09-25T12:32:28.399Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/44/b9/040d1a1c7836922828e6480cd2366bb8fe0ebf75b413d2bb51a9b0e7f78f/opentelemetry_api-1.45.0-py3-none-any.whl", hash = "sha256:80e068aba7cd56c8b58512d6a36f8d25cb1dfaa0c0a4cc1c938ccf9f362d9cb3", size = 60020, upload-time = "2026-09-25T12:32:03.192Z" }, -] - [[package]] name = "orjson" version = "3.12.0" @@ -1519,62 +1439,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" }, ] -[[package]] -name = "pydantic" -version = "2.13.5" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "annotated-types" }, - { name = "pydantic-core" }, - { name = "typing-extensions" }, - { name = "typing-inspection" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/53/ef/fc4f868f4e2cee79f863883abffceff107875f569b848507319842d2a681/pydantic-2.13.5.tar.gz", hash = "sha256:51a9c5f7b2f8e636f04c6cada605d9b6a3bf1348fdf945a3d8869b19bba0ee08", size = 845750, upload-time = "2026-08-28T14:04:00.916Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/eb/47/c95ffc2009878c7aac0c5e08528022dcb885933252a88b5f170058014464/pydantic-2.13.5-py3-none-any.whl", hash = "sha256:346a034f080da3755d8e9cb5e00e8b07de1d39e4f6e2c87d8ab7cafa0b269a73", size = 472589, upload-time = "2026-08-28T14:03:59.136Z" }, -] - -[[package]] -name = "pydantic-core" -version = "2.46.5" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/af/f9/8a06bea35ef8daf588f707784c973a7046e0034c8d8cfb08828eeffb8b75/pydantic_core-2.46.5.tar.gz", hash = "sha256:10416c15b8839ecc4ef4d0885da76da6fd0f67333a0eb8aff6d93c4b8f2910fc", size = 472262, upload-time = "2026-08-28T10:01:31.677Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8e/8a/14596f2a8367da50cf7cbac48169ee5d9c8e11d486a3b527082384630c72/pydantic_core-2.46.5-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:c1c43ad4339643d70ebb8124e1305a7dab423001eff58bb41a0f731adbc98355", size = 2074081, upload-time = "2026-08-28T09:59:16.141Z" }, - { url = "https://files.pythonhosted.org/packages/ae/d5/d8a4eb6d6c7f66b91dd37c576d76e9e60fba900caf5372c17bcf949febc2/pydantic_core-2.46.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1a353f84de772f423b5ffb11d7ae352fbbef0f446f3c0b0af0f8236d7233606e", size = 1920497, upload-time = "2026-08-28T09:59:18.065Z" }, - { url = "https://files.pythonhosted.org/packages/8e/26/092079428f86e927e030b2c0ced87df69dbb1c875cdeaa67bf42ea2be746/pydantic_core-2.46.5-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5086029a57366b8cf81b130a43908738095c270c21a8d7f0e8bdfdb89718e2f3", size = 1952130, upload-time = "2026-08-28T09:59:20.476Z" }, - { url = "https://files.pythonhosted.org/packages/08/c3/8ec0e290a9ebaebd64047bf5fda94be835c6b1551b02437e4b76778fbcd7/pydantic_core-2.46.5-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:46c25dda9d092a06c08db76ffe0a197107904d0dfac653f7d5306bbcd6d6119c", size = 2026371, upload-time = "2026-08-28T09:59:22.227Z" }, - { url = "https://files.pythonhosted.org/packages/01/72/4fd20ad520fb8da0157f95b27a7eb05a72790ef08138e7701ac972c342ea/pydantic_core-2.46.5-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:37ea7b83c935e5b0d68c9449b82651accf78a10828b2c02b2f2d9e9496446c21", size = 2202822, upload-time = "2026-08-28T09:59:24.277Z" }, - { url = "https://files.pythonhosted.org/packages/31/b0/d16e0771206b29314f0d52198b720be21e8a99ab2bf11e3bc0d7c9cebdff/pydantic_core-2.46.5-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e64e88d5585bea9ce95861079de72006c7fa6d3df4e3a3b65ba31eb979c15c9f", size = 2262756, upload-time = "2026-08-28T09:59:26.608Z" }, - { url = "https://files.pythonhosted.org/packages/2c/9b/59634b7ac631c63b2a37760eb6943af3e29573d6b59a4abc5e7f019d4cee/pydantic_core-2.46.5-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:54d510bac3ee52247af28ed4bb18a1e799f040ac60fd2bf5ccd4c92f1fbe786f", size = 2068352, upload-time = "2026-08-28T09:59:29.044Z" }, - { url = "https://files.pythonhosted.org/packages/08/7c/570abb1ad2155348dc754ea91be22e5aaa18eb6d69a6068f7c6f2679a6ed/pydantic_core-2.46.5-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:a2a5e1d0ff29adddc9f6d6821a66302e4493f8ca898b715b6b1182c2c201ea0a", size = 2104777, upload-time = "2026-08-28T09:59:30.95Z" }, - { url = "https://files.pythonhosted.org/packages/8e/25/5bf74adc65a1ac5b7be3f6cb0bcb5433615c1598a801c19d830d84c98ded/pydantic_core-2.46.5-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:03b9666e41e35d8909852ba191a0607520f81b74eaf12ccf8737005dbb313821", size = 2156312, upload-time = "2026-08-28T09:59:32.604Z" }, - { url = "https://files.pythonhosted.org/packages/90/6a/2ef38830675e050121040618135564ed56b860b45433b02d9b4ebece46f3/pydantic_core-2.46.5-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:a91c17edf6eea2402cb5457b4c89e99bc5ed1004aa34c4adf1d4258c1a5c22c2", size = 2150067, upload-time = "2026-08-28T09:59:34.453Z" }, - { url = "https://files.pythonhosted.org/packages/90/ef/a7dbb03a14a64c2a4621f989c615ed9a892535a6cad938fc27079f919d80/pydantic_core-2.46.5-cp314-cp314-musllinux_1_1_armv7l.whl", hash = "sha256:b49924c73a235e969511bf2aabdff3beebf9820931f646c80274d5d780010c47", size = 2304516, upload-time = "2026-08-28T09:59:36.194Z" }, - { url = "https://files.pythonhosted.org/packages/68/f8/6bb4c4b80e8a6fde1904c64a51c62a1d04fcdfa3ea521a66b2ddefa1d885/pydantic_core-2.46.5-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:2cbd9a5eff05e51c447c34dfa4632145b26b09120cf04bd0c871e44c1a5e1c9a", size = 2335223, upload-time = "2026-08-28T09:59:37.931Z" }, - { url = "https://files.pythonhosted.org/packages/2a/80/f46b8c681195190b2c1f1c7c0a81abce60663e987613e09ef64d433dd96b/pydantic_core-2.46.5-cp314-cp314-win32.whl", hash = "sha256:2d5d76654becf5efd62c9e51c3756c67b49498b0c9a40884934c40807adbd074", size = 1934827, upload-time = "2026-08-28T09:59:39.836Z" }, - { url = "https://files.pythonhosted.org/packages/f7/3c/60674207246bc0a4009d2391b7c7251c7159f279c8d2ab8aae8ef46f3dee/pydantic_core-2.46.5-cp314-cp314-win_amd64.whl", hash = "sha256:fa10ef4112775900e7a0661068635eb67b2ab824fbde764de6e0e21982a93db0", size = 2042648, upload-time = "2026-08-28T09:59:41.792Z" }, - { url = "https://files.pythonhosted.org/packages/69/0c/117c562c7c1babdf44576b72a5e496906506c93690387ecfbca7c729ae2e/pydantic_core-2.46.5-cp314-cp314-win_arm64.whl", hash = "sha256:045ab3b6d308439e32b81cc173bba5b9018bc6ed896afd0c65b3b009b1699af5", size = 1989652, upload-time = "2026-08-28T09:59:43.702Z" }, - { url = "https://files.pythonhosted.org/packages/e8/66/9336ae58f9eb68c41d121894e52c4c89eccb07eb8f602a04ee9c3f37736a/pydantic_core-2.46.5-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:8816f3d218beb4b787de5c9759c259b8fa61f9dec42dc7811f320a33771778b7", size = 2065829, upload-time = "2026-08-28T09:59:45.364Z" }, - { url = "https://files.pythonhosted.org/packages/c5/02/bc19b47a96c2d3109760711acf22369e56bd7e405ca52f7ade164d2ead57/pydantic_core-2.46.5-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:bce57638e08ac148e5778cce7feb968307a727d66f8e2274a543d0cf0c9ad6a3", size = 1905716, upload-time = "2026-08-28T09:59:47.18Z" }, - { url = "https://files.pythonhosted.org/packages/52/a4/70b47c0509923dd98ccfed04fb3e32ea3849c82a0ff2205bb41009b43c00/pydantic_core-2.46.5-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:976e1128455aa595ea04c79ccfedff1aaeab96ee013fcc916bed120c4f0ad94f", size = 1934216, upload-time = "2026-08-28T09:59:49.241Z" }, - { url = "https://files.pythonhosted.org/packages/52/ab/aa03b65f7bb198585edf806b906c3223ecf1795543e39e23aec4cce27ad2/pydantic_core-2.46.5-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e7b891faeedeafba41b2983e5001a81b6a915b69544c7e7570d1989ce1c36ac7", size = 2010635, upload-time = "2026-08-28T09:59:51.692Z" }, - { url = "https://files.pythonhosted.org/packages/3c/8b/0da06343f30b84ec549aafd309c6456223d5dc8bd36af504c573faad561d/pydantic_core-2.46.5-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5f194189415698233dd1114a093a9b56e61e2c57e11b469be3b0506f46f0771c", size = 2209369, upload-time = "2026-08-28T09:59:53.582Z" }, - { url = "https://files.pythonhosted.org/packages/d6/5b/844c4defaa34a3df66eb9257087d121d70c201298b96abdf9f492fc2f1bf/pydantic_core-2.46.5-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:82a36973cf8a2ef5406f4fe2edbf8ed0c99629535d959e0b100c76a32535a111", size = 2253238, upload-time = "2026-08-28T09:59:55.484Z" }, - { url = "https://files.pythonhosted.org/packages/f4/64/a4e536cb16d7f61a7fd3120b46c577fc7fa7325992f69c4f52bc786d77d8/pydantic_core-2.46.5-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cdbb78909f52b981d3b2d56b97328d71eb0b974c36bd77c920123a7ebb192829", size = 2065740, upload-time = "2026-08-28T09:59:58.038Z" }, - { url = "https://files.pythonhosted.org/packages/5f/75/aaa38c6bc2d085f6605b34eabdc6a8a4e0b2e61fc9c8e6e52b28e97b3125/pydantic_core-2.46.5-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:52e24eacdb536cade636aa90fb851835222becff8484b7001fdc78cb0290f2aa", size = 2087425, upload-time = "2026-08-28T09:59:59.898Z" }, - { url = "https://files.pythonhosted.org/packages/55/ae/fcab4cfc39aba3689e1d20c8b5250ad280957022c09af2ed9cd585602a5e/pydantic_core-2.46.5-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:37ae34309d7bd8c0d61ab839668058f2a7962ea1fc51d105d2db228fe0618034", size = 2139306, upload-time = "2026-08-28T10:00:03.057Z" }, - { url = "https://files.pythonhosted.org/packages/2d/f4/f1d03a4bc9d9acbc62f4d742b8a319af52f71885079868b2ff8e48a651ee/pydantic_core-2.46.5-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:0cdbada856a1c69a7624a64d3d9aefe79300bd6ef827b43a4f265010b9b55184", size = 2144589, upload-time = "2026-08-28T10:00:05.645Z" }, - { url = "https://files.pythonhosted.org/packages/83/f3/7a53bb1356de514a4cd295f25b6ac39237895620c0462d2592b76c16e114/pydantic_core-2.46.5-cp314-cp314t-musllinux_1_1_armv7l.whl", hash = "sha256:545f26c504b27c3758439a5e6d9349931f0a04f855668d5fe323c89e82300a38", size = 2288882, upload-time = "2026-08-28T10:00:07.931Z" }, - { url = "https://files.pythonhosted.org/packages/cd/94/5a81583660c175c59d49ffb09f4b3a44debeaf86a19fca664ae1cdd9ee32/pydantic_core-2.46.5-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:ff218293c9c806138dca139765e3b067621be52bcd93cdc14c7711be7ddc90a9", size = 2335210, upload-time = "2026-08-28T10:00:10.177Z" }, - { url = "https://files.pythonhosted.org/packages/5a/9f/5d685c2693b972d1a59c998586e8823712b66603aeff47ee60a4bdaafd37/pydantic_core-2.46.5-cp314-cp314t-win32.whl", hash = "sha256:97cf3eb53a8cccacf9d46686a0926186c9bfb5574f2ed66d3639d5fe117cd3a9", size = 1921180, upload-time = "2026-08-28T10:00:12.35Z" }, - { url = "https://files.pythonhosted.org/packages/70/12/5c94ee16d65a37a15f9e869f5e6256df111154491173801a4c5e800ab548/pydantic_core-2.46.5-cp314-cp314t-win_amd64.whl", hash = "sha256:d2f9fc07a8042a8f95925b35c4f04f469707c981fc33245b6ca187cf5d2dd290", size = 2020515, upload-time = "2026-08-28T10:00:14.774Z" }, - { url = "https://files.pythonhosted.org/packages/63/19/67830dda664e6bdf9285ee2e40f355d0d7d6b92aa0c42e8d217bb8d33d36/pydantic_core-2.46.5-cp314-cp314t-win_arm64.whl", hash = "sha256:acf8a67ba51f4ca9ddbd0e6b3000a65ac51ab734661778b3e7ba64d99a710f2f", size = 1989276, upload-time = "2026-08-28T10:00:16.984Z" }, -] - [[package]] name = "pygments" version = "2.21.0" @@ -1687,7 +1551,7 @@ name = "pytest" version = "9.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-runtime') or (extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-test') or (extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-training') or (extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-runtime') or (extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-test') or (extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-training')" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, { name = "iniconfig" }, { name = "packaging" }, { name = "pluggy" }, @@ -1698,15 +1562,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, ] -[[package]] -name = "python-dotenv" -version = "1.2.4" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/74/26/2fbeedb218a787a5eea551c7532cac4e009f83d689dd2faa0d0353473f86/python_dotenv-1.2.4.tar.gz", hash = "sha256:f0d53e69935a851c0dcc78f3ab7aaccd8cabef0b92382b576b824212902873c0", size = 60824, upload-time = "2026-10-01T05:36:10Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/60/d1/38f3a3405989a89ac18390803e70c6ad7c7760da4f9b83cbeca0c44a0c72/python_dotenv-1.2.4-py3-none-any.whl", hash = "sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc", size = 23266, upload-time = "2026-10-01T05:36:08.633Z" }, -] - [[package]] name = "pyyaml" version = "6.0.2" @@ -2017,18 +1872,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/4c/07/2ebca9b11fb9be7340a818d8d6f63feaebb146be2c4afbd6061701d6df6e/snowballstemmer-3.1.1-py3-none-any.whl", hash = "sha256:7e207fa178741da09cdee59d3ecec3827ad5f92b1fc5c9ff3755b639f71f5752", size = 104164, upload-time = "2026-06-03T00:56:38.614Z" }, ] -[[package]] -name = "starlette" -version = "1.7.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "anyio" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/7b/2b/3850dc6bf7ef71b088962eba31dafc6cffd2f96e577ebb0bb316df96da3e/starlette-1.7.0.tar.gz", hash = "sha256:c79f74ea63cff761804fbbfb182f1e0b440c2d07b164d24700c5a1bab5d6ff5d", size = 2736246, upload-time = "2026-09-23T07:30:26.35Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/4e/d6/1ec1b290f9e0fb067899b61e1d37a30c923068bad260b216dbe37a7d2967/starlette-1.7.0-py3-none-any.whl", hash = "sha256:67f8e99895493dd2911a03f11314af6ceebeae4e704bb9f43dfc6a9db151c93e", size = 78980, upload-time = "2026-09-23T07:30:24.567Z" }, -] - [[package]] name = "sympy" version = "1.14.0" @@ -2166,18 +2009,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, ] -[[package]] -name = "typing-inspection" -version = "0.4.4" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a3/26/b09b8010994eccc3c09092e6b34058f36a460eea2d4c3e8b910c695975a0/typing_inspection-0.4.4.tar.gz", hash = "sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47", size = 76928, upload-time = "2026-08-12T12:37:25.997Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147", size = 14750, upload-time = "2026-08-12T12:37:24.648Z" }, -] - [[package]] name = "unittest-xml-reporting" version = "4.0.0" @@ -2199,190 +2030,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, ] -[[package]] -name = "uvicorn" -version = "0.54.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "click" }, - { name = "h11" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/da/34/30e9280707135d2cfc589dfff3cb796bd07a3aeb1a3e415ba09dd89d7bb4/uvicorn-0.54.0.tar.gz", hash = "sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620", size = 112283, upload-time = "2026-09-25T06:52:37.601Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/38/0c/b54a4fdd7f90a3af8b02ebc9ce6712c2c208b7926a2f7bad95c33ebbe943/uvicorn-0.54.0-py3-none-any.whl", hash = "sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf", size = 87427, upload-time = "2026-09-25T06:52:35.829Z" }, -] - -[package.optional-dependencies] -standard = [ - { name = "httptools" }, - { name = "python-dotenv" }, - { name = "pyyaml", version = "6.0.2", source = { registry = "https://pypi.org/simple" }, marker = "extra == 'group-22-openbikecomputer-tools-dev' or extra == 'group-22-openbikecomputer-tools-planner-search' or (extra != 'group-22-openbikecomputer-tools-search-runtime' and extra != 'group-22-openbikecomputer-tools-search-test' and extra != 'group-22-openbikecomputer-tools-search-training')" }, - { name = "pyyaml", version = "6.0.3", source = { registry = "https://pypi.org/simple" }, marker = "extra == 'group-22-openbikecomputer-tools-search-runtime' or extra == 'group-22-openbikecomputer-tools-search-test' or extra == 'group-22-openbikecomputer-tools-search-training'" }, - { name = "uvloop", marker = "(platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32') or (platform_python_implementation == 'PyPy' and extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-runtime') or (platform_python_implementation == 'PyPy' and extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-test') or (platform_python_implementation == 'PyPy' and extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-training') or (platform_python_implementation == 'PyPy' and extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-runtime') or (platform_python_implementation == 'PyPy' and extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-test') or (platform_python_implementation == 'PyPy' and extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-training') or (sys_platform == 'cygwin' and extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-runtime') or (sys_platform == 'cygwin' and extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-test') or (sys_platform == 'cygwin' and extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-training') or (sys_platform == 'cygwin' and extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-runtime') or (sys_platform == 'cygwin' and extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-test') or (sys_platform == 'cygwin' and extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-training') or (sys_platform == 'win32' and extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-runtime') or (sys_platform == 'win32' and extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-test') or (sys_platform == 'win32' and extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-training') or (sys_platform == 'win32' and extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-runtime') or (sys_platform == 'win32' and extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-test') or (sys_platform == 'win32' and extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-training')" }, - { name = "watchfiles" }, - { name = "websockets" }, -] - -[[package]] -name = "uvloop" -version = "0.23.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/fa/42/02c739ce85fb2ee8d99212c61417da8140c6b87e9d97c430bea520d76044/uvloop-0.23.0.tar.gz", hash = "sha256:28d160f51ab4da3b187063652e643dea6831072add4adc1e6d62afbe73b6be27", size = 2559185, upload-time = "2026-10-01T03:17:04.4Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/4e/a4/00e85345871c59c834a23c136c1771205856028ecc8ba940b3951178e59b/uvloop-0.23.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:b90397a50ad6332ed3e459c648ac20d182cce24a557354363ad85fc9ea4a17cd", size = 1421363, upload-time = "2026-10-01T03:16:02.599Z" }, - { url = "https://files.pythonhosted.org/packages/d0/a9/e5f0f3cfde30af3ec32eba8ec07bccdba2b5116afbd1ecc53edfeb0a0790/uvloop-0.23.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:be53e1d5f83de43dc175c87612ecc128d444b38e5c56cb3f807f5a73d6887476", size = 785177, upload-time = "2026-10-01T03:16:04.018Z" }, - { url = "https://files.pythonhosted.org/packages/9e/79/9ddf78f8cd75a15c14a09a57f59c587b8cd9d82802c5c8368b9c3ebefa0b/uvloop-0.23.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6b3cbc4f96ddfa1fb88a78a69dd851369825b7816d9702eee8c4461505ba172e", size = 4381060, upload-time = "2026-10-01T03:16:05.642Z" }, - { url = "https://files.pythonhosted.org/packages/1e/20/57d63c44d32326878fcad5c63854afc9deb394ed95673c1b1a429178c79d/uvloop-0.23.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:31e0cf90bc8fd88784f6802cdba968a51fb1aec1cc3feec74d862b2d371d1330", size = 4418891, upload-time = "2026-10-01T03:16:07.326Z" }, - { url = "https://files.pythonhosted.org/packages/12/c5/0795abecda2cc3dfe41033f880a32a9ff103be4e6b177ac736833c153a0e/uvloop-0.23.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fa8ed556fcc87a4091cf61587ef172fa104323dc89ecc085a618ba7ff8629a8f", size = 4214811, upload-time = "2026-10-01T03:16:09.13Z" }, - { url = "https://files.pythonhosted.org/packages/20/18/9010dacd5221eec1bd79a4a83ac68f3db6a42d7bb657f7b640c4838ca6b6/uvloop-0.23.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f3fbfe82829d8e381426a289b87e59e585278728361db9ce975b88b51f64f410", size = 4294876, upload-time = "2026-10-01T03:16:10.875Z" }, - { url = "https://files.pythonhosted.org/packages/b1/08/f6384a03c771d00067cba4f542a69b2fc1a982e9fd78b357c2f788678d72/uvloop-0.23.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:7e35c9bc977760981693e1a7a51493b58ee5a501f9ebb1e547565ee40b6c6208", size = 1494811, upload-time = "2026-10-01T03:16:12.399Z" }, - { url = "https://files.pythonhosted.org/packages/ac/01/756a4fb24a449f313cf4a153eb0c6210b49cfe5539255ec9fb1e17d2c4ef/uvloop-0.23.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:5bb9be71d9ee39b4359b832f9569518ec9bc08704194034e79e4958e6bc4d46d", size = 819396, upload-time = "2026-10-01T03:16:14.094Z" }, - { url = "https://files.pythonhosted.org/packages/3e/45/e314b0c600b14f53dad3a3c2d7a922a249a88225fd727652b53e1854b9dd/uvloop-0.23.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1e84575f11873c109cf3962ad0bdf679094466184125f4cadcc41a73febff41f", size = 4734966, upload-time = "2026-10-01T03:16:15.815Z" }, - { url = "https://files.pythonhosted.org/packages/66/0d/8686a7f0b1b2d55ebd770ba21f8e0e4ffa0cde5ab738f43ffb8264499052/uvloop-0.23.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bbbdb8fcd5e7062e546eec1ac78c28bb21ae7df54c18f8e4b06e15a18d661a49", size = 4584963, upload-time = "2026-10-01T03:16:18.198Z" }, - { url = "https://files.pythonhosted.org/packages/78/b2/034a2d47e435ac02357c42956246887167bdc0357bdd6ad31c5f6d94497b/uvloop-0.23.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:76345f51367fb1f23e08605c6efb18374f669be5b223658fbab6b17627950507", size = 4421388, upload-time = "2026-10-01T03:16:19.953Z" }, - { url = "https://files.pythonhosted.org/packages/f0/77/131f4b583e6b4b715c404a66b51c812d701db20f25c9018b188a2b00062c/uvloop-0.23.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:6c7ef4701a96553514b2688e342ef1bf2beae6cfd172d89a76c768292aabf405", size = 4402414, upload-time = "2026-10-01T03:16:21.716Z" }, - { url = "https://files.pythonhosted.org/packages/58/3d/ee11f4718ea1280595c67ed25c83d4c92115dc100bbdfd192d3ed9339168/uvloop-0.23.0-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:f1341c6abcee1c31277cfe28d34e46196f2143ec3d755e6efe7452126e1f626d", size = 1418095, upload-time = "2026-10-01T03:16:23.241Z" }, - { url = "https://files.pythonhosted.org/packages/f8/0c/7ca516a0671418517d79a09d3ff2ccbb44af94c75711afa6e4cf58aa6f65/uvloop-0.23.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:e095f9e105af76593b4c183bb0bcbdae64bd913a59ec595732dc108b48730ab5", size = 784837, upload-time = "2026-10-01T03:16:24.666Z" }, - { url = "https://files.pythonhosted.org/packages/35/95/75d4e28e596d505b7ae11de517646b4ca3d369fb8537ba755410380da11a/uvloop-0.23.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f673d835bdb1a60229cc3609a113fd2c9ce3f4a3c75ad4eaed111180c00199d2", size = 4380276, upload-time = "2026-10-01T03:16:26.389Z" }, - { url = "https://files.pythonhosted.org/packages/10/99/68daf827ad62efaf4667d1f3fda127046d42161178396bdd93aab3684082/uvloop-0.23.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c3f23f403a273900d57de6ee5ca0614c650f7f58563065dad1a4744498960e53", size = 4451496, upload-time = "2026-10-01T03:16:28.364Z" }, - { url = "https://files.pythonhosted.org/packages/71/69/f67e696ee688f426a96f99099bae26fec14a1d0fa75dccdd6518ee267c0c/uvloop-0.23.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:cbe8d03d4efcccdb7fcedecbaa1e1fa02913eaf3a74cb933634a6bc6d2ea9e2a", size = 4212541, upload-time = "2026-10-01T03:16:30.014Z" }, - { url = "https://files.pythonhosted.org/packages/f1/6a/c8c436a9d7453297b4be70bdf6a9f9fc9400da45e0059ddf7b28ab63f4c7/uvloop-0.23.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:4f1798f56c6f4ba5ac11fa2869e5717926e4470d97a1dd42b4f59219d43b5027", size = 4319377, upload-time = "2026-10-01T03:16:31.705Z" }, - { url = "https://files.pythonhosted.org/packages/3b/2c/8fc15a03489299aab8a6212dfe0f137dc39836f915c87f7fd9d9ddd814de/uvloop-0.23.0-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:098a85e1393ef5202767b7e5fb41a32cd8bd81e6ee4af364c179801c4aa3f6d4", size = 1493428, upload-time = "2026-10-01T03:16:33.859Z" }, - { url = "https://files.pythonhosted.org/packages/b7/7c/05e4a210790229607f71460fcb2ed4a2c7bc72668d8a928ce577c22e38f8/uvloop-0.23.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:5a2bbad3a63007f7e9524d4903ba04fee252557c2acd86f9a3d4f91786695254", size = 818115, upload-time = "2026-10-01T03:16:35.45Z" }, - { url = "https://files.pythonhosted.org/packages/65/14/a40b11c6c024213803b13955664a15754c72f64c873a33d986b26ec9ff5b/uvloop-0.23.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4a08875543bbd4519faf30497506c9cda8a48470467ffdf967c7313c7a5981a8", size = 4734149, upload-time = "2026-10-01T03:16:37.025Z" }, - { url = "https://files.pythonhosted.org/packages/9f/83/f421a077712c1e87603bfec62744c3cd3a2f4b47378025db3d740df9af0d/uvloop-0.23.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:12634f15e6625f78b3f2922f91404c4d7173487eba11746764153f556e9852dc", size = 4661763, upload-time = "2026-10-01T03:16:38.719Z" }, - { url = "https://files.pythonhosted.org/packages/f5/62/25dcaa6b7e7b48f82ce633854ce96597ab768f9650931f4f86c572de392c/uvloop-0.23.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:378188efbb1524f2219d05246a3e1e5907217848d2882144dff59585f1b81d55", size = 4421324, upload-time = "2026-10-01T03:16:40.488Z" }, - { url = "https://files.pythonhosted.org/packages/05/46/04628239b43dcef703af314202a3307d6060918e2d76aa86c5b1188f5551/uvloop-0.23.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:4b8e207c67d207a8608fec57e116511030af3495dc0109b8c333cf9cb412b16f", size = 4462501, upload-time = "2026-10-01T03:16:42.359Z" }, -] - -[[package]] -name = "watchfiles" -version = "1.3.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "anyio" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b3/68/e6aa0b77d217b31f8f486ec0cdfe5e00e6e38dc0be657e7d85819b9faf0a/watchfiles-1.3.0.tar.gz", hash = "sha256:99aee4a07847c06820765fd7b1b49ceac4f3f711ccb7d104655a33231de1c207", size = 108119, upload-time = "2026-09-21T09:08:55.664Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/68/fa/c0b840d5d8bafe640925408ce11095948c8945bb61be1e67d0ab629b872a/watchfiles-1.3.0-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:000b9688fc8133037a8b075c8ebf98f32844ff8964dda61e85c1db547dafc441", size = 399703, upload-time = "2026-09-21T09:08:13.518Z" }, - { url = "https://files.pythonhosted.org/packages/c7/8a/894799b485fe9473ad10422a0d9668e53fb78e3a2b5cc6061159572844ad/watchfiles-1.3.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:bbc1198edfdc90fda0600f825aa94150f428dfcbf8138746f55998e0e660d64c", size = 397647, upload-time = "2026-09-21T09:08:15.16Z" }, - { url = "https://files.pythonhosted.org/packages/5a/61/f277cd5ead05f5d37b98b41fbdd0c943ee0c04d49738f62e902cb291cf43/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4af9c464d410e8c44b58ddf1cbec7c3a02c1cb2c6c80df9c74659ba2fbda0ab5", size = 454994, upload-time = "2026-09-21T09:08:16.587Z" }, - { url = "https://files.pythonhosted.org/packages/46/66/ea4c01382975e53b1ac1b0a0ea1b353416b8127fb6e04f5c1c313119aab6/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:eb94e40b9a0db19636b5e3fed0a9803452ecc7381df13b385272abb779ee83ca", size = 460105, upload-time = "2026-09-21T09:08:17.961Z" }, - { url = "https://files.pythonhosted.org/packages/31/c3/1a501b597817096c9831c255f6270c124ce0e2faeb74124be24dcc93b86d/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7398930a2b76b9dc67a4e6b8bfc7baf30946892a86f417a3920c07bdd6febc30", size = 493761, upload-time = "2026-09-21T09:08:19.327Z" }, - { url = "https://files.pythonhosted.org/packages/5a/16/77352d05e152c7786a016e9f1decdb4507e8aa5bcf3343c72142a0413d14/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:025b108f2d5cc2799cb941f79380df3e8b22bfb589c218e801767fe78d598c95", size = 577500, upload-time = "2026-09-21T09:08:20.723Z" }, - { url = "https://files.pythonhosted.org/packages/95/fe/81001c55b24466fe9911135e50269fd3a29f43e446627a92adfab54553b6/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:be9ef3cd403d756a304a0a08a112163c63da7ec72c8c9d083c98818291ff8f29", size = 469209, upload-time = "2026-09-21T09:08:22.346Z" }, - { url = "https://files.pythonhosted.org/packages/8a/cf/e3ad894ed5909a7c44b0707e89bc25d19a3d78b3a7aec846119443b6ae56/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b5768b49e426fd5b550b012c866db347cdf15c398ef98dc557b6e6b72fa74cd1", size = 458353, upload-time = "2026-09-21T09:08:23.7Z" }, - { url = "https://files.pythonhosted.org/packages/7f/f5/2f106829e6e2bc91ad74614730f6df484202b9a4d20d927dbf2f08d37d44/watchfiles-1.3.0-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:d36c72fcdc08f143d87316a4c4c3b064e340da2c7383d39803950740ed418935", size = 468707, upload-time = "2026-09-21T09:08:25.167Z" }, - { url = "https://files.pythonhosted.org/packages/15/37/2741ab776b978669c1f3bba1e573f1a184f727ab8b4d3a6d9c61090800ed/watchfiles-1.3.0-cp310-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:f0c9865240e065a2247f4b5248528ae3d01e0e8ae071462c250c884dc16e3ee3", size = 632510, upload-time = "2026-09-21T09:08:26.532Z" }, - { url = "https://files.pythonhosted.org/packages/48/64/db4a4684275fe9b696ee5118c194705c1423b3d42181c3f8ee70194d5c73/watchfiles-1.3.0-cp310-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:380f513d26cc2e598266b88d66456e07d67ef4be8f0f435a1154d9c44b43d509", size = 661723, upload-time = "2026-09-21T09:08:28.004Z" }, - { url = "https://files.pythonhosted.org/packages/52/80/95ddb24f6a2f595c031c24432ab7b8aa7d6d1ada0c6d63a552166e06e8d1/watchfiles-1.3.0-cp310-abi3-win32.whl", hash = "sha256:509d9f74d2bec5c1f4cd868ddcfe0c9601f7ea53066dfcb19d8ede742c4de661", size = 277761, upload-time = "2026-09-21T09:08:29.335Z" }, - { url = "https://files.pythonhosted.org/packages/48/a1/1c4a1b3c8030cd03206232612be8a6e8799093490c220b0fcb935d02b75a/watchfiles-1.3.0-cp310-abi3-win_amd64.whl", hash = "sha256:1acabde19b67e673274e89a04d613b7fb1f122e2c4b8ec9a581e59c149264b61", size = 290643, upload-time = "2026-09-21T09:08:30.45Z" }, - { url = "https://files.pythonhosted.org/packages/82/e0/d2db577c632d26d08078c4390dd870b8555c4e558df25d22270f0166c71f/watchfiles-1.3.0-cp310-abi3-win_arm64.whl", hash = "sha256:d978cc1dd7ba44f5590d7de74f7a9c8be7262d9e469c2c0efb8bbfc2574321dc", size = 285510, upload-time = "2026-09-21T09:08:31.561Z" }, - { url = "https://files.pythonhosted.org/packages/4f/55/a122743607939429ab6a7272672f49303aa02bbd34c3f06676765a3861de/watchfiles-1.3.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:e0204f90677b7fb8d3a824279a71a01166bea9f6e53923b8056592d87b33b0b6", size = 395978, upload-time = "2026-09-21T09:08:32.747Z" }, - { url = "https://files.pythonhosted.org/packages/3e/9d/0ee1b0ea42acfe72afa2484f0222e2386dd09992e9034a81e63cc3cdab0a/watchfiles-1.3.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7c1125e99f84934a92996ae343501285617373acd66f16b59fd5654b27ad8d80", size = 387997, upload-time = "2026-09-21T09:08:33.953Z" }, - { url = "https://files.pythonhosted.org/packages/b7/f2/4319c6b683e8bd28465dfc53c750617a2a07f072eb2e3ab0182ccf812229/watchfiles-1.3.0-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a85e243c87109d9f48a2e0d10d6abdee8768cc114848b32281ec83d7f81d86ef", size = 448067, upload-time = "2026-09-21T09:08:35.104Z" }, - { url = "https://files.pythonhosted.org/packages/b7/71/9f37ac192a51a24de3a2d7fe9aac1e99b2b2668300674ff7a9f85d95beb1/watchfiles-1.3.0-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:dd538c71766c59c732e2c5cedc39323c99c11897b99f93eac773438e54af206a", size = 452881, upload-time = "2026-09-21T09:08:36.238Z" }, - { url = "https://files.pythonhosted.org/packages/34/07/1224667c32a4a96876ddd642da69733cbfe6a15897db0865aec5a882cebc/watchfiles-1.3.0-cp314-cp314t-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:da213822ec9082b62cadf3008e07a8c690ec7a3c89f6dc5e55a8cf07b56a1b26", size = 484802, upload-time = "2026-09-21T09:08:37.717Z" }, - { url = "https://files.pythonhosted.org/packages/bd/4d/7f29cd87e1f826df86fc0418d0b8f370ca0311c29c618406dc492aad9951/watchfiles-1.3.0-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d4593392e87669836670f87d62fc754059eaeb0e6157af44060a46558cebe5a3", size = 567522, upload-time = "2026-09-21T09:08:38.94Z" }, - { url = "https://files.pythonhosted.org/packages/e3/ac/3aa1f84abd4dbbfbae99a817dd931f77b439261c911189cad4c30fdfd470/watchfiles-1.3.0-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:26b81bc515a0f03f66a69a6fea86eea54c8eca4173c46dd7222569f79dd2f977", size = 461997, upload-time = "2026-09-21T09:08:40.142Z" }, - { url = "https://files.pythonhosted.org/packages/82/1c/27c66764d5b0dbb70a36770a32eca217eba739c28b24e8583a035087a3d7/watchfiles-1.3.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ca39661934749df580d89f3dde266f2af7c6968f4c21c72ce2dc387d299e6aa7", size = 451856, upload-time = "2026-09-21T09:08:41.305Z" }, - { url = "https://files.pythonhosted.org/packages/1e/b3/a45827084d953c1d0dd3d75abf85dcac26a0f5d115ad2fe0b7e9e931573b/watchfiles-1.3.0-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:04c5500faa725d69a99b0f63750e80795e455bb951849e9c98a811b4324997c4", size = 459889, upload-time = "2026-09-21T09:08:42.58Z" }, - { url = "https://files.pythonhosted.org/packages/7a/3d/07740d23ce2bb23419bb24055c435a9abe5fe03efdaea1ba0720b831aab6/watchfiles-1.3.0-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:ec3cd4bb181a7b6329134204c2277c7144ab5f62cce9c5335d6f901ee7ce8d6a", size = 624482, upload-time = "2026-09-21T09:08:44.064Z" }, - { url = "https://files.pythonhosted.org/packages/91/46/9540f8123eaec86df989f26d7704cad0448d9fb7271763a4f8f9fe23617d/watchfiles-1.3.0-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:e5871d4a7f788a9f64fb06f5793389d29d171e5c32d37c3ebfd520b017cc7694", size = 653724, upload-time = "2026-09-21T09:08:45.257Z" }, - { url = "https://files.pythonhosted.org/packages/25/9d/b9deb52f1e4528ffe44338c5ebab95c32ed79203082da661de50288e130a/watchfiles-1.3.0-cp314-cp314t-win32.whl", hash = "sha256:81c989d7267bfb7b676cd32c83bec97914e396870983cbf493e29415037bff5e", size = 270863, upload-time = "2026-09-21T09:08:46.518Z" }, - { url = "https://files.pythonhosted.org/packages/59/59/8b1881afccbafda06248be4185e28034dd73c80c85e4da24f2cb0c1321eb/watchfiles-1.3.0-cp314-cp314t-win_amd64.whl", hash = "sha256:d754e049006e81a9be49dc78ba7802081cee426e968cbc63ee19e164fa2d0e39", size = 286879, upload-time = "2026-09-21T09:08:47.874Z" }, - { url = "https://files.pythonhosted.org/packages/46/dd/41c12ae9745d5d72f709333287679d71cbba68ad7678fed872207bba94f4/watchfiles-1.3.0-cp314-cp314t-win_arm64.whl", hash = "sha256:a5b631db08fd3032db57ec6a92d1777cd60f88803287e4e941a4858c53aab1e0", size = 276924, upload-time = "2026-09-21T09:08:48.976Z" }, -] - -[[package]] -name = "websockets" -version = "17.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/01/89/3f825ab71c242fffb62ea8fe638741c290f62f8d7aadf8125ff897747af3/websockets-17.2.tar.gz", hash = "sha256:36c2fb94c990cc2545143b12690e2de6c16300f9dbe5b4f33fa300cf57dc8792", size = 188355, upload-time = "2026-10-03T14:56:53.5Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8b/74/6bc991a28ac983600e65de408ebd1b1413d554ed0468ae5c831bc52dded6/websockets-17.2-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:ecb748910e9ba4624ebe2057791df51dcbffb48c37108ab94a3c593472023c9e", size = 217791, upload-time = "2026-10-03T14:54:26.381Z" }, - { url = "https://files.pythonhosted.org/packages/cb/2f/158e99426be6e71d09520bae53f29294fbb614b2fc5fbf8867b1d08395a7/websockets-17.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:2ab9af5cb7265899e659f079eb71691375a1025b6d5fbd3caa495dd08f70833a", size = 215486, upload-time = "2026-10-03T14:54:27.962Z" }, - { url = "https://files.pythonhosted.org/packages/5c/09/1abf942723c0001d9c2fca1551907dade6304517b982b0bf10bba107fa81/websockets-17.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:06e46da092bca3a52e98f0458c66b247993ce501a07cd09c858be3296511ab7d", size = 215699, upload-time = "2026-10-03T14:54:29.523Z" }, - { url = "https://files.pythonhosted.org/packages/a7/1d/1ade03963ef497c47e6bad79e24370827b2fe6145fa8f58070ff2b7dcbac/websockets-17.2-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:fcce735ffd72ac4056db05325d9f0232382b74826f0196eb6a15ca903abdaa0f", size = 225081, upload-time = "2026-10-03T14:54:31.278Z" }, - { url = "https://files.pythonhosted.org/packages/9f/fd/47b8a0361c49da939b976a07b27a72a9f893d01dfcf4d2a28b53419ce1ef/websockets-17.2-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:42cbca10f82a8b2fb1536e8a0830ca6ceeb6bb3d8d64b766e0795369135654a8", size = 225430, upload-time = "2026-10-03T14:54:32.917Z" }, - { url = "https://files.pythonhosted.org/packages/f0/26/f4d4c76264ee037c5556ab5f50fcba302746dabf7528955534e4dda9965e/websockets-17.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c63ff5a21f26bd0e6a8464b53fadbe174825c8718ac14180df45665eaacdb6af", size = 226676, upload-time = "2026-10-03T14:54:34.833Z" }, - { url = "https://files.pythonhosted.org/packages/37/b3/c8b1c981322a050c4babfd327ffc9880f9c3834f5b15d2574e37eeb8768c/websockets-17.2-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:63f543463601c1558b755f8dd7618b6ec3dd0934dda051d3b7030d8c76e54de2", size = 228048, upload-time = "2026-10-03T14:54:36.424Z" }, - { url = "https://files.pythonhosted.org/packages/f0/5a/1cb29ddb23e6bc27ffd1c5316cd3616360d1ba0c3854eaa134ee3207bd28/websockets-17.2-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4c32eb565ad9ce8a6444248e5b7a19dbb86a81c811fe5fcc2fba7a735aed5163", size = 227281, upload-time = "2026-10-03T14:54:38.01Z" }, - { url = "https://files.pythonhosted.org/packages/ba/64/135274572dc0c845fc1111e2b932c807c395daac75d6eae6cfa148d8a208/websockets-17.2-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5d459bbb6c22f26dcebea56924a362aba50d453b9867912862c970434fcf0d94", size = 226025, upload-time = "2026-10-03T14:54:39.613Z" }, - { url = "https://files.pythonhosted.org/packages/58/75/f1e386aec3124489411caf5138cdd5a2bc43d3fd4a681c69adcf5f6272a5/websockets-17.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f19ca1a21871f024e38faf4107b433047df27558dff1b72a1dac31481e2c1fe5", size = 223277, upload-time = "2026-10-03T14:54:41.165Z" }, - { url = "https://files.pythonhosted.org/packages/60/eb/24733a0f568c2eb99e60f9faa620a98fb228c06a01e7e2f348b33290ed9c/websockets-17.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c76b4bcbf0f713194591673fc86a42820e14da6bbd1bb445d3d002cc4d1e4521", size = 226148, upload-time = "2026-10-03T14:54:42.779Z" }, - { url = "https://files.pythonhosted.org/packages/55/6d/ea66a30af74f5983cae31ebb9ef78b178b366a12856a414e1472225c4a34/websockets-17.2-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:30201a7f69833b015556c72feb69ea501b645986fd0b90dab13f589e995ff428", size = 224615, upload-time = "2026-10-03T14:54:44.41Z" }, - { url = "https://files.pythonhosted.org/packages/87/80/c6f2228ad89774429d270179375ebddb657119215f52d1df7c680d65cad7/websockets-17.2-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:0c8600aec354cc259f1691b0b42816f04a9886a953f82cb227246df76057f97a", size = 225398, upload-time = "2026-10-03T14:54:46.063Z" }, - { url = "https://files.pythonhosted.org/packages/f7/4a/3d8da19732ad468d4be7f1e3ac298078b60bdda55edde6589bef84a5eb7e/websockets-17.2-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:307fc22ea496be8542d67b82ae8c867a978dfd19ac35573d4f15943fd9277dfe", size = 226571, upload-time = "2026-10-03T14:54:47.672Z" }, - { url = "https://files.pythonhosted.org/packages/58/22/1231657122d9cc24791bb90af13cc2f4e84cf0d3a454cb37e3abfdcb2fd9/websockets-17.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:9c88697fa943bd4ef67cc919a17d81de6581846f52bfa8c6f64a916098986556", size = 224125, upload-time = "2026-10-03T14:54:49.537Z" }, - { url = "https://files.pythonhosted.org/packages/1a/04/350ca2445da758bc42cdb4218b44d4ce0d5a9c1d5e4cc4a58d64348ad9da/websockets-17.2-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:f7eac84d4969da82166d5e90d9c38d2f416fe24f9708a7013569b193745b9a31", size = 225081, upload-time = "2026-10-03T14:54:51.075Z" }, - { url = "https://files.pythonhosted.org/packages/da/c4/dec952b0df3a5d918ed2a545abb0c25ae519c3bc2d9aba3b7c46abae8f05/websockets-17.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:313f6703023d53baabab6d6c5c37cf637b2c4fee255acf2ed5e92ad69e28f1b7", size = 225376, upload-time = "2026-10-03T14:54:52.675Z" }, - { url = "https://files.pythonhosted.org/packages/f2/b4/198a260afbcc086ff4979774e51834ed7fb5b95f9ef305e0c4924630b857/websockets-17.2-cp314-cp314-win32.whl", hash = "sha256:08d90cf344bdb971ba3a826b78d4da9bfd56cc6a97a604d9b88cbd40bfa6c735", size = 217760, upload-time = "2026-10-03T14:54:54.247Z" }, - { url = "https://files.pythonhosted.org/packages/e5/9e/0523f8bc2f7aaddf39562d4fa01b4d38fa61b23d980917a16d2dd19c8dac/websockets-17.2-cp314-cp314-win_amd64.whl", hash = "sha256:dac93bf7a9beb215be3282b8441173cd50806c41c007b8be9bb24e03c60ad563", size = 218104, upload-time = "2026-10-03T14:54:55.845Z" }, - { url = "https://files.pythonhosted.org/packages/55/17/7b8bb4cb64a199e7082f1f9be784d657842fefc327ac777d6c1493504804/websockets-17.2-cp314-cp314-win_arm64.whl", hash = "sha256:2ab742249f953d148a9ba696c8b9944361e8cb92e8bc61ba2dd53a178403afd3", size = 217989, upload-time = "2026-10-03T14:54:57.376Z" }, - { url = "https://files.pythonhosted.org/packages/ee/76/f54ed054b6e860f1e0bbc7019542a048352d41231fdff6d904b379f881c7/websockets-17.2-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:a69ce25be5f1330ee1c74eb6fabbbceaa96b384beedd2627cecded7546490c40", size = 218125, upload-time = "2026-10-03T14:54:58.943Z" }, - { url = "https://files.pythonhosted.org/packages/e6/4c/0f3375cea66a125ae01d21fb9c537aae955ef499bfe7e2b2376a34362f2a/websockets-17.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:8e24b878cf54843a63985d90480f163ca7f692689fbcbe9cdbd8165521083a8b", size = 215658, upload-time = "2026-10-03T14:55:00.674Z" }, - { url = "https://files.pythonhosted.org/packages/0c/05/7c871a67bfb4b61adc1fe13583db97803f87dfeca644fe6ef51df7bb276d/websockets-17.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f33c7908a6885dcae9f462a4a8347b637053b4ff2b96beb4c23fba1cf7818e5f", size = 215858, upload-time = "2026-10-03T14:55:02.379Z" }, - { url = "https://files.pythonhosted.org/packages/41/8e/59df4d9cd357e902d1c74b13c3c0c3841c8df6e4b1b3d131bf26a23fdcb1/websockets-17.2-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:c796a1bb3e4015249639849f30e8e680df8a431b45d417ba8acf843d2451d95f", size = 225443, upload-time = "2026-10-03T14:55:03.966Z" }, - { url = "https://files.pythonhosted.org/packages/5c/64/5e486a3a44e041203c62eccf1fc89c7f8824e21104a7b82b182e5b21c228/websockets-17.2-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:983bcdc898662f6ba9d6a025c30d29946ff0986d9ad60d400af0da3671f7cbf3", size = 225726, upload-time = "2026-10-03T14:55:05.797Z" }, - { url = "https://files.pythonhosted.org/packages/f0/98/b6eb53121c91fbe8b6897aba06861ce60f9ab58faffc6bca5750cbc21681/websockets-17.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:35e0f088ddfd9d9bc5019e27ff3767411779e92b59db5bb1507f2731a5b61158", size = 226895, upload-time = "2026-10-03T14:55:07.626Z" }, - { url = "https://files.pythonhosted.org/packages/8a/18/8c091321b99c91eb3eaec9acbd940e69308b4e465b5605c430af0cf7d3a5/websockets-17.2-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:19e2511412ad3393191de652513bc7a0ca3c93af143b32d96d46e59fbbddf1d4", size = 229040, upload-time = "2026-10-03T14:55:09.321Z" }, - { url = "https://files.pythonhosted.org/packages/1a/96/3a92f944305b7de42fcb7530b9fa69607b4b4ce993c36a9f2330dbc318ba/websockets-17.2-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cb5e2bf969ac99a6ae3c71208a5eb05cfde973192540ffa6e1068b57fb78c4f8", size = 227469, upload-time = "2026-10-03T14:55:10.935Z" }, - { url = "https://files.pythonhosted.org/packages/ea/a9/624f6d75ba326c22d03698b34c0ada984f1d76196322a62f6c22903b831d/websockets-17.2-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:691780fca2be3dec512cb603cb91060271968cb4af86b51d07c57445c5754a37", size = 226202, upload-time = "2026-10-03T14:55:12.536Z" }, - { url = "https://files.pythonhosted.org/packages/47/af/1e6e8c625aeb268830af2c4227fe05e8db59f4f4debe1dadfd0ada214895/websockets-17.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:2d39c19b1ba6a6791050383fd69efdd3b63533e2254693d0263879cd5f5921ba", size = 223743, upload-time = "2026-10-03T14:55:14.164Z" }, - { url = "https://files.pythonhosted.org/packages/dd/81/33c5280f4f6f81637c93ae065c6a594dfe35935622af135a5f7c3768bf22/websockets-17.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e48ac2b302986c6f55cf61e8e36b4dd97d0132c5078a713a697a940934ba422e", size = 226492, upload-time = "2026-10-03T14:55:15.796Z" }, - { url = "https://files.pythonhosted.org/packages/1d/f3/7aa9fc36e67caccbcfee2c48f4ada41e9da512d41523c024d039f0f22ba3/websockets-17.2-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:e136197f1262620ef2e507afc3ea759c1ae7d221886da20eec5f4c9f2618c2aa", size = 224940, upload-time = "2026-10-03T14:55:17.661Z" }, - { url = "https://files.pythonhosted.org/packages/3f/8c/457aff7081a63d1261608bb4d7b0b0f9dfe780697a2a334671745742850b/websockets-17.2-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:3eb44019a2b0b3b91bac95998f1e4e5589730421170e060fe654a2b7be727dc7", size = 225835, upload-time = "2026-10-03T14:55:19.607Z" }, - { url = "https://files.pythonhosted.org/packages/3e/c3/7a13a3b3050db2c36772ded49f8d48f99eb080948e9f6f762e7529925ab5/websockets-17.2-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:e5855e574804398859c5fbaf4fc7882b96278b7f6572a3d889627e6eb6cfca59", size = 226848, upload-time = "2026-10-03T14:55:21.274Z" }, - { url = "https://files.pythonhosted.org/packages/c4/3e/d5b2c1e473b1031a4a0ec0e10de69df5b981ab4a10aa482bb45c18dd43f5/websockets-17.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:5dc29815520c329f5662f6eb3ebadecf0d4f8c82dfa416d4d6efbf8f39245559", size = 224541, upload-time = "2026-10-03T14:55:22.874Z" }, - { url = "https://files.pythonhosted.org/packages/79/5d/bb81976cc1aa546afb51395ce42913521e9dea062bb34a61308cfff30726/websockets-17.2-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:d1a4f9462da6496b6cb79bbb09c60d17f7e63e8a1df136797b3afabec9560e4d", size = 225315, upload-time = "2026-10-03T14:55:24.443Z" }, - { url = "https://files.pythonhosted.org/packages/f4/6b/314962d5440c61b4c107914599c13ceeecc6bdb6e2e73a5f7e566a7d1f26/websockets-17.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:9496bff5541086478264678bac73c0a75b2fde94fdf6568893bca1f7c6d50d18", size = 225747, upload-time = "2026-10-03T14:55:26.033Z" }, - { url = "https://files.pythonhosted.org/packages/98/fc/9eb64b34a3a4458eb08f3f24bde01508f72a00790330723c158ebb965048/websockets-17.2-cp314-cp314t-win32.whl", hash = "sha256:e1e3bc8090a7eae79fdf634b63bdbfa3c93999991023c37c6fd3b469fc8ff5dc", size = 217891, upload-time = "2026-10-03T14:55:27.681Z" }, - { url = "https://files.pythonhosted.org/packages/ba/ed/3a4e2a09b0822d6e525cbc6e44a4885669bad5b22ab9c64fa2444bc15325/websockets-17.2-cp314-cp314t-win_amd64.whl", hash = "sha256:65a89a5bde227bfe908016f35b5bd347970cd1e5b0360f389502eba1c7fde6e0", size = 218229, upload-time = "2026-10-03T14:55:29.314Z" }, - { url = "https://files.pythonhosted.org/packages/b5/66/cffb75ee746dd060984c3c3e2eac7f875a866225a30dfa53e2cd18232565/websockets-17.2-cp314-cp314t-win_arm64.whl", hash = "sha256:1c27339934109dfaca83f18ab2c23db06714e9d5deca2c8e37e8f492ab90d20b", size = 218146, upload-time = "2026-10-03T14:55:31.001Z" }, - { url = "https://files.pythonhosted.org/packages/12/e9/10a9b1633b63594054c87b97af048628cea2b21b5089a52a9fc1e0af60a3/websockets-17.2-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:a7c4bb26de6ef496d24822aee4f6a305d97cd33d21a2b85f290292d69ba1c25e", size = 217719, upload-time = "2026-10-03T14:55:32.674Z" }, - { url = "https://files.pythonhosted.org/packages/0c/00/ff4020fe0886dac7199a16ce2805c7afd7b981bd2e81d3fa18dff5d9863a/websockets-17.2-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:c08da1f15040bd1e1a6074bd4518a6ef20e67b1594ecfb0aa75e5b45f87e6d6d", size = 215448, upload-time = "2026-10-03T14:55:34.338Z" }, - { url = "https://files.pythonhosted.org/packages/66/06/bc7b944f81514378b2c2ab96c17df19e871cd33b9be0f1f6dfc975457e5e/websockets-17.2-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:3117abfd32b183bdb6194df9317766d32c6517f3d1c0aa8c62d5c6ccfda0b4a8", size = 215674, upload-time = "2026-10-03T14:55:35.918Z" }, - { url = "https://files.pythonhosted.org/packages/a8/da/2b2b76faa2f10c4813e3872c9577fd13a798f5918b1785b86ff7d635eb2a/websockets-17.2-cp315-cp315-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:a046227daa7f191e843d26b911c1146233e9a33d249e0c954dcb3ac7c398710e", size = 225119, upload-time = "2026-10-03T14:55:37.777Z" }, - { url = "https://files.pythonhosted.org/packages/ae/d4/22cbe288c0d5cef7620503be92c0098d82220353fc7e188034a19c517240/websockets-17.2-cp315-cp315-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2901bdf24f20bc884124b3e88c61f7ece260c20c81e610f2196007395264a4aa", size = 225549, upload-time = "2026-10-03T14:55:39.364Z" }, - { url = "https://files.pythonhosted.org/packages/4c/0a/504b0d3063679f2c60430c3539482d42a4cb8bd1a76646baf742030a93cc/websockets-17.2-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f60e39adfecf998488166aca8ff24ab1ac406c9ecbecbcf9b3bcfc43cb1ec9a1", size = 226717, upload-time = "2026-10-03T14:55:40.942Z" }, - { url = "https://files.pythonhosted.org/packages/4e/ea/5da9309cc55c2665a6eebc22c369d9918c0d77258c61e92058e6b08d5ff1/websockets-17.2-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:d4df62fd8448a85c752bbea1803cb3a2785e6fc8352009ab64ad7447af079b3c", size = 228413, upload-time = "2026-10-03T14:55:42.54Z" }, - { url = "https://files.pythonhosted.org/packages/a6/74/5a24df72aa5500f311105687af864c27f1f9da910e968e97818c6149e6b0/websockets-17.2-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c8eea55fdfa9ba65c6981eea38bd20c800bce2f092a2803d82de764ecf0f071a", size = 227196, upload-time = "2026-10-03T14:55:44.251Z" }, - { url = "https://files.pythonhosted.org/packages/5e/ee/ca32cc1ed892dc4ac30a922e8f648048233fbdb8b0bce7048860ec4c60ec/websockets-17.2-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:3f0def1279644acaa9bc861d4234af3f82ea9cee7e460dffac5cb63e691501e9", size = 226092, upload-time = "2026-10-03T14:55:45.842Z" }, - { url = "https://files.pythonhosted.org/packages/7d/0c/12d4a73324aa9798d5165d20c088f9dba66c75c871960e5d921ec66694e4/websockets-17.2-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:fb78fb4158c12f77a934a003006784108a27a6553cfc0c6f10483c9c02e94f48", size = 223486, upload-time = "2026-10-03T14:55:47.45Z" }, - { url = "https://files.pythonhosted.org/packages/bc/a4/7fe15da5abb8f0f61e6a357593f7f2ed55724825b7db0ffe72b5c5fad68d/websockets-17.2-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:f8969ad228115ad8869b5fed801f899e52ab8ad376fdb165ba4760a277c8258a", size = 226200, upload-time = "2026-10-03T14:55:49.126Z" }, - { url = "https://files.pythonhosted.org/packages/08/b9/4cd3a311f96a2eea0ed458bc01fe2cce42f9cd50aa9e64315dfc855d63a9/websockets-17.2-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:4a49ca342efc0800e6ae94ed5c9cbdcb319308f75e73c21181e4c24d6710e8dd", size = 224862, upload-time = "2026-10-03T14:55:50.674Z" }, - { url = "https://files.pythonhosted.org/packages/41/b5/22caa3460f75e42bfcc74028870b556d22847ea9a9034aa03986f07f16a9/websockets-17.2-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:06fa3ce9c3154826c33d4395b225b2994aa64f1f3bcd8be8ed932019175d9268", size = 225391, upload-time = "2026-10-03T14:55:52.393Z" }, - { url = "https://files.pythonhosted.org/packages/95/be/8d28f92092076abf1ddfb3206b0ce956120a22e7c3105f6a3029d727deae/websockets-17.2-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:50644d8715be7e0ec0682f9d7744b63008e199c5e1618a48fa153756a332235f", size = 226545, upload-time = "2026-10-03T14:55:54.127Z" }, - { url = "https://files.pythonhosted.org/packages/cb/7b/ff943fa383e540fe17f066cc10a3eeedef26e50fd45aae2bdc6746d6f95a/websockets-17.2-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:60deca33e584c09e91f70f8b55a0b1de7d671d6a63f051d154920f48bed717c7", size = 224352, upload-time = "2026-10-03T14:55:55.856Z" }, - { url = "https://files.pythonhosted.org/packages/e9/df/1e6c3e06c473c9fd833a5c1620b15e2c3b37647b91b7d41871d20bc098de/websockets-17.2-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:b5f79366a8d8dbb981d53ba800bb54a95454595ab8a4548c2b95501b32a08326", size = 225255, upload-time = "2026-10-03T14:55:57.497Z" }, - { url = "https://files.pythonhosted.org/packages/db/f8/d8a4f988f7cbb568d8bd69da4632c5b6010aa9cd9366f285e23b73b678d9/websockets-17.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:f2bbf3f28d0b63157577c8b774b9136f076afa6797e1a52a2ecd477f23cad3a8", size = 225513, upload-time = "2026-10-03T14:55:59.338Z" }, - { url = "https://files.pythonhosted.org/packages/75/e0/920357165b2797a2530fc9e271d79a9b5fee2b750b154c990c740f767af3/websockets-17.2-cp315-cp315-win32.whl", hash = "sha256:74836317b7010b579522bb52426f1e225608b042c9e78cbe2493522bebb8a318", size = 217722, upload-time = "2026-10-03T14:56:01.307Z" }, - { url = "https://files.pythonhosted.org/packages/5f/eb/25bdca25bbc329ffb330ef33993397d6556a871e40a0d196e757699ea3f7/websockets-17.2-cp315-cp315-win_amd64.whl", hash = "sha256:aaead3d926e9ab4124ada727d20cd62d396649917822df4f771d1f07f1079b40", size = 218017, upload-time = "2026-10-03T14:56:02.914Z" }, - { url = "https://files.pythonhosted.org/packages/fa/cb/ea30a552bbcd1c75f0d14bfce6c884ee36187030b85b74a242aacc02406e/websockets-17.2-cp315-cp315-win_arm64.whl", hash = "sha256:40960554e60eb60c3eec4ff9e42a80f84f8cd3ca9bc80a5481a61f1e64d807c9", size = 217929, upload-time = "2026-10-03T14:56:04.604Z" }, - { url = "https://files.pythonhosted.org/packages/4a/01/477664c619af8aa3c908d482e2a95e13ceed9d78f21d15902013c3bc6c28/websockets-17.2-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:9a2a60a7f0ea5f239efb6391d2b28630a640d82dad63e3bee47cf2c623c4495d", size = 218029, upload-time = "2026-10-03T14:56:06.336Z" }, - { url = "https://files.pythonhosted.org/packages/2a/a9/b0be62ff1c0e2bc966da56b36d3d820c7e2ad3c0c4a4ac414fc7335b214f/websockets-17.2-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:cca2fcb72c007103740fa4fc3df19fdb1a318c641c69f3b0cc47ed63a889336e", size = 215607, upload-time = "2026-10-03T14:56:08.035Z" }, - { url = "https://files.pythonhosted.org/packages/fc/2b/a6738530de0437a31c1b168e4096ecf790aafaf561f33a009886c7d8042e/websockets-17.2-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:b789356bc4e2e6c20ba52817f92c3fed74e24657654237ecd536c54843b80c6c", size = 215817, upload-time = "2026-10-03T14:56:09.852Z" }, - { url = "https://files.pythonhosted.org/packages/c3/c2/2fc44ddc419cbb09ee1708af3e78d8a4b018db01fc7e4f91bd730e2f8d9e/websockets-17.2-cp315-cp315t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:222fb626fa15701a850eccc778be17312142b2f6a0e16aea80770b7459adb784", size = 225979, upload-time = "2026-10-03T14:56:11.85Z" }, - { url = "https://files.pythonhosted.org/packages/2e/91/a215b14caa7ea65bc36db81609108899c259503300d1560dae9c70a135e7/websockets-17.2-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:4497e87c34a2d21cbec1227858fec3af8e514dd70c47625557a122fcebc081dc", size = 226250, upload-time = "2026-10-03T14:56:13.548Z" }, - { url = "https://files.pythonhosted.org/packages/65/b9/9406a18e9edf558ed504d2a7679371d0f8107e4ef526c80b154ea4ec9752/websockets-17.2-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6281c171557ce0e408e19d9a223f22d915117ac38a5a7f32ed83809e7492316c", size = 227579, upload-time = "2026-10-03T14:56:15.143Z" }, - { url = "https://files.pythonhosted.org/packages/fe/45/a73af119244f46f5130005d7ab63f1c75890c890141a0ca2adc9d97d4671/websockets-17.2-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:08d97098644728bd1895caa7ecf3090b8e563d70809870d2adb33a107bd061d0", size = 229205, upload-time = "2026-10-03T14:56:17.086Z" }, - { url = "https://files.pythonhosted.org/packages/c1/92/ccd8e2e921d134a56f1ed4642d276500d9e33b3dc4d6deb63d614b3e53a6/websockets-17.2-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1fdb8d5a1660307dc6d36d0b7fc725213cbd7f80800904dc4896aa3208b89121", size = 228011, upload-time = "2026-10-03T14:56:18.716Z" }, - { url = "https://files.pythonhosted.org/packages/e0/ef/7d71105d19a7aaab5ff87b9c712f6c1dda44e72ea56aa0e7b777f2fc274b/websockets-17.2-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:18b0a46e5e9b315e2b54ce8c3bafdeef0e1388ca363114fa868e6aab2dc58512", size = 226892, upload-time = "2026-10-03T14:56:20.412Z" }, - { url = "https://files.pythonhosted.org/packages/56/f7/87012d628b21e66e699440f39bfa7cc55fae7f52b2c532ab62184a589624/websockets-17.2-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7f115d5d804a2163dd89245710049078b0e726a58c1f44a1f86c2c6e79055d76", size = 224241, upload-time = "2026-10-03T14:56:22.257Z" }, - { url = "https://files.pythonhosted.org/packages/55/f5/495371068b27ee5f7c435187f9dafd62402f195e2c76063bdd4653da1565/websockets-17.2-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:1d829946a2e7630f92f9d7b45b62f3abe9f393cc2dea6a35edb3988f865e75f2", size = 227076, upload-time = "2026-10-03T14:56:23.909Z" }, - { url = "https://files.pythonhosted.org/packages/18/18/3dce3cc6099be5e044e0fd5d0e0c9931c8e3387511cdec8014a345f619e5/websockets-17.2-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:6c274fc1572edf7c197094a0eb1887d45fdc95254bc80597dc7599550486c06a", size = 225727, upload-time = "2026-10-03T14:56:25.689Z" }, - { url = "https://files.pythonhosted.org/packages/47/30/57d0c7aaf8d4473926fa8829b8136483f561388d1e747ae71c9f2a83d5fd/websockets-17.2-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:4173a4b8a025ae44313d9d9b4ecf31e886c7b7faf45386d51a8ca4ff2dcf3f2a", size = 226225, upload-time = "2026-10-03T14:56:27.246Z" }, - { url = "https://files.pythonhosted.org/packages/0c/9f/9dce1203756756c00b407b9a6b13a7500fcd38f2634d4daa3f65575814ec/websockets-17.2-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:d8cfe9522ad69b6abb26b413ed1deca43cb915cefc588433d557cb3ae1c783e2", size = 227333, upload-time = "2026-10-03T14:56:28.811Z" }, - { url = "https://files.pythonhosted.org/packages/9a/2f/d3b6b876678ebb03017b7afd7111fe44d54b93f036a80ebb4b481dd1ab74/websockets-17.2-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:908d81d88bb16141613a6275059b5114656d5c2f0b5400b421d54fe6f1943507", size = 225082, upload-time = "2026-10-03T14:56:30.578Z" }, - { url = "https://files.pythonhosted.org/packages/32/b0/a69b573a5e56d2e7a5dcbb447466f442380cf81515e1cb1220cd626c8042/websockets-17.2-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:c6590e1eb624ff6b15b872421bc9a10bc6d2057635d69c6cd244ac3f928f85c6", size = 225945, upload-time = "2026-10-03T14:56:32.32Z" }, - { url = "https://files.pythonhosted.org/packages/70/be/a72911dc8e33f74c196012366ce4d99b1a803894a377a1ed0c8e66df9caa/websockets-17.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:61040f6f7da5a279d2f77496c69d51132aba75f701c52bded400d4c639277b18", size = 226241, upload-time = "2026-10-03T14:56:34.142Z" }, - { url = "https://files.pythonhosted.org/packages/7d/a9/02a68c1d8e5572918e0962d3aad881078f73ede43abd9b1336e4efaa8909/websockets-17.2-cp315-cp315t-win32.whl", hash = "sha256:f90bad2839c185a1edf8ee22a257cfc8a39e0e337a0490ab185dfa76ef04d1bd", size = 217847, upload-time = "2026-10-03T14:56:36.204Z" }, - { url = "https://files.pythonhosted.org/packages/2b/bf/3d7c33b8d5e7712a60e0149c017ed50394ec5e8cf72e5cb6a1ffaf11a42d/websockets-17.2-cp315-cp315t-win_amd64.whl", hash = "sha256:315551f4ccedbbf9fd4f7e8bf037a5948c976ade0e919ba5d8f581d465f6f725", size = 218169, upload-time = "2026-10-03T14:56:37.79Z" }, - { url = "https://files.pythonhosted.org/packages/27/57/ab34cc6460c5322e6932750fa5c6c64be89e6ee4e2707d13c4e9d3312b25/websockets-17.2-cp315-cp315t-win_arm64.whl", hash = "sha256:0a6220bdf8d5f11af71251a599092d89ac1d6bfac691c7f5951c5b07953947a0", size = 218089, upload-time = "2026-10-03T14:56:39.427Z" }, - { url = "https://files.pythonhosted.org/packages/8a/58/835cd51934d6780fa586f275b5d9901eead6d81569b4343b3767cdbaae4c/websockets-17.2-py3-none-any.whl", hash = "sha256:6aa59f0ef92e796b2db6f5f26550c4713c0e4036899fadf02f55e2ed4db0b7ae", size = 211883, upload-time = "2026-10-03T14:56:51.898Z" }, -] - [[package]] name = "zstandard" version = "0.25.0" From fbb5bc97b7c17d39467e91358838ac3d51743141 Mon Sep 17 00:00:00 2001 From: timohueser Date: Sun, 15 Nov 2026 22:04:53 +0100 Subject: [PATCH 2/6] docs: point Prepare a map at the Device page Co-Authored-By: Claude Opus --- docs/content/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/content/index.md b/docs/content/index.md index 0f718187b9..88e6af26e3 100644 --- a/docs/content/index.md +++ b/docs/content/index.md @@ -12,7 +12,7 @@ offline maps, route navigation, and ride recording. ## Start here - [Try the device](../#demo): explore a ride in the browser demo. -- [Prepare a map](../builder/): choose coverage and download a map. +- [Prepare a map](../plan/#/device): choose coverage and download a map. - [Work on the software](src:README.md): find setup instructions and the source code. ## How the system fits together From 4ec6daf5a33334c8a90fd2827028ce645807ad6d Mon Sep 17 00:00:00 2001 From: timohueser Date: Sun, 15 Nov 2026 22:14:05 +0100 Subject: [PATCH 3/6] web: close the test gaps of the deleted page and remove its dead code The pretend device gives back its map and can hold a put, so the area journey compares the sent map with the pinned map byte for byte, and stops a send while the put runs. A unit test holds that Stop does not abort a send once the device has each byte. The packer cases of the routing-profile test move to obc-bake with their own suite and CI job. MapRun loses the members only the old page read, and the host alias goes. The link check no longer skips links to builder/, and the launch entries of the deleted server go. Co-Authored-By: Claude Opus --- .claude/launch.json | 13 -- .github/workflows/ci.yml | 52 ++++- builder/web/src/lib/coverage/run.svelte.ts | 139 +------------ .../src/lib/device-sync/state.svelte.test.ts | 34 +++- builder/web/src/lib/platform/index.ts | 5 +- .../test-support/device-sync/fake-device.ts | 21 +- .../web/tests/browser/planner/area.test.js | 27 +++ builder/web/tsconfig.json | 6 +- builder/web/vite.config.ts | 3 - docs/build_docs.py | 4 +- docs/testing.md | 2 +- host/obc-bake/tests/test_routing_profiles.py | 185 ++++++++++++++++++ pyproject.toml | 2 + tools/test_plan.py | 1 + tools/testing/suites.toml | 16 +- tools/tests/test_selection_plan.py | 10 +- uv.lock | 6 +- 17 files changed, 354 insertions(+), 172 deletions(-) create mode 100644 host/obc-bake/tests/test_routing_profiles.py diff --git a/.claude/launch.json b/.claude/launch.json index adc89e47dd..48c6c0ebb1 100644 --- a/.claude/launch.json +++ b/.claude/launch.json @@ -1,12 +1,6 @@ { "version": "0.0.1", "configurations": [ - { - "name": "web-builder", - "runtimeExecutable": ".venv/bin/python", - "runtimeArgs": ["-m", "builder.server", "--no-browser", "--port", "8000"], - "port": 8000 - }, { "name": "web-builder-frontend", "runtimeExecutable": "npm", @@ -14,13 +8,6 @@ "cwd": "builder/web", "port": 5173 }, - { - "name": "web-builder-static", - "runtimeExecutable": "npm", - "runtimeArgs": ["run", "dev", "--", "--mode", "web", "--port", "5173"], - "cwd": "builder/web", - "port": 5173 - }, { "name": "data-page", "runtimeExecutable": "tools/obc", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index db20a65bf0..c269c0fbcf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -415,6 +415,56 @@ jobs: path: ${{ runner.temp }}/ui-snapshots/*.png if-no-files-found: ignore + # Routing-profile round-trips through the obc-pack binary. These pack the tiny corpus with custom + # profiles and byte-compare the §8.6 profile table against independently quantized expectations, + # so they pin the packer's writer against the spec rather than against itself. The preflight is + # what stops a missing binary or corpus from turning the suite into a silent skip. + packer-python: + needs: selection + if: contains(fromJSON(needs.selection.outputs.jobs), 'packer-python') + runs-on: ubuntu-24.04 + 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: . + shared-key: host-tests + save-if: false + - uses: ./.github/actions/setup-host-deps + - uses: actions/setup-python@v5 + with: + python-version-file: .python-version + - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + with: + version: *python-uv-version + - name: Prepare the packer profile tests + run: | + uv sync --locked --group packer-test + cargo build -p obc-bake --bin obc-pack --release --locked + - name: Packer binary and corpus are present + run: | + test -x target/release/obc-pack + test -f builder/tests/corpus/data/tiny.osm.pbf + - name: Packer profile tests (pytest) + id: python-packer + run: | + mkdir -p .artifacts/python + rm -f .artifacts/python/packer.xml + uv run --locked --group packer-test python -m pytest host/obc-bake/tests/test_routing_profiles.py -v --junitxml=.artifacts/python/packer.xml + - name: Upload packer Python test results + if: ${{ !cancelled() && (steps.python-packer.outcome == 'success' || steps.python-packer.outcome == 'failure') }} + uses: actions/upload-artifact@v4 + with: + name: python-packer-${{ github.run_attempt }} + path: .artifacts/python/packer.xml + if-no-files-found: error + embedded: needs: selection if: contains(fromJSON(needs.selection.outputs.jobs), 'embedded') @@ -1161,7 +1211,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, embedded, boot, device, deny, wasm, wasm-bridges, docs, ios-unit, ios-app, ios-release, web, web-browser, verification, planner-search] + needs: [selection, guards, cairn, fmt, clippy, test, ui-snapshots, packer-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/builder/web/src/lib/coverage/run.svelte.ts b/builder/web/src/lib/coverage/run.svelte.ts index 915c43dd63..3c57869a72 100644 --- a/builder/web/src/lib/coverage/run.svelte.ts +++ b/builder/web/src/lib/coverage/run.svelte.ts @@ -9,8 +9,6 @@ import { isWorkerResponse, requestTransferList, type AssembleWorkerRequest, - type CellReadMode, - type MapWriteMode, type WorkerCell, type WorkerSourceCell, type WorkerTerrainCell, @@ -38,7 +36,6 @@ import { downloadCells, planCells, type CellDownloadPlan, - type CellDownloadProgress, } from "../catalog/download"; import type { CoverageStore } from "./store.svelte"; import type { JobContext } from "../device/progress"; @@ -158,9 +155,6 @@ export class MapRun { 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 one delivery, so `done` can wait for a send that is still running rather @@ -169,33 +163,23 @@ export class MapRun { /** 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 + /** The bytes of the 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); + #cachedBytes = 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"); + #runFileName = "OBC map.obcm"; #output = $state.raw(null); #nextRunId = 0; #activeRunId = 0; #failure: Promise = Promise.resolve(); - #paused = $state(false); #estimate = $state(null); #estimateLedger = $state.raw(null); @@ -203,9 +187,8 @@ export class MapRun { #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. */ + * request. */ #estimateError = $state(null); - #estimateNonce = $state(0); readonly #disposeEstimate: () => void; constructor(store: CoverageStore) { @@ -215,24 +198,7 @@ export class MapRun { }); } - 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 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 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; } @@ -320,14 +286,6 @@ export class MapRun { 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 @@ -358,7 +316,6 @@ export class MapRun { 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: @@ -482,10 +439,7 @@ export class MapRun { try { await discardCellStore(revision); } catch { - this.#runWarnings = [ - ...this.#runWarnings, - "Temporary map cells could not be deleted; use ‘Delete stored map data’.", - ]; + // The next run clears the working files when it starts. } } @@ -493,22 +447,8 @@ export class MapRun { 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. + // The next run clears the working files when it starts. } - if (!checked && !this.#running) await this.clearStoredCells(true); } async #initializeStorage() { @@ -526,24 +466,6 @@ export class MapRun { } } - 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); @@ -584,7 +506,6 @@ export class MapRun { 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; @@ -670,15 +591,8 @@ export class MapRun { this.#activeRunId = runId; this.#output = out; this.#runFileName = this.#mapFileName(); - this.#errorMessage = null; 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"; out.ctx.phase("downloading", l.totalBytes); @@ -730,7 +644,6 @@ export class MapRun { 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 @@ -741,7 +654,6 @@ export class MapRun { 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 @@ -787,7 +699,6 @@ export class MapRun { } }, onProgress: (p) => { - this.#dlProgress = p; out.ctx.progress(p.receivedBytes, p.totalBytes); }, signal: runAbort.signal, @@ -815,7 +726,6 @@ export class MapRun { this.#phase = "assembling"; out.ctx.phase("assembling", 0); - this.#asmPhase = "open"; this.#asmPhaseStart = { open: performance.now() }; const req: AssembleWorkerRequest = { type: "assemble", @@ -893,38 +803,14 @@ export class MapRun { }); }); - readonly #refreshBlocked = $derived(this.#output !== null || 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 { - // Assembly and PUT are one DeviceJob. Ask its controller to cancel: merely aborting the - // cell downloader would let a live PUT commit and only then paint the run as cancelled. - this.#output?.ctx.cancel(new DOMException("cancelled", "AbortError")); - } - - 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) { + if (!l || !l.isFinal || l.cellCount === 0 || !idle || this.#clearingCells) { // 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. @@ -997,16 +883,6 @@ export class MapRun { ); }); - 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", ); @@ -1023,7 +899,6 @@ export class MapRun { l.cellCount > 0 && this.#refusal === null && !this.#running && - !this.#paused && !this.#clearingCells && this.#estimate !== null && this.#estimateLedger === l && diff --git a/builder/web/src/lib/device-sync/state.svelte.test.ts b/builder/web/src/lib/device-sync/state.svelte.test.ts index 2ea80582b1..6fcfa1af5d 100644 --- a/builder/web/src/lib/device-sync/state.svelte.test.ts +++ b/builder/web/src/lib/device-sync/state.svelte.test.ts @@ -8,9 +8,11 @@ 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'; +import { sendMap, syncDevice, type SyncReport } from './sync'; -vi.mock('./sync', () => ({ syncDevice: vi.fn() })); +vi.mock('./sync', () => ({ syncDevice: vi.fn(), sendMap: vi.fn() })); +vi.mock('../core/bridge', () => ({ initCore: vi.fn(async () => {}) })); +vi.mock('./map.svelte', () => ({ buildMap: vi.fn() })); const SERIAL = '9F3A00C1E2B47D10'; const session = (status: DeviceSession['status']) => @@ -73,4 +75,32 @@ describe('startDeviceSync', () => { deviceHolder.session = null; remembered.device = null; }); + + it('does not stop a map send once the device has each byte', async () => { + vi.spyOn(deviceHolder, 'open').mockResolvedValue(null); + vi.mocked(syncDevice).mockResolvedValue(report([])); + rememberCard(SERIAL, '8f2c41d96b074ea3b1559c207de83466'); + let signal: AbortSignal | undefined; + vi.mocked(sendMap).mockImplementation(async (_serial, _library, _build, ctx) => { + signal = ctx.signal; + // The device stores the map, then the host cleans up: Stop is too late for both. + for (const phase of ['committing', 'finalizing'] as const) { + ctx.phase(phase); + deviceSync.stop(); + } + return null; + }); + deviceHolder.session = session('ready'); + const stop = startDeviceSync(new Library(new IDBFactory())); + flushSync(); + await vi.waitFor(() => expect(deviceSync.running).toBe(false)); + deviceSync.sendMap(); + await vi.waitFor(() => expect(signal).toBeDefined()); + await settle(); + expect(signal!.aborted).toBe(false); + expect([deviceSync.map, deviceSync.mapProblem]).toEqual([null, null]); + stop(); + deviceHolder.session = null; + remembered.device = null; + }); }); diff --git a/builder/web/src/lib/platform/index.ts b/builder/web/src/lib/platform/index.ts index 7846e52d13..8d0ee21a6f 100644 --- a/builder/web/src/lib/platform/index.ts +++ b/builder/web/src/lib/platform/index.ts @@ -1,5 +1,4 @@ -// The one place the app reaches its host. `$host` is a Vite alias (see vite.config.ts) that -// names the web host, `web.ts`, in every mode. +// The one place the app reaches its host, the web host. -export { platform } from "$host"; +export { platform } from "./web"; export * from "./types"; diff --git a/builder/web/test-support/device-sync/fake-device.ts b/builder/web/test-support/device-sync/fake-device.ts index e6e901eb8b..df2161b1e9 100644 --- a/builder/web/test-support/device-sync/fake-device.ts +++ b/builder/web/test-support/device-sync/fake-device.ts @@ -1,7 +1,7 @@ /** * A device on a pretend cable: `planner.html?fake-device`, on the dev server and in the build of the browser tests. The wasm * test device of the sync tests holds a map, a route and two rides of today. The chooser of the Connect button plugs it in. - * `window.deviceTest`: `plug(unformatted)` and `unplug()` move the cable, `hold()` stops each sync at its start until `release()`, and + * `window.deviceTest`: `plug(unformatted)` and `unplug()` move the cable, `hold()` stops each sync at its start and `holdPut()` each put before its first byte, until `release()`; `map()` gives the map on the card; and * `offer(version)` publishes a pretend software version. The card is the same at each page load. `plug(true)` puts a second * device with the same serial on the cable, whose card has no format. A format restarts the device, as the real one does. */ @@ -11,6 +11,7 @@ import { firmwareCheck } from '../../src/lib/firmware/check.svelte'; import { flatDevice, initFlatDevice } from '../../src/lib/usb/flat-device'; import { encodeRideObject, type RideObject } from '../../src/lib/usb/objects'; import { ObjectKind } from '../../src/lib/usb/protocol'; +import { bytesSource } from '../../src/lib/usb/source'; import type { DeviceState, DeviceWatcher } from '../../src/lib/usb/session'; import { WatchedDeviceSession } from '../../src/lib/usb/session.svelte'; @@ -61,7 +62,21 @@ export async function fakeDevice(): Promise { const list = rig.client.list.bind(rig.client); rig.client.list = async (...args) => { await gate; return list(...args); }; const hold = () => { gate = new Promise(resolve => open = resolve); }; - const release = () => open(); + // A held put has started on the wire: the device has its header and waits for the first byte. + let putGate: Promise = Promise.resolve(), openPut = () => {}; + const put = rig.client.put.bind(rig.client); + rig.client.put = (target, source, options) => { + const src = source instanceof Uint8Array ? bytesSource(source) : source, wait = putGate; + return put(target, { ...src, async *chunks(size) { await wait; yield* src.chunks(size); } }, options); + }; + const holdPut = () => { putGate = new Promise(resolve => openPut = resolve); }; + const release = () => { open(); openPut(); }; + /** The payload of the map that the device selects, as numbers. */ + const map = () => { + const shards = rig.device.entries.filter(entry => entry.kind === ObjectKind.MapShard); + const selected = shards.reduce((best, entry) => entry.objectId < best.objectId ? entry : best); + return Array.from(rig.device.payloadOf(selected.objectId) ?? []); + }; const offer = (version: string) => { firmwareCheck.release = { version, bytes: 1, sha256: '', url: 'https://updates.test/UPDATE.BIN' }; }; const watcher: DeviceWatcher = { get current() { return state; }, @@ -74,5 +89,5 @@ export async function fakeDevice(): Promise { // `open()` then gives this session, and never a WebUSB one. Object.assign(deviceHolder, { session, opening: Promise.resolve(session) }); // `route`: the `device` of a `sent` entry for the route on the card. - Object.assign(window, { deviceTest: { plug, unplug, hold, release, offer, route: `${STORE}:${route.objectId}` } }); + Object.assign(window, { deviceTest: { plug, unplug, hold, holdPut, release, map, offer, route: `${STORE}:${route.objectId}` } }); } diff --git a/builder/web/tests/browser/planner/area.test.js b/builder/web/tests/browser/planner/area.test.js index 94fe894941..01f28ff4eb 100644 --- a/builder/web/tests/browser/planner/area.test.js +++ b/builder/web/tests/browser/planner/area.test.js @@ -1,5 +1,7 @@ import { expect, test } from '@playwright/test'; import { spawn } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { HOSTS, respond } from './stubs.js'; @@ -7,6 +9,9 @@ import { HOSTS, respond } from './stubs.js'; const REPO = join(dirname(fileURLToPath(import.meta.url)), '../../../../..'); const PLANNER_CATALOG = 'https://maps.openbikecomputer.com/planner/catalog.json'; const CORS = { 'access-control-allow-origin': '*' }; +/** The map that `obcm-assemble` writes from the cells of the fixture catalog. */ +const PINNED_MAP = join(REPO, 'builder/wasm/tests/fixture/expected/map.obcm'); +const sha256 = bytes => createHash('sha256').update(bytes).digest('hex'); // The fixture catalog of the builder journey: one region, "Bridge Fixture", of two detail cells side by side. let server, origin; @@ -200,6 +205,28 @@ test('"Send the map" builds the map that waits and puts it on the device; Stop i await expect(row).not.toContainText('New area'); await expect(row.getByRole('button')).toHaveCount(0); await expect(row.getByRole('link', { name: 'Change the area of the map' })).toBeVisible(); + // The card holds the map that `obcm-assemble` wrote from the same cells, byte for byte. + const sent = Buffer.from(await page.evaluate(() => window.deviceTest.map())); + expect(sha256(sent)).toBe(sha256(await readFile(PINNED_MAP))); expect(errors).toEqual([]); expect(await nextMap(page)).toBeNull(); }); + +test('Stop while the map goes to the device keeps the map of the card, and the new map waits', async ({ page }) => { + await library(page, () => window.coverTest.library.setState('nextMap', { regions: ['bridge-fixture'], boxes: [], light: 'default', dark: 'dusk', bytes: 16_000 })); + const errors = await open(page, '?fake-device#/device'); + await page.getByRole('button', { name: 'Connect a device' }).click(); + const row = page.locator('.row', { has: page.getByText('Map', { exact: true }) }); + await expect(page.locator('.row', { hasText: 'In sync.' })).toBeVisible(); + const before = await page.evaluate(() => window.deviceTest.map()); + + await page.evaluate(() => window.deviceTest.holdPut()); + await row.getByRole('button', { name: 'Send the map' }).click(); + await expect(row).toContainText(/Send \d+ %/); + await row.getByRole('button', { name: 'Stop' }).click(); + await page.evaluate(() => window.deviceTest.release()); + await expect(row).toContainText('The new map was not sent. “Send the map” starts again.'); + await expect(row).toContainText('New area · 15.6 KB'); + expect(await page.evaluate(() => window.deviceTest.map())).toEqual(before); + expect(errors).toEqual([]); +}); diff --git a/builder/web/tsconfig.json b/builder/web/tsconfig.json index 8a7acb5079..862450b696 100644 --- a/builder/web/tsconfig.json +++ b/builder/web/tsconfig.json @@ -12,11 +12,7 @@ "types": ["vite/client", "node", "@webgpu/types"], "strict": true, "noUnusedLocals": true, - "noUnusedParameters": true, - // The platform alias of vite.config.ts, which names the web host in every mode. - "paths": { - "$host": ["./src/lib/platform/web.ts"] - } + "noUnusedParameters": true }, // `test-support/` holds what the suites need and the app must not have: the loader for the wasm // test device, and the device smoke's phases. It is checked to the same bar; its generated diff --git a/builder/web/vite.config.ts b/builder/web/vite.config.ts index ba88a4dbc8..5907d0b504 100644 --- a/builder/web/vite.config.ts +++ b/builder/web/vite.config.ts @@ -34,9 +34,6 @@ export default defineConfig(({ mode }) => { // Always a string, so a build without it drops the pretend device of `planner.ts` with its wasm. define: { "import.meta.env.VITE_FAKE_DEVICE": JSON.stringify(process.env.VITE_FAKE_DEVICE ?? "") }, resolve: { - // Root-relative rather than an absolute path so the config needs no - // node: builtins (and so no @types/node just to type-check itself). - alias: { $host: "/src/lib/platform/web.ts" }, // Component tests run through Vitest's SSR transform even when their // per-file environment supplies a DOM. Select Svelte's client runtime // there so mounted tests exercise the real browser lifecycle. diff --git a/docs/build_docs.py b/docs/build_docs.py index 7988d64ffa..1ac132d056 100644 --- a/docs/build_docs.py +++ b/docs/build_docs.py @@ -816,9 +816,9 @@ def check_links(rendered): continue path, _, frag = href.partition("#") target = urljoin(url, path).lstrip("/") if path else url - # The map builder is a sibling *app* in the published artifact, not a page + # The web app is a sibling *app* in the published artifact, not a page # this renderer produces — there is no HTML here to validate it against. - if target.startswith(("builder/", "plan/")): + if target.startswith("plan/"): continue label = "/" + url if not frag and target.startswith("docs/") and (OUT / target[5:]).is_file(): diff --git a/docs/testing.md b/docs/testing.md index 2886447e8b..900495ced3 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -103,7 +103,7 @@ and a missing expected file fails the upload. Download with | Artifact | Holds | | --- | --- | | `rust-test-ATTEMPT`, `rust-fixtures-ATTEMPT` | nextest JUnit XML for the fast and fixture tiers; the fast artifact also holds `doctests.log` and `formats-default.log` | -| `python-repository-tools-ATTEMPT`, `python-firmware-tools-ATTEMPT` | unittest and pytest XML | +| `python-repository-tools-ATTEMPT`, `python-firmware-tools-ATTEMPT`, `python-packer-ATTEMPT` | unittest and pytest XML | | `web-builder-ATTEMPT` | Vitest JUnit XML | | `web-builder-browser-ATTEMPT`, `web-demo-browser-ATTEMPT` | the Chromium journeys of the web app and of the landing page, with a screenshot and trace on failure | | `ios-tests-coverage-ATTEMPT`, `ios-screenshots-ATTEMPT`, `ios-application-ATTEMPT` | `.xcresult` bundles; restore the suffix and open in Xcode | diff --git a/host/obc-bake/tests/test_routing_profiles.py b/host/obc-bake/tests/test_routing_profiles.py new file mode 100644 index 0000000000..91d116a762 --- /dev/null +++ b/host/obc-bake/tests/test_routing_profiles.py @@ -0,0 +1,185 @@ +"""Routing profiles through the real `obc-pack` binary. + +A config carrying custom ``routing.profiles`` is packed over the tiny corpus fixture, and the +§8.6 profile-table bytes of the map are compared with expectations that this file quantizes +itself from the spec. A sub-1.0 multiplier and any profile set but the four bike types must fail +the pack with the packer's own error. + +Run from the repo root, after ``cargo build -p obc-bake --bin obc-pack --release``:: + + uv run --locked --group packer-test python -m pytest host/obc-bake/tests/test_routing_profiles.py +""" +import json +import os +import re +import struct +import subprocess + +import pytest + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) +TINY_PBF = os.path.join(REPO_ROOT, "builder", "tests", "corpus", "data", "tiny.osm.pbf") +SCHEMA_PRESET = os.path.join(REPO_ROOT, "builder", "presets", "schema.json") + +# Canonical class order; must match obc-map-core/src/nav.rs and the OBCM spec. +HIGHWAY_CLASSES = [ + "cycleway", "path", "track", "footway", "steps", "bridleway", "living_street", + "residential", "service", "unclassified", "tertiary", "secondary", "primary", "trunk_cycl", +] +SURFACE_CLASSES = ["unknown", "paved", "compacted", "gravel", "dirt", "rough", "cobbles", "grass"] +NAME_LEN = 12 +PROFILE_RECORD_LEN = 56 # 12 name + 32 highway + 8 surface + climb_weight + 3 reserved (v12) +CLIMB_WEIGHT_OFF = 52 +# The one OBCM version literal in the tree is the format crate's constant. +OBCM_VERSION = int(re.search(r"pub const VERSION: u8 = (\d+);", + open(os.path.join(REPO_ROOT, "firmware/obc-formats/src/obcm.rs")).read())[1]) + +def _pack_bin(): + override = os.environ.get("OBC_PACK_BIN") + if override and os.path.exists(override): + return override + for profile in ("release", "debug"): + p = os.path.join(REPO_ROOT, "target", profile, "obc-pack") + if os.path.exists(p) and os.access(p, os.X_OK): + return p + return None + +requires_pack = pytest.mark.skipif( + _pack_bin() is None or not os.path.exists(TINY_PBF), + reason="obc-pack binary or tiny corpus fixture not built", +) + +def _quantize(v): + """Mirror obc-pack's quantize_multiplier: forbidden -> 0, else round(v*16) clamped 16..255.""" + if v == "forbidden": + return 0 + q = round(v * 16) + return max(16, min(255, q)) + +def _expected_record(profile): + """Build the 56-byte v12 §8.6 record we expect the packer to write for a profile.""" + default_q = _quantize(profile.get("default", 2.0)) + highway = [default_q] * 32 + surface = [default_q] * 8 + for cls, val in profile.get("highway", {}).items(): + highway[HIGHWAY_CLASSES.index(cls)] = _quantize(val) + for cls, val in profile.get("surface", {}).items(): + surface[SURFACE_CLASSES.index(cls)] = _quantize(val) + name = profile["name"].encode("utf-8") + assert len(name) <= NAME_LEN + name_field = name + b"\xff" * (NAME_LEN - len(name)) + # The climb weight (absent in a config means climb-blind) and three reserved ZERO bytes. + # Zero, not 0xFF: the name field is a padded string, this is a reserved field. + climb = bytes([int(profile.get("climb_weight", 0))]) + b"\x00" * 3 + return name_field + bytes(highway) + bytes(surface) + climb + +def _pack(tmp_path, profiles, min_component_edges=None): + """Pack the tiny corpus with the given routing.profiles; return the .obcm bytes.""" + cfg = json.load(open(SCHEMA_PRESET)) + cfg.pop("_meta", None) + routing = {"profiles": profiles} + if min_component_edges is not None: + routing["min_component_edges"] = min_component_edges + cfg["routing"] = routing + cfg_path = tmp_path / "config.json" + cfg_path.write_text(json.dumps(cfg)) + out_path = tmp_path / "out.obcm" + # --no-land avoids the network land-polygon dataset; the profile table is + # written regardless of graph contents. + proc = subprocess.run( + [_pack_bin(), TINY_PBF, str(cfg_path), str(out_path), "--no-land"], + capture_output=True, text=True, + ) + assert proc.returncode == 0, f"obc-pack failed: {proc.stdout}\n{proc.stderr}" + return out_path.read_bytes() + +def _profile_table(data): + """Locate and slice the §8.6 profile table out of a packed .obcm.""" + assert data[:4] == b"OBCM", "bad magic" + assert data[4] == OBCM_VERSION, f"expected OBCM v{OBCM_VERSION}, got v{data[4]}" + # Every offset that addresses the *file* counts 2^scale-byte units, not bytes. + # Arithmetic *inside* a structure (the `nav_off + 22` below) stays in bytes. + scale = data[40] # header: Offset Scale @ 40 (u8) + assert 0 <= scale <= 9, f"§1.1 restricts Offset Scale to 0..=9, got {scale}" + unit = 1 << scale + (nav_off,) = struct.unpack_from(" 64 + "highway": {"cycleway": 1.0, "track": 7.0, "steps": "forbidden", "primary": 2.5}, + "surface": {"paved": 1.0, "gravel": 5.0, "rough": "forbidden"}, + "climb_weight": 12, # v12 §8.6: flat metres charged per metre of ascent +} +MINIMAL = {"name": "Gravel", "default": 2.0} + +def _four(road, gravel=None): + """The four bike types in their fixed order, with the given Road and Gravel entries.""" + return [road, gravel or {"name": "Gravel"}, {"name": "MTB"}, {"name": "Touring"}] + +@requires_pack +def test_custom_profiles_round_trip_to_112_bytes(tmp_path): + """A config with custom weights packs to §8.6 records that match byte-for-byte.""" + data = _pack(tmp_path, _four(CUSTOM, MINIMAL)) + count, table = _profile_table(data) + assert count == 4 + rec0 = table[:PROFILE_RECORD_LEN] + rec1 = table[PROFILE_RECORD_LEN:2 * PROFILE_RECORD_LEN] + assert rec0 == _expected_record(CUSTOM) + assert rec1 == _expected_record(MINIMAL) + # Spot-check the load-bearing cells directly against the spec's encoding. + assert rec0[NAME_LEN + HIGHWAY_CLASSES.index("cycleway")] == 16 # 1.0x + assert rec0[NAME_LEN + HIGHWAY_CLASSES.index("steps")] == 0 # forbidden + assert rec0[NAME_LEN + HIGHWAY_CLASSES.index("footway")] == 64 # inherits default 4.0x + assert rec0[NAME_LEN + 32 + SURFACE_CLASSES.index("rough")] == 0 # forbidden + assert rec0[CLIMB_WEIGHT_OFF] == 12 # v12: taken verbatim, no admissibility floor + assert rec1[CLIMB_WEIGHT_OFF] == 0 # …and absent means climb-blind + assert rec0[CLIMB_WEIGHT_OFF + 1:] == b"\x00" * 3, "the reserved tail is zero" + +@requires_pack +def test_forbidden_primary_is_quantized_to_zero(tmp_path): + """The acceptance-criterion shape: switching a class to forbidden zeroes its wire byte.""" + profile = {"name": "Road", "default": 2.0, "highway": {"primary": "forbidden"}} + data = _pack(tmp_path, _four(profile)) + _count, table = _profile_table(data) + assert table[NAME_LEN + HIGHWAY_CLASSES.index("primary")] == 0 + +@requires_pack +def test_anything_but_the_four_bike_types_is_rejected(tmp_path): + """The count, the order and the names of the profiles are fixed (OBCM §8.6).""" + cfg = json.load(open(SCHEMA_PRESET)) + cfg.pop("_meta", None) + for profiles in ([CUSTOM], _four(CUSTOM)[::-1], _four({"name": "Racer"})): + cfg["routing"] = {"profiles": profiles} + cfg_path = tmp_path / "config.json" + cfg_path.write_text(json.dumps(cfg)) + proc = subprocess.run( + [_pack_bin(), TINY_PBF, str(cfg_path), str(tmp_path / "out.obcm"), "--no-land"], + capture_output=True, text=True, + ) + assert proc.returncode != 0, f"{[p['name'] for p in profiles]} must fail the pack" + assert "four bike types" in proc.stdout + proc.stderr + +@requires_pack +def test_sub_one_multiplier_is_rejected_with_admissibility_error(tmp_path): + """A multiplier below 1.0 must be rejected by the packer with the admissibility error.""" + cfg = json.load(open(SCHEMA_PRESET)) + cfg.pop("_meta", None) + cfg["routing"] = {"profiles": _four({"name": "Road", "highway": {"cycleway": 0.5}})} + cfg_path = tmp_path / "config.json" + cfg_path.write_text(json.dumps(cfg)) + proc = subprocess.run( + [_pack_bin(), TINY_PBF, str(cfg_path), str(tmp_path / "out.obcm"), "--no-land"], + capture_output=True, text=True, + ) + assert proc.returncode != 0, "a sub-1.0 multiplier must fail the pack" + msg = proc.stdout + proc.stderr + assert "below 1.0" in msg + assert "admissible" in msg diff --git a/pyproject.toml b/pyproject.toml index 60af9fb212..5b55664031 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,6 +26,8 @@ trailview-sky = [{ include-group = "planner-maps" }, "numpy==2.5.3", "openexr==3 planner-search = ["orjson==3.12.0", "pyyaml==6.0.2", "shapely==2.1.2", "zstandard==0.25.0"] dev = ["unittest-xml-reporting==4.0.0", "PyYAML==6.0.2"] +# The routing-profile test of `obc-pack` (host/obc-bake/tests/test_routing_profiles.py). +packer-test = ["pytest>=8.0.0"] search-runtime = [ "orjson==3.12.0", "shapely==2.1.2", diff --git a/tools/test_plan.py b/tools/test_plan.py index 6ef7add147..c2dfe26d47 100644 --- a/tools/test_plan.py +++ b/tools/test_plan.py @@ -54,6 +54,7 @@ class Job: "clippy": Job(needs=("selection",), roots=(ROOT_WORKSPACE,)), "test": Job(needs=("selection",), roots=(ROOT_WORKSPACE,), script="tools/ci/test.sh"), "ui-snapshots": Job(needs=("selection",), packages=("obc-sim",)), + "packer-python": Job(needs=("selection",), packages=("obc-bake", "obc-pack")), "embedded": Job(needs=("selection",), roots=("firmware/obc-fw-nrf54l", "firmware/obc-sensor-sim")), "boot": Job(needs=("selection",), roots=("firmware/obc-boot",)), "device": Job(needs=("selection",), packages=("obc-app", "obc-link")), diff --git a/tools/testing/suites.toml b/tools/testing/suites.toml index 9daf188ea8..4128396ce4 100644 --- a/tools/testing/suites.toml +++ b/tools/testing/suites.toml @@ -407,6 +407,20 @@ triggers = ["tools/trailview/**", "data/trailview/**", "fixtures/sources/trailvi "tools/step_pool.py", "tools/step_request.py", "tools/data_registry.py", "tools/planner_runtime.py", "data/sources.toml", "builder/web/src/lib/trailview/models/trees/**", "builder/web/src/lib/trailview/models/plants/**", "pyproject.toml", "uv.lock"] +[[suite]] +id = "python.packer-profiles" +route = "ordinary" +command = "rm -f .artifacts/python/packer.xml && uv run --locked --group packer-test python -m pytest host/obc-bake/tests/test_routing_profiles.py -v --junitxml=.artifacts/python/packer.xml" +jobs = ["packer-python"] +fixtures = ["builder-corpus"] +triggers = [ + "host/obc-bake/tests/test_routing_profiles.py", + "builder/tests/corpus/**", + "builder/presets/**", + "host/obc-map-core/schema/config.schema.json", + "pyproject.toml", "uv.lock", +] + [[suite]] id = "ios.replay-camera" scoped = true @@ -499,7 +513,7 @@ triggers = ["Cargo.toml", "Cargo.lock", "rust-toolchain.toml"] id = "ci.rust-builds" route = "ordinary" command = "obc check device board wasm" -jobs = ["boot", "device", "embedded", "ui-snapshots", "wasm"] +jobs = ["boot", "device", "embedded", "packer-python", "ui-snapshots", "wasm"] foundation = true triggers = ["Cargo.toml", "Cargo.lock", "rust-toolchain.toml", "tools/install-riscv.sh"] diff --git a/tools/tests/test_selection_plan.py b/tools/tests/test_selection_plan.py index 9a88c42743..507a1eee60 100644 --- a/tools/tests/test_selection_plan.py +++ b/tools/tests/test_selection_plan.py @@ -452,8 +452,8 @@ def test_every_package_reaches_the_jobs_that_compile_it(self) -> None: "obc-boot": ["boot", "fmt"], "obc-builder-bridge": ["clippy", "fmt", "test", "wasm-bridges"], "obc-web-demo": ["clippy", "fmt", "test", "wasm"], - "obc-pack": ["clippy", "fmt", "test"], - "obc-bake": ["clippy", "fmt", "test"], + "obc-pack": ["clippy", "fmt", "packer-python", "test"], + "obc-bake": ["clippy", "fmt", "packer-python", "test"], "obc-sim": ["clippy", "fmt", "test", "ui-snapshots"], "obc-app": ["clippy", "device", "fmt", "test"], } @@ -475,7 +475,7 @@ def test_selected_job_set_per_change_class(self) -> None: ( "foundational Rust crate", ["firmware/obc-crc/src/lib.rs"], - ["boot", "cairn", "clippy", "device", "embedded", "fmt", "ios-app", "ios-release", "ios-unit", "test", "ui-snapshots", "wasm", "wasm-bridges"], + ["boot", "cairn", "clippy", "device", "embedded", "fmt", "ios-app", "ios-release", "ios-unit", "packer-python", "test", "ui-snapshots", "wasm", "wasm-bridges"], ), ( "shared vectors", @@ -491,12 +491,12 @@ def test_selected_job_set_per_change_class(self) -> None: ( "workflow", [".github/workflows/ci.yml"], - ["boot", "cairn", "clippy", "deny", "device", "docs", "embedded", "fmt", "ios-app", "ios-release", "ios-unit", "planner-search", "test", "ui-snapshots", "verification", "wasm", "wasm-bridges", "web", "web-browser"], + ["boot", "cairn", "clippy", "deny", "device", "docs", "embedded", "fmt", "ios-app", "ios-release", "ios-unit", "packer-python", "planner-search", "test", "ui-snapshots", "verification", "wasm", "wasm-bridges", "web", "web-browser"], ), ( "nextest configuration", [".config/nextest.toml"], - ["boot", "cairn", "clippy", "deny", "device", "docs", "embedded", "fmt", "planner-search", "test", "ui-snapshots", "verification", "wasm", "wasm-bridges", "web", "web-browser"], + ["boot", "cairn", "clippy", "deny", "device", "docs", "embedded", "fmt", "packer-python", "planner-search", "test", "ui-snapshots", "verification", "wasm", "wasm-bridges", "web", "web-browser"], ), ("web demo crate", ["sim/web-demo/src/lib.rs"], ["cairn", "clippy", "fmt", "test", "wasm"]), ("web demo Trunk target", ["docs/index.html"], ["docs", "wasm", "wasm-bridges"]), diff --git a/uv.lock b/uv.lock index 6860cae298..c7e66a2251 100644 --- a/uv.lock +++ b/uv.lock @@ -999,6 +999,9 @@ forest-reference = [ { name = "pillow" }, { name = "pmtiles" }, ] +packer-test = [ + { name = "pytest" }, +] planner-climate = [ { name = "h5py" }, { name = "numcodecs" }, @@ -1126,6 +1129,7 @@ forest-reference = [ { name = "pillow", specifier = "==12.3.0" }, { name = "pmtiles", specifier = "==3.8.1" }, ] +packer-test = [{ name = "pytest", specifier = ">=8.0.0" }] planner-climate = [ { name = "h5py", specifier = "==3.16.0" }, { name = "numcodecs", specifier = "==0.17.0" }, @@ -1551,7 +1555,7 @@ name = "pytest" version = "9.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-runtime') or (extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-test') or (extra == 'group-22-openbikecomputer-tools-dev' and extra == 'group-22-openbikecomputer-tools-search-training') or (extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-runtime') or (extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-test') or (extra == 'group-22-openbikecomputer-tools-planner-search' and extra == 'group-22-openbikecomputer-tools-search-training')" }, { name = "iniconfig" }, { name = "packaging" }, { name = "pluggy" }, From 020d7d428c5d39ac06d0b0ade4e6b1069784ebef Mon Sep 17 00:00:00 2001 From: timohueser Date: Sun, 15 Nov 2026 22:20:53 +0100 Subject: [PATCH 4/6] web: test that the map send waits for the check of the map Co-Authored-By: Claude Opus --- .../src/lib/device-sync/map.svelte.test.ts | 41 +++++++++++++++++++ builder/web/src/lib/device-sync/map.svelte.ts | 2 +- 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 builder/web/src/lib/device-sync/map.svelte.test.ts diff --git a/builder/web/src/lib/device-sync/map.svelte.test.ts b/builder/web/src/lib/device-sync/map.svelte.test.ts new file mode 100644 index 0000000000..803837d785 --- /dev/null +++ b/builder/web/src/lib/device-sync/map.svelte.test.ts @@ -0,0 +1,41 @@ +// @vitest-environment happy-dom + +import { flushSync } from 'svelte'; +import { describe, expect, it } from 'vitest'; +import type { MapRun } from '../coverage/run.svelte'; +import type { CoverageStore } from '../coverage/store.svelte'; +import { ready } from './map.svelte'; + +/** The parts of a store and a run that `ready` reads, as state that the test changes. */ +function stubs() { + const store = $state({ indexError: null, resolutionError: null, regionErrors: new Map(), ledger: { isFinal: false, cellCount: 0 } }); + const run = $state({ ready: false, refusal: null as string | null, estimateError: null as string | null }); + return { store, run, typed: [store as unknown as CoverageStore, run as unknown as MapRun] as const }; +} + +describe('ready', () => { + it('lets the send start only after the cell lists and the memory check of the run are complete', async () => { + const { store, run, typed } = stubs(); + let done = false; + const waiting = ready(...typed, new AbortController().signal).then(() => { done = true; }); + flushSync(); + store.ledger = { isFinal: true, cellCount: 5 }; + flushSync(); + await Promise.resolve(); + expect(done, 'the memory check of the run has not answered').toBe(false); + + run.ready = true; + flushSync(); + await waiting; + expect(done).toBe(true); + }); + + it('ends with the refusal of the memory check, and never starts the send', async () => { + const { store, run, typed } = stubs(); + const waiting = ready(...typed, new AbortController().signal); + store.ledger = { isFinal: true, cellCount: 5 }; + run.refusal = 'Reduce the map selection.'; + flushSync(); + await expect(waiting).rejects.toThrow('Reduce the map selection.'); + }); +}); diff --git a/builder/web/src/lib/device-sync/map.svelte.ts b/builder/web/src/lib/device-sync/map.svelte.ts index f40b22dfab..751db0c8ee 100644 --- a/builder/web/src/lib/device-sync/map.svelte.ts +++ b/builder/web/src/lib/device-sync/map.svelte.ts @@ -41,7 +41,7 @@ export async function buildMap(next: NextMap, client: FlatStoreClient, ctx: JobC } /** Resolves when the run can start, and rejects with the reason why it never can. */ -function ready(store: CoverageStore, run: MapRun, signal: AbortSignal): Promise { +export function ready(store: CoverageStore, run: MapRun, signal: AbortSignal): Promise { return new Promise((resolve, reject) => { let stop = () => {}; const end = (error?: unknown) => { From 1a7a15a67370d6940591002251c4e28579f27cd2 Mon Sep 17 00:00:00 2001 From: timohueser Date: Sun, 15 Nov 2026 22:39:31 +0100 Subject: [PATCH 5/6] web: fix the review findings of the deleted page The local frontend gate no longer calls the deleted build:all; its vitest step builds the app. The option to keep downloaded map data goes, so each run clears the work files of the runs before it. The route upload of the old page, two unused format helpers, saveBytes and the static and log options of the fixture server go. The 503 base map case checks again that only the tile host is asked, and false sentences that named the map builder are correct. Co-Authored-By: Claude Opus --- .cairn/baseline.json | 1 - README.md | 2 +- builder/web/src/lib/coverage/run.svelte.ts | 106 ++------------- .../src/lib/device-sync/map.svelte.test.ts | 2 +- builder/web/src/lib/device-sync/map.svelte.ts | 2 +- builder/web/src/lib/device/flows.test.ts | 57 +------- builder/web/src/lib/device/progress.ts | 2 +- builder/web/src/lib/device/route.test.ts | 72 ---------- builder/web/src/lib/device/route.ts | 128 ------------------ builder/web/src/lib/device/write.ts | 31 +---- builder/web/src/lib/download.ts | 10 +- builder/web/src/lib/format.ts | 22 +-- builder/web/src/lib/usb/objects.ts | 3 +- builder/web/src/lib/usb/protocol.ts | 2 +- builder/web/src/pages/area/outside.ts | 2 +- .../web/tests/browser/planner/area.test.js | 4 +- docs/design/README.md | 9 +- docs/design/map.json | 32 ++--- tools/fixture_catalog.py | 61 +-------- tools/justfile | 2 +- 20 files changed, 53 insertions(+), 497 deletions(-) delete mode 100644 builder/web/src/lib/device/route.test.ts delete mode 100644 builder/web/src/lib/device/route.ts diff --git a/.cairn/baseline.json b/.cairn/baseline.json index 357ff19dd7..cecc03b94f 100644 --- a/.cairn/baseline.json +++ b/.cairn/baseline.json @@ -26,7 +26,6 @@ "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", diff --git a/README.md b/README.md index edc216081d..35141eb8bc 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 builder, Rust/WASM core, USB transport, presets, and server | +| `builder/` | Web app, Rust/WASM core, USB transport, and presets | | `companion-ios/` | SwiftUI companion app and shared iOS package | | `specs/` | Normative binary, wire, and vector contracts | | `fixtures/` | Scenario registry, source provenance, and fixture builders | diff --git a/builder/web/src/lib/coverage/run.svelte.ts b/builder/web/src/lib/coverage/run.svelte.ts index 3c57869a72..1df9fb3c15 100644 --- a/builder/web/src/lib/coverage/run.svelte.ts +++ b/builder/web/src/lib/coverage/run.svelte.ts @@ -23,19 +23,16 @@ import { 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 { downloadCells, planCells, - type CellDownloadPlan, } from "../catalog/download"; import type { CoverageStore } from "./store.svelte"; import type { JobContext } from "../device/progress"; @@ -44,16 +41,6 @@ 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 @@ -101,48 +88,6 @@ interface Output { readonly operations: Set>; } -/** - * 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 { @@ -163,11 +108,6 @@ export class MapRun { /** Set by `failRun`: a delivery that has not started must not write into an * output that is being discarded. */ #sinkClosed = false; - /** The bytes of the cells this run did not have to fetch, because a previous one already put - * them in OPFS under the same digest. */ - #cachedBytes = 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); @@ -239,7 +179,7 @@ export class MapRun { destroy(): void { this.#destroyed = true; - const cause = new DOMException("the map builder was closed", "AbortError"); + const cause = new DOMException("the map run 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 @@ -456,7 +396,7 @@ export class MapRun { try { release = await acquireMapWorkStorage(this.#startWait.signal); if (this.#destroyed) return; - if (!this.#keepCells) await clearMapWorkStorage(); + await clearMapWorkStorage(); } catch { // Startup maintenance is best-effort, as it was before serialization. A later run's // own probes give the actionable storage error. @@ -582,7 +522,7 @@ export class MapRun { 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.#destroyed) throw new DOMException("the map run 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."); } @@ -593,7 +533,6 @@ export class MapRun { this.#runFileName = this.#mapFileName(); this.#delivery = Promise.resolve(); this.#sinkClosed = false; - this.#cachedBytes = 0; this.#phase = "downloading"; out.ctx.phase("downloading", l.totalBytes); @@ -613,18 +552,15 @@ export class MapRun { 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 + // worth out of the tab's heap. 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, + // No run reuses the cells of another. OPFS still carries this run when available, // because that working disk is what makes country-sized assembly possible. - if (!this.#keepCells) { - await runOp(clearCellStores); - } + await runOp(clearCellStores); const writable = await runOp(cellStoreWritable); - out.transientCellRevision = writable && !this.#keepCells ? revision : null; + out.transientCellRevision = writable ? revision : null; let cellStore = writable ? await runOp( () => openCellStore(revision), @@ -640,21 +576,15 @@ export class MapRun { ) : null; if (!cellStore) out.transientCellRevision = null; - let fetchPlan = plan; if (cellStore) { - const cached = await scanCached(plan, cellStore, runOp); - fetchPlan = cached.plan; - 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)); + const hasRoom = await runOp(() => hasRoomFor(projectedRunDiskBytes(l), reclaimable)); if (!hasRoom) { cellStore = null; - fetchPlan = plan; - 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. @@ -668,7 +598,7 @@ export class MapRun { try { await runOp(() => - downloadCells(fetchPlan, { + downloadCells(plan, { fetchImpl: store.client.fetchImpl, onCell: async (item, bytes) => { if (item.article) { @@ -822,15 +752,6 @@ export class MapRun { 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 @@ -842,13 +763,8 @@ export class MapRun { // 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 diskNeed = projectedRunDiskBytes(l); const onDisk = writable && (await hasRoomFor(diskNeed, reclaimable)); if (this.#destroyed || estimateId !== this.#estimateGeneration || l !== this.#ledger) return; this.#estimateLedger = l; diff --git a/builder/web/src/lib/device-sync/map.svelte.test.ts b/builder/web/src/lib/device-sync/map.svelte.test.ts index 803837d785..786e08dfc2 100644 --- a/builder/web/src/lib/device-sync/map.svelte.test.ts +++ b/builder/web/src/lib/device-sync/map.svelte.test.ts @@ -14,7 +14,7 @@ function stubs() { } describe('ready', () => { - it('lets the send start only after the cell lists and the memory check of the run are complete', async () => { + it('lets the send start only after the memory check of the run is complete', async () => { const { store, run, typed } = stubs(); let done = false; const waiting = ready(...typed, new AbortController().signal).then(() => { done = true; }); diff --git a/builder/web/src/lib/device-sync/map.svelte.ts b/builder/web/src/lib/device-sync/map.svelte.ts index 751db0c8ee..a72c8672e7 100644 --- a/builder/web/src/lib/device-sync/map.svelte.ts +++ b/builder/web/src/lib/device-sync/map.svelte.ts @@ -1,4 +1,4 @@ -/** Builds the device map that waits, in this tab, and sends it to the device. It needs the wasm core of the map builder. */ +/** Builds the device map that waits, in this tab, and sends it to the device. It needs the shared wasm core. */ import { CatalogClient } from '../catalog/client'; import { mapWorkBusy } from '../cells/workBarrier'; import { MapRun } from '../coverage/run.svelte'; diff --git a/builder/web/src/lib/device/flows.test.ts b/builder/web/src/lib/device/flows.test.ts index 4ae0e8aec9..346588ef02 100644 --- a/builder/web/src/lib/device/flows.test.ts +++ b/builder/web/src/lib/device/flows.test.ts @@ -1,14 +1,13 @@ /** - * The three flows, end to end against the simulated device. + * The map and firmware flows, end to end against the simulated device. * * The LM20's USB peripheral does not exist yet, so this is where "it works" is decided. The device on * the other end is the real protocol engine over a real flat store on a simulated card: it assigns * the ids, enforces the compare-and-swap, answers a second transfer `busy`, refuses a payload its * extents cannot hold with the bytes it needed, and runs the bilateral cancel. * - * A map is **one object**, exactly as a route and a firmware image are: one `PUT`, one stream, one - * whole-payload CRC, one commit. There is no multi-file map upload to test, so a map's tests are the - * same tests the other two get, on a much larger object. + * A map is **one object**, exactly as a firmware image is: one `PUT`, one stream, one whole-payload + * CRC, one commit. There is no multi-file map upload to test. * * Nothing here proves the LM20 enumerates, that its endpoints have the sizes assumed, or that a real * SD write keeps up. What it does prove is the object-model half, including the four failure paths @@ -27,11 +26,9 @@ import { FlatDevice, flatDevice } from "../usb/flat-device"; import { loopbackLink } from "../usb/loopback"; import type { BytePipe, DeviceLink } from "../usb/pipe"; import { ObjectKind } from "../usb/protocol"; -import { initConvert } from "../convert/bridge"; import { expectBytes } from "../../../test-support/bytes"; import { loadFlatDevice } from "../../../test-support/flat-device/load"; -import { prepareRoute } from "./route"; -import { armUpdate, sendMapBlob, sendMapBytes, sendRoute, stageFirmware } from "./write"; +import { armUpdate, sendMapBlob, sendMapBytes, stageFirmware } from "./write"; import type { JobContext, JobPhase } from "./progress"; function repoRoot(): string { @@ -46,14 +43,7 @@ function repoRoot(): string { const ROOT = repoRoot(); const vector = (name: string) => new Uint8Array(readFileSync(join(ROOT, "specs/vectors", name))); -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(); -}); +beforeAll(loadFlatDevice); interface Watched extends JobContext { readonly phases: JobPhase[]; @@ -319,43 +309,6 @@ describe("map upload from a file", () => { }); }); -describe("route upload", () => { - it("converts a dropped GPX and sends the OBCR the device would have produced itself", async () => { - await withDevice({}, async ({ client, device }) => { - const gpx = readFileSync(join(ROOT, "host/obc-vectors/src/route-source.gpx")); - // The route's name comes from the file's stem, which is what makes this comparable to - // the checked-in vector: same input, same name, same bytes. - const prepared = await prepareRoute(new File([gpx], "Vector Loop.gpx"), 0); - expect(prepared.obcr).toEqual(vector("route-waypoints.obcr")); - expect(prepared.header).toMatchObject({ - name: "Vector Loop", - pointCount: 9, - distanceM: 2207, - ascentM: 76, - }); - - const result = await sendRoute(client, prepared, context()); - expect(device.payloadOf(result.objectId)).toEqual(prepared.obcr); - // The display name is what a catalog listing shows, and it is the route's own name — - // so the row a rider reads on the device page is the row they dropped. - const listed = await client.list({ kind: ObjectKind.Route }); - expect(listed.entries.map((entry) => [entry.objectId, entry.displayName])).toEqual([ - [result.objectId, "Vector Loop"], - ]); - }); - }); - - it("rejects a file that is not a route before anything is sent", async () => { - await withDevice({}, async ({ client, device }) => { - await expect(prepareRoute(new File([new Uint8Array(64)], "notes.txt"), 0)).rejects.toMatchObject({ - name: "ConvertError", - }); - expect(device.entries).toEqual([]); - void client; - }); - }); -}); - describe("firmware update", () => { it("stages a verified container and replaces the one already on the card", async () => { await withDevice({}, async ({ client, device }) => { diff --git a/builder/web/src/lib/device/progress.ts b/builder/web/src/lib/device/progress.ts index 48452bb63b..ebfaa78046 100644 --- a/builder/web/src/lib/device/progress.ts +++ b/builder/web/src/lib/device/progress.ts @@ -1,6 +1,6 @@ /** * What a long device write reports while it runs — the seam between the flows (`write.ts`, plain - * TypeScript, tested under Node) and the thing that renders them (`job.svelte.ts`, runes). + * TypeScript, tested under Node) and the thing that shows them (`lib/device-sync/state.svelte.ts`). * * It lives in its own file so the flows never import a `.svelte.ts` module: everything with logic in * it stays framework-free. diff --git a/builder/web/src/lib/device/route.test.ts b/builder/web/src/lib/device/route.test.ts deleted file mode 100644 index 8d903eca66..0000000000 --- a/builder/web/src/lib/device/route.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -/** - * What the panel says about a dropped route, held to the checked-in OBCR vector. - * - * The numbers shown before a route is sent are read out of the header the converter produced, so - * the guard that matters is that this reader agrees with `specs/vectors/manifest.json` — the - * same record the firmware and the iOS app are pinned to. A distance read from the wrong offset - * would look perfectly plausible on screen. - */ - -import { existsSync, readFileSync } from "node:fs"; -import { dirname, join } from "node:path"; -import { fileURLToPath } from "node:url"; -import { describe, expect, it } from "vitest"; - -import { RouteError, decodeRouteHeader, routeNameFrom } from "./route"; - -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 from " + import.meta.url); -} - -const ROOT = repoRoot(); -const vector = (name: string) => new Uint8Array(readFileSync(join(ROOT, "specs/vectors", name))); - -describe("decodeRouteHeader", () => { - it("reads the vector's header exactly as the manifest records it", () => { - const header = decodeRouteHeader(vector("route-waypoints.obcr")); - expect(header).toMatchObject({ - version: 5, - name: "Vector Loop", - pointCount: 9, - distanceM: 2207, - ascentM: 76, - }); - }); - - it("reads a waypoint-free route the same way", () => { - // The waypoint section is reached by an explicit offset and never by the ride path — - // the two fixtures are the same ride, so every stat must match. - const withWaypoints = decodeRouteHeader(vector("route-waypoints.obcr")); - const plain = decodeRouteHeader(vector("route-plain.obcr")); - expect(plain.distanceM).toBe(withWaypoints.distanceM); - expect(plain.pointCount).toBe(withWaypoints.pointCount); - }); - - it("refuses something that is not a route", () => { - expect(() => decodeRouteHeader(vector("update-container-v1.bin"))).toThrow(RouteError); - expect(() => decodeRouteHeader(new Uint8Array(20))).toThrow(RouteError); - expect(() => decodeRouteHeader(vector("route-plain.obcr").subarray(0, 159))).toThrow(RouteError); - const obsolete = vector("route-plain.obcr"); - obsolete[4] = 3; - expect(() => decodeRouteHeader(obsolete)).toThrow(RouteError); - }); -}); - -describe("routeNameFrom", () => { - it("uses the file's stem", () => { - expect(routeNameFrom("Schauinsland loop.gpx")).toBe("Schauinsland loop"); - expect(routeNameFrom("/tmp/rides/day one.GPX")).toBe("day one"); - expect(routeNameFrom(".gpx")).toBe("Route"); - }); - - it("trims to the format's 48 bytes without splitting a codepoint", () => { - const name = routeNameFrom("ü".repeat(40) + ".gpx"); - expect(new TextEncoder().encode(name).length).toBeLessThanOrEqual(48); - expect(name).toBe("ü".repeat(24)); - }); -}); diff --git a/builder/web/src/lib/device/route.ts b/builder/web/src/lib/device/route.ts deleted file mode 100644 index da3018808c..0000000000 --- a/builder/web/src/lib/device/route.ts +++ /dev/null @@ -1,128 +0,0 @@ -/** - * A dropped GPX, on its way to the device. - * - * Two rules shape this: - * - * - **The device never parses XML.** A route crosses the wire as an OBCR file and is written to - * storage verbatim, so the peer converts. Here that is the wasm bridge, which is the same - * `obc-route` code the device and the CLI run, pinned byte-for-byte by `bridge.test.ts`. - * - **Show what was dropped before sending it.** A GPX file's name says nothing about what is inside - * it, and the rider is about to put it on the thing they will navigate by. The distance, the - * ascent and the point count come from the OBCR header the conversion just produced, not from - * re-reading the GPX. - */ - -import { gpxToObcr } from "../convert/bridge"; -import { truncateUtf8 } from "../format"; -import { viewOf } from "../usb/protocol"; - -/** The route name field's cap, and the OBCR header's own. */ -export const ROUTE_NAME_MAX = 48; - -/** The device's bike types in the device's order. The index is the OBCR header's type byte. */ -export const BIKE_TYPES = ["Road", "Gravel", "MTB", "Touring"] as const; - -const BIKE_TYPE_KEY = "obcm.routeBikeType"; - -/** This page's pick, which holds when storage is denied. */ -let picked: number | null = null; - -/** The bike type last picked for a dropped route. Road when there is no pick. */ -export function rememberedBikeType(): number { - if (picked !== null) return picked; - try { - const bike = Number(globalThis.localStorage?.getItem(BIKE_TYPE_KEY)); - return Number.isInteger(bike) && bike >= 0 && bike < BIKE_TYPES.length ? bike : 0; - } catch { - return 0; - } -} - -export function rememberBikeType(bike: number): void { - picked = bike; - try { - globalThis.localStorage?.setItem(BIKE_TYPE_KEY, String(bike)); - } catch { - // The pick still applies to this page; denied storage means the next visit starts at Road. - } -} - -/** Complete current OBCR header, including waypoint and Visit descriptors. */ -const HEADER_LEN = 160; -const MAGIC = 0x4f424352; // "OBCR", big-endian read of the four ASCII bytes - -/** The header fields worth showing a rider, read back out of the produced file. */ -export interface RouteHeader { - version: number; - name: string; - /** Distinct stored points. Decimated for drawing; the distances below are not. */ - pointCount: number; - /** Meters, exact — computed at conversion from **all** raw GPX points, not the stored ones. */ - distanceM: number; - /** Meters of ascent, smoothed, likewise from the raw points. */ - ascentM: number; - descentM: number; -} - -export class RouteError extends Error { - constructor(message: string) { - super(message); - this.name = "RouteError"; - } -} - -/** - * Read an OBCR header. - * - * Deliberately a *reader*, not a validator: the file it is handed came out of `gpx_to_obcr` a moment - * ago, so the checks here exist to catch a wrong file being fed in, not to re-verify the converter. - */ -export function decodeRouteHeader(bytes: Uint8Array): RouteHeader { - if (bytes.length < HEADER_LEN) { - throw new RouteError(`That file is ${bytes.length} bytes — too short to be a route.`); - } - const view = viewOf(bytes); - if (view.getUint32(0, false) !== MAGIC) throw new RouteError("That file is not an OBCR route."); - const version = bytes[4]; - if (version !== 5) { - throw new RouteError(`That route is OBCR v${version}; this page writes v5.`); - } - const nameLen = Math.min(bytes[6], ROUTE_NAME_MAX); - return { - version, - name: new TextDecoder().decode(bytes.subarray(64, 64 + nameLen)), - pointCount: view.getUint32(32, true), - distanceM: view.getUint32(36, true), - ascentM: view.getUint32(40, true), - descentM: view.getUint32(44, true), - }; -} - -/** A converted route, ready to announce and to send. */ -export interface PreparedRoute { - /** The OBCR bytes, exactly as they will be stored. */ - readonly obcr: Uint8Array; - readonly header: RouteHeader; - /** The dropped file's name, for the "what did I just drop" line. */ - readonly sourceName: string; -} - -/** - * Convert a dropped file to an OBCR typed `bike` and read back what it contains. - * - * The route's name is the file's stem, trimmed to the format's 48 **bytes** — the OBCR header - * measures the field in bytes, so trimming by JavaScript string length would produce a name the - * converter then truncates differently. Anything the conversion rejects arrives as a `ConvertError` - * with a message written for a rider; it is not re-wrapped, because that message is already right. - */ -export async function prepareRoute(file: File, bike: number): Promise { - const bytes = new Uint8Array(await file.arrayBuffer()); - const obcr = await gpxToObcr(bytes, routeNameFrom(file.name), bike); - return { obcr, header: decodeRouteHeader(obcr), sourceName: file.name }; -} - -/** A file name turned into a route name: no extension, no path, and inside the format's byte cap. */ -export function routeNameFrom(filename: string): string { - const stem = filename.replace(/\.[^./\\]+$/, "").replace(/^.*[\\/]/, "").trim(); - return truncateUtf8(stem || "Route", ROUTE_NAME_MAX); -} diff --git a/builder/web/src/lib/device/write.ts b/builder/web/src/lib/device/write.ts index 2b5e0c6886..8d73134f6e 100644 --- a/builder/web/src/lib/device/write.ts +++ b/builder/web/src/lib/device/write.ts @@ -1,15 +1,14 @@ /** - * The three things the builder writes to a device: a map, a route, a firmware image. + * The two things the web app writes to a device here: a map and a firmware image. * * A map is one object. There is no multi-file map upload here — no manifest, no shards, no separate * terrain file to order against them — so every write in this file is a single `PUT` against one - * `.obcm`, `.obcr` or `UPDATE.BIN`, and there is no state that outlives a transfer. + * `.obcm` or `UPDATE.BIN`, and there is no state that outlives a transfer. * - * All three are the same shape underneath: declare the length, the whole-payload CRC, the kind and a + * Both are the same shape underneath: declare the length, the whole-payload CRC, the kind and a * display name, stream the payload, read back what the commit published. What differs is what has to * be true *before* the first byte moves — the map checks the selected map's current id and revision, - * the route has its OBCR header read back and shown, and the firmware has its whole OBCU container - * checked (header CRC, image CRC, slot ceiling). + * and the firmware has its whole OBCU container checked (header CRC, image CRC, slot ceiling). * * "Uploaded" means the device has a valid object. The device verifies the declared length and the * whole-payload CRC, runs the kind's validator, and only then commits; anything else is an error @@ -31,7 +30,6 @@ import { EntryFlags, ObjectKind, type PutResponse } from "../usb/protocol"; import { truncateUtf8 } from "../format"; import { readUpdateImage, type UpdateImage } from "../firmware/obcu"; import type { JobContext } from "./progress"; -import type { PreparedRoute } from "./route"; /** The display-name field: at most 48 UTF-8 bytes. */ export const DISPLAY_NAME_MAX = 48; @@ -147,27 +145,6 @@ async function sendMapSource( ); } -/** - * Send a converted route. - * - * Uploaded as a **create**: the device assigns the `ObjectId` and reports it in the answer. Dropping - * the same GPX twice therefore makes two objects. The catalog carries every object's payload length - * and CRC, so a caller that wants convergence looks before it uploads — - * `FlatStoreClient.findCreated` is that lookup, used to reconcile an upload whose answer was lost - * rather than to pre-empt an ordinary second drop. - */ -export function sendRoute(client: FlatStoreClient, route: PreparedRoute, ctx: JobContext): Promise { - ctx.phase("sending", route.obcr.length); - return client.put( - { kind: ObjectKind.Route, displayName: displayName(route.header.name, "Route") }, - route.obcr, - { - signal: ctx.signal, - onProgress: (done, total) => ctx.progress(done, total), - }, - ); -} - /** A verified update, and what the device will report once it is running. */ export interface StagedFirmware { readonly image: UpdateImage; diff --git a/builder/web/src/lib/download.ts b/builder/web/src/lib/download.ts index 85c2a129dc..0375e5e198 100644 --- a/builder/web/src/lib/download.ts +++ b/builder/web/src/lib/download.ts @@ -187,15 +187,7 @@ async function fetchOnce(url: string, pin: BytePin, opts: DownloadOptions): Prom return bytes; } -export function saveBytes(bytes: Uint8Array, filename: string, type = "application/octet-stream"): void { - saveBlob(new Blob([bytes as unknown as BlobPart], { type }), filename); -} - -/** - * Save a Blob the caller already holds. The assembly stages its files as Blobs while the - * run is still going and saves them once the set is complete, and a Blob is what a - * browser can spill to disk rather than keep in the tab's heap. - */ +/** Save a Blob as a file. A Blob is what a browser can spill to disk rather than keep in the tab's heap. */ export function saveBlob(blob: Blob, filename: string): void { const url = URL.createObjectURL(blob); const anchor = document.createElement("a"); diff --git a/builder/web/src/lib/format.ts b/builder/web/src/lib/format.ts index ed1d5ec186..ba3ab7ced0 100644 --- a/builder/web/src/lib/format.ts +++ b/builder/web/src/lib/format.ts @@ -1,6 +1,4 @@ -/** Human byte sizes. Host-neutral on purpose: the build card shows a result - * 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. */ +/** Human byte sizes. */ 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"; @@ -8,24 +6,6 @@ export function formatBytes(n: number): string { return n + " B"; } -/** Throughput, for a transfer whose speed is worth stating — a map upload is minutes long, and the - * number is what makes that credible instead of alarming. */ -export function formatRate(bytesPerSecond: number): string { - return formatBytes(Math.round(bytesPerSecond)) + "/s"; -} - -/** A rough remaining time. Rounded coarsely and prefixed by the caller with - * "about", because a to-the-second estimate off a moving average is a - * precision nobody has. */ -export function formatDuration(seconds: number): string { - if (seconds < 60) return `${Math.max(1, Math.round(seconds))} s`; - const minutes = Math.round(seconds / 60); - if (minutes < 60) return `${minutes} min`; - const hours = Math.floor(minutes / 60); - const rest = minutes % 60; - return rest ? `${hours} h ${rest} min` : `${hours} h`; -} - /** Trim UTF-8 to a byte-sized wire field without splitting a codepoint. */ export function truncateUtf8(text: string, maxBytes: number): string { const encoder = new TextEncoder(); diff --git a/builder/web/src/lib/usb/objects.ts b/builder/web/src/lib/usb/objects.ts index fd43a5f893..5f2d7e8e63 100644 --- a/builder/web/src/lib/usb/objects.ts +++ b/builder/web/src/lib/usb/objects.ts @@ -6,8 +6,7 @@ * *inside* one object mean, and only for the one kind this app has to look inside. * * Routes, maps and firmware images are absent on purpose: an `.obcr`, an `.obcm` and an `UPDATE.BIN` - * are written verbatim and read back verbatim. The browser's OBCR encoding is the wasm bridge's job, - * and `device/route.ts` reads its header. + * are written verbatim and read back verbatim. The browser's OBCR encoding is the wasm bridge's job. * * There is no list object: `LIST` is a control response carrying 88-byte catalog entries, and what a * client can know about an object without downloading it is exactly what that entry holds. The diff --git a/builder/web/src/lib/usb/protocol.ts b/builder/web/src/lib/usb/protocol.ts index 0a5f9d5db0..020f8780f6 100644 --- a/builder/web/src/lib/usb/protocol.ts +++ b/builder/web/src/lib/usb/protocol.ts @@ -261,7 +261,7 @@ export interface FormatResponse { * A `DataView` over exactly the bytes of `data` — `subarray` keeps the parent buffer, so the offset * and length have to be carried explicitly or every field read is off by the slice. * - * Exported because `objects.ts` and `device/route.ts` parse the same little-endian layouts. + * Exported because `objects.ts` parses the same little-endian layouts. */ export function viewOf(data: Uint8Array): DataView { return new DataView(data.buffer, data.byteOffset, data.byteLength); diff --git a/builder/web/src/pages/area/outside.ts b/builder/web/src/pages/area/outside.ts index 12217a138b..ca0a4c4f68 100644 --- a/builder/web/src/pages/area/outside.ts +++ b/builder/web/src/pages/area/outside.ts @@ -1,4 +1,4 @@ -/** Finds the parts of the rider's routes that leave the area of a device map. It needs the wasm core of the map builder. */ +/** Finds the parts of the rider's routes that leave the area of a device map. It needs the shared wasm core. */ import type { RegionEntry } from '../../lib/catalog/manifest'; import { cellIndexHas } from '../../lib/catalog/satellites'; import { cellContaining, formatCellId, type UBox } from '../../lib/core/grid'; diff --git a/builder/web/tests/browser/planner/area.test.js b/builder/web/tests/browser/planner/area.test.js index 01f28ff4eb..a3edecae89 100644 --- a/builder/web/tests/browser/planner/area.test.js +++ b/builder/web/tests/browser/planner/area.test.js @@ -157,10 +157,12 @@ test('the base map loads in the light and the dark look, from the tile host only }); test('when the base map does not load, the map says so and a click still adds a region', async ({ page }) => { - const errors = await open(page, '#/device/area', { tiles: 'fail' }); + const outside = []; + const errors = await open(page, '#/device/area', { tiles: 'fail', outside }); await expect(page.getByRole('status').filter({ hasText: 'Map background unavailable.' })).toBeVisible(); await page.locator('.leaflet-container').click(); await expect(page.locator('.parts li')).toHaveText(['Bridge Fixture']); + expect(outside.every(url => new URL(url).hostname === HOSTS.tiles)).toBe(true); expect(errors).toEqual([]); }); diff --git a/docs/design/README.md b/docs/design/README.md index d594122430..0dd3ee0656 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -54,7 +54,7 @@ flowchart LR s_content ==> s_map_reading s_device_link ==> s_card_storage s_device_link ==> s_firmware_update - s_device_link ==> s_map_assembly + s_device_link --> s_navigation s_device_map_baking ==> s_content s_device_map_baking ==> s_map_reading s_device_map_baking --> s_rendering_display @@ -73,6 +73,7 @@ flowchart LR s_navigation --> s_map_reading s_rendering_display --> s_foundations s_repository_tooling --> s_card_storage + s_repository_tooling --> s_device_runtime s_route_planning --> s_library s_route_planning ==> s_map_assembly s_route_planning ==> s_trailview @@ -91,7 +92,7 @@ flowchart LR | --- | --- | --- | --- | --- | | [host-runtime](host-runtime.md) | Runs the device core on a computer or phone instead of the board. | draft | card-storage, device-runtime, foundations, map-reading, navigation, rendering-display | map-assembly, simulators | | [library](library.md) | Keeps the rider's routes, rides, photos of rides and settings in the browser, each route and ride with a summary, and saves and loads them as one backup file. | draft | | route-planning, web-planner | -| [map-assembly](map-assembly.md) | Assembles a device map from published cells. | draft | card-storage, device-link, device-map-baking, device-map-builder, foundations, host-runtime, map-reading, map-style, navigation, rendering-display, route-planning | device-link, map-style, obc-data, route-planning, web-planner | +| [map-assembly](map-assembly.md) | Assembles a device map from published cells. | draft | card-storage, device-link, device-map-baking, device-map-builder, foundations, host-runtime, map-reading, map-style, navigation, rendering-display, route-planning | map-style, obc-data, route-planning, web-planner | | [map-style](map-style.md) | Defines how map features look on the device. | draft | device-map-builder, map-assembly | map-assembly, web-planner | | [route-planning](route-planning.md) | Lets a rider plan a route on a map, in the browser or on the phone. | draft | device-map-builder, library, map-assembly, trailview | device-map-builder, map-assembly, obc-data, trailview, trailview-page, web-planner | @@ -116,7 +117,7 @@ flowchart LR | [board-inputs](board-inputs.md) | Turns raw sensor bytes and button edges into the values the core reads. | draft | foundations | device-firmware, simulators | | [board-support](board-support.md) | Drives the nRF54L hardware: radio, USB, microSD, display panel, sensors, buzzer. | draft | | | | [card-storage](card-storage.md) | Keeps the device's objects on the SD card. | draft | device-link, foundations | device-firmware, device-link, host-runtime, map-assembly, repository-tooling, simulators | -| [device-link](device-link.md) | Moves objects between the device and a phone or computer. | draft | card-storage, device-map-builder, firmware-update, foundations, map-assembly, navigation | card-storage, device-firmware, device-map-builder, firmware-update, map-assembly, simulators, web-planner | +| [device-link](device-link.md) | Moves objects between the device and a phone or computer. | draft | card-storage, device-map-builder, firmware-update, foundations, navigation | card-storage, device-firmware, device-map-builder, firmware-update, map-assembly, simulators, web-planner | | [device-runtime](device-runtime.md) | Drives each frame of the device core. | draft | foundations, map-reading, navigation, rendering-display | device-firmware, host-runtime, repository-tooling, simulators | | [discovery](discovery.md) | Tells the rider what is around them: places, summits, landmarks. | draft | | | | [firmware-update](firmware-update.md) | Installs a verified firmware image on the device, with rollback. | draft | device-link, foundations | device-firmware, device-link, device-map-builder, simulators, web-planner | @@ -156,7 +157,7 @@ flowchart LR ## Tangles -- A cycle between card-storage, device-link, device-map-builder, firmware-update, host-runtime, map-assembly, map-style, route-planning, trailview: card-storage -> device-link, device-link -> card-storage, device-link -> device-map-builder, device-link -> firmware-update, device-link -> map-assembly, device-map-builder -> device-link, device-map-builder -> firmware-update, device-map-builder -> route-planning, device-map-builder -> trailview, firmware-update -> device-link, host-runtime -> card-storage, map-assembly -> card-storage, map-assembly -> device-link, map-assembly -> device-map-builder, map-assembly -> host-runtime, map-assembly -> map-style, map-assembly -> route-planning, map-style -> device-map-builder, map-style -> map-assembly, route-planning -> device-map-builder, route-planning -> map-assembly, route-planning -> trailview, trailview -> route-planning +- A cycle between card-storage, device-link, device-map-builder, firmware-update, host-runtime, map-assembly, map-style, route-planning, trailview: card-storage -> device-link, device-link -> card-storage, device-link -> device-map-builder, device-link -> firmware-update, device-map-builder -> device-link, device-map-builder -> firmware-update, device-map-builder -> route-planning, device-map-builder -> trailview, firmware-update -> device-link, host-runtime -> card-storage, map-assembly -> card-storage, map-assembly -> device-link, map-assembly -> device-map-builder, map-assembly -> host-runtime, map-assembly -> map-style, map-assembly -> route-planning, map-style -> device-map-builder, map-style -> map-assembly, route-planning -> device-map-builder, route-planning -> map-assembly, route-planning -> trailview, trailview -> route-planning - A cycle between content, device-map-baking, map-reading, source-preparation: content -> device-map-baking, content -> map-reading, device-map-baking -> content, device-map-baking -> map-reading, device-map-baking -> source-preparation, map-reading -> device-map-baking, source-preparation -> map-reading - route-planning -> planner-map-baking (test) is not in the doc of route-planning - search -> device-map-builder is not in the doc of search diff --git a/docs/design/map.json b/docs/design/map.json index 296fe8ab1a..2fa530d1e1 100644 --- a/docs/design/map.json +++ b/docs/design/map.json @@ -194,8 +194,8 @@ "test_depends_on": [ "map-reading" ], - "violations": 9, - "lines": 35082, + "violations": 8, + "lines": 34811, "problems": [ { "rule": "cycle", @@ -207,16 +207,12 @@ }, { "rule": "cycle", - "message": "device-link -> device-map-builder closes a cycle: builder/web/src/lib/device/flows.test.ts -> builder/web/test-support/bytes.ts (test), builder/web/src/lib/device/flows.test.ts -> builder/web/test-support/flat-device/load.ts (test), builder/web/src/lib/device/route.ts -> builder/web/src/lib/format.ts, and 9 more" + "message": "device-link -> device-map-builder closes a cycle: builder/web/src/lib/device/flows.test.ts -> builder/web/test-support/bytes.ts (test), builder/web/src/lib/device/flows.test.ts -> builder/web/test-support/flat-device/load.ts (test), builder/web/src/lib/device/sha256.test.ts -> builder/web/src/lib/core/hash.ts (test), and 8 more" }, { "rule": "cycle", "message": "device-link -> firmware-update closes a cycle: obc-vectors -> obc-dfu, builder/web/src/lib/device/write.ts -> builder/web/src/lib/firmware/obcu.ts" }, - { - "rule": "cycle", - "message": "device-link -> map-assembly closes a cycle: builder/web/src/lib/device/flows.test.ts -> builder/web/src/lib/convert/bridge.ts (test), builder/web/src/lib/device/route.ts -> builder/web/src/lib/convert/bridge.ts" - }, { "rule": "cycle", "message": "device-map-builder -> device-link closes a cycle: builder/web/test-support/device-smoke/smoke.test.ts -> builder/web/src/lib/usb/client.ts (test), builder/web/test-support/device-smoke/smoke.test.ts -> builder/web/src/lib/usb/flat-device.ts (test), builder/web/test-support/device-smoke/smoke.test.ts -> builder/web/src/lib/usb/protocol.ts (test), and 16 more" @@ -305,11 +301,11 @@ "repository-tooling" ], "violations": 8, - "lines": 9218, + "lines": 9192, "problems": [ { "rule": "cycle", - "message": "device-link -> device-map-builder closes a cycle: builder/web/src/lib/device/flows.test.ts -> builder/web/test-support/bytes.ts (test), builder/web/src/lib/device/flows.test.ts -> builder/web/test-support/flat-device/load.ts (test), builder/web/src/lib/device/route.ts -> builder/web/src/lib/format.ts, and 9 more" + "message": "device-link -> device-map-builder closes a cycle: builder/web/src/lib/device/flows.test.ts -> builder/web/test-support/bytes.ts (test), builder/web/src/lib/device/flows.test.ts -> builder/web/test-support/flat-device/load.ts (test), builder/web/src/lib/device/sha256.test.ts -> builder/web/src/lib/core/hash.ts (test), and 8 more" }, { "rule": "cycle", @@ -534,13 +530,9 @@ "test_depends_on": [ "content" ], - "violations": 9, - "lines": 21873, + "violations": 8, + "lines": 21789, "problems": [ - { - "rule": "cycle", - "message": "device-link -> map-assembly closes a cycle: builder/web/src/lib/device/flows.test.ts -> builder/web/src/lib/convert/bridge.ts (test), builder/web/src/lib/device/route.ts -> builder/web/src/lib/convert/bridge.ts" - }, { "rule": "cycle", "message": "map-assembly -> card-storage closes a cycle: obc-builder-bridge -> obc-storage" @@ -764,7 +756,7 @@ ], "test_depends_on": [], "violations": 0, - "lines": 18944, + "lines": 18895, "problems": [] }, { @@ -1029,7 +1021,7 @@ ], "test_depends_on": [], "violations": 0, - "lines": 13982, + "lines": 14023, "problems": [] }, { @@ -1184,12 +1176,6 @@ "test": false, "undeclared": false }, - { - "from": "device-link", - "to": "map-assembly", - "test": false, - "undeclared": true - }, { "from": "device-link", "to": "map-reading", diff --git a/tools/fixture_catalog.py b/tools/fixture_catalog.py index 462470daba..458f4540c9 100644 --- a/tools/fixture_catalog.py +++ b/tools/fixture_catalog.py @@ -19,7 +19,6 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import json from pathlib import Path -from threading import Thread from urllib.parse import urlsplit ROOT = Path(__file__).resolve().parents[1] @@ -234,67 +233,26 @@ def color(value: int | str) -> int: class CatalogServer(ThreadingHTTPServer): - """Serves a pinned object set, and optionally a static build alongside it on one origin. - - One origin matters: the builder fetches cells with `fetch`, and a second port would be a - cross-origin request needing CORS that the real deployment does not need. - """ + """Serves a pinned object set on loopback.""" daemon_threads = True - def __init__(self, objects: dict[str, bytes], port: int = 0, - static: Path | None = None, log: Path | None = None) -> None: + def __init__(self, objects: dict[str, bytes], port: int = 0) -> None: super().__init__(("127.0.0.1", port), _Handler) self.objects = objects - self.static = static.resolve() if static else None - self.requests: list[str] = [] - self.log = log - if log: - log.parent.mkdir(parents=True, exist_ok=True) - log.write_text(json.dumps({"served": sorted(objects)}) + "\n") @property def origin(self) -> str: return f"http://127.0.0.1:{self.server_port}" - def start(self) -> "CatalogServer": - Thread(target=self.serve_forever, daemon=True).start() - return self - - def record(self, path: str, status: int, kind: str) -> None: - self.requests.append(path) - if self.log: - with self.log.open("a") as handle: - handle.write(json.dumps({"path": path, "status": status, "kind": kind}) + "\n") - - def static_file(self, path: str) -> Path | None: - """A file under the static root, or `None`. A path that escapes the root is not one.""" - - if not self.static: - return None - candidate = (self.static / path.lstrip("/")).resolve() - if candidate.is_dir(): - candidate = candidate / "index.html" - if not candidate.is_file() or self.static not in candidate.parents: - return None - return candidate - class _Handler(BaseHTTPRequestHandler): def do_GET(self) -> None: # noqa: N802 — BaseHTTPRequestHandler's spelling server: CatalogServer = self.server # type: ignore[assignment] path = urlsplit(self.path).path - body, kind, name = server.objects.get(path), "object", path - if body is None: - static = server.static_file(path) - # The served file names the type: a request for the root is an index.html, and - # answering it as an octet-stream makes the browser download the app. - if static: - body, kind, name = static.read_bytes(), "static", static.name - status = 200 if body is not None else 404 - server.record(path, status, kind if body is not None else "missing") - self.send_response(status) - self.send_header("Content-Type", content_type(name) if body is not None else "text/plain") + body = server.objects.get(path) + self.send_response(200 if body is not None else 404) + self.send_header("Content-Type", content_type(path) if body is not None else "text/plain") self.end_headers() self.wfile.write(body if body is not None else b"not found") @@ -306,15 +264,8 @@ def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--catalog", choices=sorted(CATALOGS), default="web-assemble") parser.add_argument("--port", type=int, default=0) - parser.add_argument("--static", type=Path, help="A built site to serve on the same origin.") - parser.add_argument("--log", type=Path, help="JSONL request log; its first line names what is served.") args = parser.parse_args() - if args.static and not (args.static / "index.html").is_file(): - raise SystemExit( - f"{args.static}/index.html is missing. Build it first:\n" - " cd builder/web && npm run build" - ) - server = CatalogServer(CATALOGS[args.catalog](), args.port, args.static, args.log) + server = CatalogServer(CATALOGS[args.catalog](), args.port) print(f"{server.origin} serving {len(server.objects)} pinned objects", flush=True) try: server.serve_forever() diff --git a/tools/justfile b/tools/justfile index 3fc1b86cf4..c890fe0a6e 100644 --- a/tools/justfile +++ b/tools/justfile @@ -731,8 +731,8 @@ check *args: # gets the core and test device from the `wasm-bridges` job; locally we build them. step "wasm bridges" npm run build:wasm step "frontend svelte-check" npm run check + # `bundle.test.ts` builds the web app and inspects the emitted chunks. step "frontend vitest" npm test - step "frontend builds (dev + web)" npm run build:all popd >/dev/null else _warn "skip frontend — npm not installed"; SKIPPED+=("frontend"); fi fi From a27555bbadb96d567ea9919b69ee88c905823b85 Mon Sep 17 00:00:00 2001 From: timohueser Date: Sun, 15 Nov 2026 22:43:20 +0100 Subject: [PATCH 6/6] web: delete the reuse of kept map cells No run reuses the cells of another, so openCellInventory, the stored-cell term of the disk projection and their tests go. Co-Authored-By: Claude Opus --- builder/web/src/lib/cells/quota.test.ts | 6 ------ builder/web/src/lib/cells/quota.ts | 4 ++-- builder/web/src/lib/cells/store.test.ts | 15 +-------------- builder/web/src/lib/cells/store.ts | 18 +++--------------- 4 files changed, 6 insertions(+), 37 deletions(-) diff --git a/builder/web/src/lib/cells/quota.test.ts b/builder/web/src/lib/cells/quota.test.ts index 332fae4d48..78e5388d8d 100644 --- a/builder/web/src/lib/cells/quota.test.ts +++ b/builder/web/src/lib/cells/quota.test.ts @@ -12,10 +12,4 @@ describe("projectedRunDiskBytes", () => { }), ).toBe(2_453_810_944); }); - - it("does not charge free quota again for cells already included in origin usage", () => { - const ledger = { totalBytes: 100, core: { bytes: 20 }, terrain: { bytes: 10 } }; - expect(projectedRunDiskBytes(ledger, 30)).toBe(210); - expect(projectedRunDiskBytes(ledger, 1_000)).toBe(150); - }); }); diff --git a/builder/web/src/lib/cells/quota.ts b/builder/web/src/lib/cells/quota.ts index ebb17576c8..5b8077ddae 100644 --- a/builder/web/src/lib/cells/quota.ts +++ b/builder/web/src/lib/cells/quota.ts @@ -14,8 +14,8 @@ export interface DiskLedger { } /** New downloaded cells, assembled output, and peak retained merge scratch. */ -export function projectedRunDiskBytes(ledger: DiskLedger, storedCellBytes = 0): number { +export function projectedRunDiskBytes(ledger: DiskLedger): number { const terrain = ledger.terrain?.bytes ?? 0; - const newCellBytes = Math.max(0, ledger.totalBytes - terrain - storedCellBytes); + const newCellBytes = Math.max(0, ledger.totalBytes - terrain); return newCellBytes + ledger.totalBytes + SCRATCH_PER_CORE_BYTE * ledger.core.bytes; } diff --git a/builder/web/src/lib/cells/store.test.ts b/builder/web/src/lib/cells/store.test.ts index f0b04f2973..05ec010af8 100644 --- a/builder/web/src/lib/cells/store.test.ts +++ b/builder/web/src/lib/cells/store.test.ts @@ -182,19 +182,6 @@ describe("cellStoreRevision", () => { }); describe("the write side", () => { - it("inspects an existing cell revision without creating a missing one", async () => { - const root = opfs(); - const { openCellInventory, openCellStore } = await withOpfs(root); - expect(await openCellInventory("missing")).toBeNull(); - expect(root.dirs.has("obc-cells")).toBe(false); - - const store = (await openCellStore("kept"))!; - await store.put(KEY_A, new Uint8Array([1, 2, 3, 4])); - const inventory = (await openCellInventory("kept"))!; - expect(await inventory.has(KEY_A, 4)).toBe(true); - expect(await inventory.has(KEY_A, 3)).toBe(false); - }); - it("keeps a cell under its digest and recognises it again", async () => { const root = opfs(); const { openCellStore } = await withOpfs(root); @@ -271,7 +258,7 @@ describe("the write side", () => { expect([...root.dirs.keys()]).toEqual([]); }); - it("counts and clears prior output and scratch without touching reusable cells", async () => { + it("counts and clears prior output and scratch without touching the cells", async () => { const root = opfs(); const { clearAssemblyStorage, openCellStore, reclaimableAssemblyBytes } = await withOpfs(root); const store = (await openCellStore("kept"))!; diff --git a/builder/web/src/lib/cells/store.ts b/builder/web/src/lib/cells/store.ts index 018809e146..c70a1d1440 100644 --- a/builder/web/src/lib/cells/store.ts +++ b/builder/web/src/lib/cells/store.ts @@ -146,18 +146,6 @@ function cellInventory(dir: Directory): CellInventory { }; } -/** Inspect one existing revision without creating or sweeping cache directories. */ -export async function openCellInventory(revision: string): Promise { - const root = await opfsRoot(); - if (!root) return null; - try { - const home = await root.getDirectoryHandle(ROOT); - return cellInventory(await home.getDirectoryHandle(revision)); - } catch { - return null; - } -} - /** * Open (creating if needed) the store for one catalog revision, and sweep the others away. * @@ -205,7 +193,7 @@ export async function clearMapWorkStorage(): Promise { for (const name of [ROOT, OUT, SCRATCH]) await removeDirectoryIfPresent(root, name); } -/** Delete output and scratch from an interrupted run, without deleting reusable cells. */ +/** Delete output and scratch from an interrupted run, and leave its cells. */ export async function clearAssemblyStorage(): Promise { const root = await opfsRoot(); if (!root) return; @@ -236,14 +224,14 @@ export async function reclaimableAssemblyBytes(): Promise { return bytes; } -/** Delete only the assembled-map staging area, leaving reusable cells and merge scratch alone. */ +/** Delete only the assembled-map staging area, and leave the cells and the merge scratch. */ export async function discardMapOutput(): Promise { const root = await opfsRoot(); if (!root) return; await removeDirectoryIfPresent(root, OUT); } -/** Delete one run's cells after its readers have closed. Used when future reuse was not selected. */ +/** Delete one run's cells after its readers have closed. */ export async function discardCellStore(revision: string): Promise { const root = await opfsRoot(); if (!root) return;