mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 13:10:29 +00:00
Compare commits
189 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 99465d04de | |||
| 73a7c4843b | |||
| 6e919696bb | |||
| d32cfb3635 | |||
| 31c9f40550 | |||
| 7ae4dcba51 | |||
| daa4e1dfcf | |||
| 9a7bce6fd8 | |||
| 0834d4f8fe | |||
| d8c28c9998 | |||
| 76ff6e15b1 | |||
| 3e0a2ef8ed | |||
| fd35f79c36 | |||
| 294a386d23 | |||
| ee79413653 | |||
| ec08915a16 | |||
| 40f9c020bb | |||
| 684a3bf5f5 | |||
| 26122a4208 | |||
| 9dc80760f7 | |||
| 090db8519d | |||
| efc55ac700 | |||
| 85b773420c | |||
| 771dab7c35 | |||
| ca7cdcebcc | |||
| 6bc27a259b | |||
| a2d9c2416d | |||
| fd1942afab | |||
| 23eabe1499 | |||
| bcc82db7bd | |||
| 26b220470a | |||
| cdc31967b2 | |||
| 4a435df6e4 | |||
| 21f4f7d5de | |||
| e3d195896c | |||
| 911bd825c1 | |||
| 81628d78ee | |||
| 69e791206e | |||
| e66330e226 | |||
| c970245e0d | |||
| cc0fe6ce2b | |||
| 39346ceca7 | |||
| 6dfba51f21 | |||
| 3973741509 | |||
| 3eac508baf | |||
| 7f6f2eb97c | |||
| f2cfbc4041 | |||
| 636fc7d0a6 | |||
| adcda60f7d | |||
| e8f808b67f | |||
| 70108e5694 | |||
| c75fb22289 | |||
| 621b2f17df | |||
| bc6728678b | |||
| 6040b60e86 | |||
| 2edf5f807a | |||
| fd864cc441 | |||
| b004d3b88e | |||
| 9b1bd6e435 | |||
| 73f3aa8309 | |||
| 82195c7418 | |||
| 9fd77b04fa | |||
| f1ea716305 | |||
| da1a02e7a8 | |||
| 9808e113e4 | |||
| 13e81c04ab | |||
| fd42d06d55 | |||
| e6f4f7a5f3 | |||
| 9497b586b7 | |||
| 77d90be4f8 | |||
| a884539a2b | |||
| 633df91bd6 | |||
| dd98469a02 | |||
| 223a7605ed | |||
| 0e04eeaf9a | |||
| aa77e21d4b | |||
| 8c8cfb5d5d | |||
| 9eeb59997e | |||
| 8179d7d707 | |||
| f211a1c614 | |||
| f42ef5246c | |||
| e1a5864406 | |||
| 62c03d71bf | |||
| f4ce2c2bd0 | |||
| d643f8c329 | |||
| 1b270806a1 | |||
| 2d7392c4c0 | |||
| a9cdb2f91c | |||
| 2983971c8b | |||
| e6a0a39a51 | |||
| 87612c0c79 | |||
| ff57883e3d | |||
| cd1a3fd433 | |||
| 377f22972b | |||
| fff7d123f6 | |||
| bedb70c479 | |||
| 3b8270edc3 | |||
| 6137aaf716 | |||
| 97a3389409 | |||
| 95ade9cbb2 | |||
| c4c278d2f3 | |||
| 2cb1964863 | |||
| 876cc5e0f0 | |||
| caae538056 | |||
| 1cebddac0e | |||
| 78bfa8183a | |||
| 43af349391 | |||
| 9c35343d9d | |||
| b0b1986377 | |||
| f11f021e15 | |||
| 6e7336b8d7 | |||
| 927fcab67f | |||
| c51f4f78bb | |||
| 12f4a40d7c | |||
| 3a6e91e26b | |||
| 680ce7324a | |||
| f5fbd60b5e | |||
| 8c1395c8f1 | |||
| 19bfa77ace | |||
| 2fb041a428 | |||
| be1983c9a4 | |||
| 2288487fe1 | |||
| b2384892a8 | |||
| 43e30ca28e | |||
| 42f0705f07 | |||
| e97dbc89c9 | |||
| 76dfbe0a00 | |||
| 424fa538e0 | |||
| 863ff62b6c | |||
| e2b0910e28 | |||
| cf9172f9e7 | |||
| 0e911608af | |||
| 95d067ad6d | |||
| ba043cb1c0 | |||
| 3a4c523509 | |||
| 057748c47a | |||
| e4457ed9eb | |||
| f430cbe59e | |||
| 5316362e9e | |||
| 900f2bfc30 | |||
| b7c8f0629c | |||
| 45fef1077a | |||
| ddb42ecf0a | |||
| 09295781f4 | |||
| 5938609f69 | |||
| d3cd484519 | |||
| 410d2393e0 | |||
| 44b6340be5 | |||
| 2f3dc4ea79 | |||
| af861e5816 | |||
| c1bbe27ac6 | |||
| 11f4373076 | |||
| f57fb7f9de | |||
| 96f2427518 | |||
| 3f51153dcc | |||
| fc37eb95d1 | |||
| 55607ff2f9 | |||
| 1ea08dcf0a | |||
| c6f6dd2d57 | |||
| 579df97bba | |||
| aa2f7ca8b4 | |||
| 17c9c0758f | |||
| 7340087353 | |||
| 910c98b971 | |||
| b144781e9f | |||
| a26db47cb6 | |||
| 9e5379d092 | |||
| 693acd5580 | |||
| c3f6177be1 | |||
| 60642cc18b | |||
| 54b843ae29 | |||
| 633e9bcdc1 | |||
| eab501925f | |||
| 2630d7e8ec | |||
| 116ba52fbb | |||
| e5fb6d9107 | |||
| 98529bc84c | |||
| 4a3ad562a7 | |||
| 518287ff12 | |||
| 0cdfb9eb42 | |||
| 4d0067a455 | |||
| 66d4431d26 | |||
| 293a48c26a | |||
| 80fca10784 | |||
| 830cd6e3b5 | |||
| 0f338d5484 | |||
| a99cd40f4d | |||
| f3ea50b17b | |||
| 2e3762afe1 |
@@ -0,0 +1,156 @@
|
||||
name: Set up Node and the workspaces
|
||||
description: >-
|
||||
Node from .nvmrc, the workspace dependencies from an exact cache or npm ci,
|
||||
and optionally shared/dist from a cache or a build. Runs after checkout.
|
||||
|
||||
# A local action, so it is versioned with the workflow that calls it and needs
|
||||
# no SHA pin. scripts/ci/changed-areas.mjs counts .github/actions/ like
|
||||
# test.yml: a change here runs everything.
|
||||
#
|
||||
# node_modules is restored only on an exact key: the runner image, the scope,
|
||||
# the Node ABI, the lockfile and every workspace package.json. There are no
|
||||
# restore-keys, so a hit is the tree npm ci would build and a miss is a plain
|
||||
# npm ci. The package.json files are in the key because npm ci is also the
|
||||
# check that they agree with the lockfile: an edited range without a fresh
|
||||
# lockfile misses the cache and fails the install, as it did when every job
|
||||
# ran npm ci. Only pushes to dev and main save, the npm download cache
|
||||
# included, so pull requests read what their base left and cannot evict it or
|
||||
# fill the repository's cache quota with entries of their own.
|
||||
|
||||
inputs:
|
||||
scope:
|
||||
description: >-
|
||||
Which workspaces to install: full (npm ci), client (shared and client)
|
||||
or shared (shared alone).
|
||||
required: true
|
||||
build-shared:
|
||||
description: "'true' to restore shared/dist, or build it on a miss."
|
||||
required: false
|
||||
default: 'false'
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
|
||||
# ImageOS and ImageVersion name the runner image, whose system libraries
|
||||
# the native modules were built against. They live in the runner's
|
||||
# environment, not in the env context, so the key is put together here. A
|
||||
# job in a container has neither; the container's OS release stands in,
|
||||
# and that job's tree is kept apart from the runner's.
|
||||
- name: Work out the cache keys
|
||||
id: keys
|
||||
shell: bash
|
||||
env:
|
||||
SCOPE: ${{ inputs.scope }}
|
||||
DEPS: ${{ hashFiles('.nvmrc', 'package-lock.json', 'package.json', 'client/package.json', 'server/package.json', 'shared/package.json') }}
|
||||
SHARED: ${{ hashFiles('shared/src/**', 'shared/package.json', 'shared/tsconfig*.json', 'shared/tsdown.config.ts', 'package-lock.json') }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
case "$SCOPE" in
|
||||
full | client | shared) ;;
|
||||
*) echo "::error::scope must be full, client or shared, not '$SCOPE'"; exit 1 ;;
|
||||
esac
|
||||
if [ -n "${ImageOS:-}" ]; then
|
||||
image="$ImageOS-${ImageVersion:-unknown}"
|
||||
else
|
||||
image="container-$(. /etc/os-release && echo "$ID$VERSION_ID")"
|
||||
fi
|
||||
abi="$(node -p process.versions.modules)"
|
||||
echo "nm=nm-$RUNNER_OS-$image-$SCOPE-node$abi-$DEPS" >> "$GITHUB_OUTPUT"
|
||||
echo "sd=sd-$RUNNER_OS-$SHARED" >> "$GITHUB_OUTPUT"
|
||||
echo "save=${{ github.event_name == 'push' && (github.ref == 'refs/heads/dev' || github.ref == 'refs/heads/main') }}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Restore node_modules
|
||||
id: nm
|
||||
uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: |
|
||||
node_modules
|
||||
server/node_modules
|
||||
client/node_modules
|
||||
shared/node_modules
|
||||
key: ${{ steps.keys.outputs.nm }}
|
||||
|
||||
# The npm download cache only matters when npm ci runs, so it is restored
|
||||
# only then. It may fall back to an older lockfile's cache: npm ci checks
|
||||
# every tarball against the lockfile's integrity hash and fetches what is
|
||||
# missing, so a stale entry only costs downloads.
|
||||
- name: Restore the npm download cache
|
||||
id: npm
|
||||
if: steps.nm.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
|
||||
restore-keys: npm-${{ runner.os }}-
|
||||
|
||||
- name: Install dependencies
|
||||
if: steps.nm.outputs.cache-hit != 'true'
|
||||
shell: bash
|
||||
env:
|
||||
SCOPE: ${{ inputs.scope }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# better-sqlite3 ships no prebuilt binary and compiles on install. The
|
||||
# hosted runners carry a compiler; the Playwright container of the e2e
|
||||
# jobs does not, so on a cache miss there it gets one first. A hit,
|
||||
# the usual case once a push to dev has saved the container's key,
|
||||
# never reaches this step.
|
||||
if ! command -v make >/dev/null || ! command -v g++ >/dev/null; then
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
timeout 300 apt-get update -qq
|
||||
timeout 300 apt-get install -y -qq --no-install-recommends make g++
|
||||
fi
|
||||
case "$SCOPE" in
|
||||
full) npm ci ;;
|
||||
# The scoped install keeps @testing-library/dom (a peer of
|
||||
# @testing-library/react) in the tree.
|
||||
client) npm ci --workspace shared --workspace client ;;
|
||||
shared) npm ci --workspace shared ;;
|
||||
esac
|
||||
|
||||
- name: Save node_modules
|
||||
if: steps.nm.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true'
|
||||
uses: actions/cache/save@v6
|
||||
with:
|
||||
path: |
|
||||
node_modules
|
||||
server/node_modules
|
||||
client/node_modules
|
||||
shared/node_modules
|
||||
key: ${{ steps.keys.outputs.nm }}
|
||||
|
||||
# Only a full install saves the download cache, so the entry holds every
|
||||
# tarball; a scoped job that finished first would otherwise claim the key
|
||||
# with part of the tree and no later run would fill it.
|
||||
- name: Save the npm download cache
|
||||
if: steps.nm.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true' && steps.npm.outputs.cache-hit != 'true' && inputs.scope == 'full'
|
||||
uses: actions/cache/save@v6
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
|
||||
|
||||
# The key holds every input of the build: the sources, the package and
|
||||
# build configs, and the lockfile that pins tsdown and zod.
|
||||
- name: Restore shared/dist
|
||||
id: sd
|
||||
if: inputs.build-shared == 'true'
|
||||
uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: shared/dist
|
||||
key: ${{ steps.keys.outputs.sd }}
|
||||
|
||||
- name: Build shared
|
||||
if: inputs.build-shared == 'true' && steps.sd.outputs.cache-hit != 'true'
|
||||
shell: bash
|
||||
run: npm run build --workspace=shared
|
||||
|
||||
- name: Save shared/dist
|
||||
if: inputs.build-shared == 'true' && steps.sd.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true'
|
||||
uses: actions/cache/save@v6
|
||||
with:
|
||||
path: shared/dist
|
||||
key: ${{ steps.keys.outputs.sd }}
|
||||
@@ -7,8 +7,11 @@
|
||||
# enforce-target-branch.yml moves those onto dev.
|
||||
#
|
||||
# Every PR runs test.yml like any other, so ci-ok decides whether it can
|
||||
# merge. Dependabot runs get no Actions secrets, so s3-contract and the Sonar
|
||||
# merge. Dependabot runs get no Actions secrets, so server-s3 and the Sonar
|
||||
# scan skip themselves on these PRs and ci-ok counts the skip as passed.
|
||||
# A bump of @playwright/test also needs the Playwright container tag and
|
||||
# digest in test.yml's client-e2e moved by hand; workflow-jobs.test.mjs
|
||||
# fails the PR until they match.
|
||||
version: 2
|
||||
updates:
|
||||
# The root lockfile covers the client, server and shared workspaces.
|
||||
|
||||
@@ -18,9 +18,16 @@ jobs:
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
|
||||
# shared's ESLint and Prettier plugins are its own devDependencies, and
|
||||
# the format ratchet in scripts/lib/ resolves prettier from the root, so
|
||||
# shared plus the root is the whole tree these checks read. npm ci
|
||||
# installs exactly what the lockfile says, where npm install could
|
||||
# resolve anew.
|
||||
- name: Install dependencies
|
||||
run: npm install
|
||||
run: npm ci --workspace shared --include-workspace-root
|
||||
|
||||
- name: Run lint & format check
|
||||
# Both are check-only: lint used to run eslint --fix, which rewrote the
|
||||
|
||||
@@ -10,6 +10,13 @@ permissions:
|
||||
#
|
||||
# Unsigned on purpose: signing and store uploads need secrets that fork PRs do
|
||||
# not get, and belong in a release workflow of their own.
|
||||
#
|
||||
# package-lock.json is not a trigger: every dependency bump touches it, and a
|
||||
# Mac build per bump only held the queue. The shells link nothing but the
|
||||
# @capacitor/* packages, all declared in client/package.json, and a Dependabot
|
||||
# bump of one of them raises the range there too, so it still runs. The client
|
||||
# typecheck and the watch and widget snapshot tests run in test.yml on every
|
||||
# change under client/.
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
@@ -24,7 +31,6 @@ on:
|
||||
- 'client/scripts/check-store-metadata.mjs'
|
||||
- 'client/fastlane/**'
|
||||
- 'client/package.json'
|
||||
- 'package-lock.json'
|
||||
- 'shared/src/i18n/*/native.ts'
|
||||
- '.github/workflows/native.yml'
|
||||
workflow_dispatch:
|
||||
@@ -182,34 +188,6 @@ jobs:
|
||||
path: client/ios/WidgetPreviews/out
|
||||
retention-days: 14
|
||||
|
||||
# The watch's half in the UI (client/src/native/watch.ts): the snapshot it
|
||||
# builds and the ticks it takes back, typechecked and tested here as well,
|
||||
# so a change to the bridge is checked next to the Swift that reads it.
|
||||
watch-bridge:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
- name: Install
|
||||
run: npm ci --workspace=shared --workspace=client
|
||||
|
||||
- name: Build shared
|
||||
run: npm run build --workspace=shared
|
||||
|
||||
- name: Typecheck the client
|
||||
working-directory: client
|
||||
run: npm run typecheck
|
||||
|
||||
- name: Test the widget and watch snapshots
|
||||
working-directory: client
|
||||
run: npx vitest run src/native/watch.test.ts src/native/widgets.test.ts src/native/widgetExtras.test.ts
|
||||
|
||||
# The watch app on watchOS simulators in its screenshot mode (DemoMode.swift):
|
||||
# every screen on the largest and the smallest watch, the main ones in every
|
||||
# language, and the complications, as PNGs to look at without a watch.
|
||||
|
||||
@@ -13,7 +13,7 @@ name: Security Scan
|
||||
# - scout scans the built image, base image packages included. It needs
|
||||
# the Docker Hub login, so it runs on PRs and pushes into main only and
|
||||
# skips fork PRs. Whether the image builds at all is test.yml's
|
||||
# docker-image job, which a red scan cannot hide.
|
||||
# docker job, which a red scan cannot hide.
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main, dev]
|
||||
|
||||
+924
-747
File diff suppressed because it is too large
Load Diff
@@ -31,6 +31,7 @@ Tests:
|
||||
npm run test # all workspaces
|
||||
npm run test --workspace=server # vitest run (server); also test:unit / test:integration / test:ws
|
||||
npm run test:e2e # server e2e (boots Nest against a temp SQLite)
|
||||
npm run test:pg --workspace=server # the Postgres lane (vitest.pg.config.ts; needs TREK_TEST_DB_URL, e.g. postgres://postgres:trek@127.0.0.1:55432/postgres)
|
||||
npm run test:cov # coverage (lcov) for all four packages incl. plugin-sdk
|
||||
cd client && npm run test # client vitest run
|
||||
cd client && npm run e2e # Playwright (CI runs the public and app projects; the screenshot and help-media ones are local)
|
||||
@@ -51,7 +52,9 @@ cd client && npm run lint:skips # no .only; skipped tests may
|
||||
cd client && npm run lint:i18n-keys # every key the client names exists in en; unused en keys may only shrink (CI gate)
|
||||
cd server && npm run lint:boundaries # no new import cycles or cross-domain reach-ins (CI gate)
|
||||
cd server && npm run lint:dialect # SQLite-only SQL spellings may only shrink (CI gate; rules in server/CLAUDE.md)
|
||||
cd server && npm run lint:engine-dispatch # engine checks outside src/db/dialect/ and src/db/engine/ may only shrink (CI gate)
|
||||
cd server && npm run probe:pg # dialect helpers + the repository statements it reaches against Postgres (CI job; needs TREK_PG_PROBE_URL)
|
||||
cd server && npm run check:pg-baseline # the Postgres baseline in server/assets/postgres/ matches the entities and the migrations (CI gate)
|
||||
cd server && npm run lint:tx # no new method writing twice outside one transaction (CI gate)
|
||||
cd server && npm run lint:test-sql # raw SQL fixtures in tests/ may only shrink; seed through tests/helpers/factories (CI gate)
|
||||
cd server && npm run lint:test-mocks # vi.mock of config, realtime and db modules in tests/ may only shrink (CI gate)
|
||||
@@ -134,13 +137,18 @@ These principles come out of a full-repo audit and shape all new code:
|
||||
|
||||
## Quality gates in CI
|
||||
|
||||
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in server-lint-checks), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, the Postgres probe (`postgres-probe`: every dialect helper on SQLite and Postgres, and the statements every repository method reaches with sample arguments against a Postgres service; the SQL errors per method and the list of methods it cannot measure are held to a baseline that only shrinks and fails while it is still unmeasured; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers (`docker-image`), and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (`deploy-manifests`). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
|
||||
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:engine-dispatch`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in `server-lint`), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, TREK on Postgres (`server-postgres`, once per supported major, 14 and 18, each in three slices: first the Postgres probe (in the first slice), every dialect helper on SQLite and Postgres and the statements every repository method reaches with sample arguments, its SQL errors per method and the methods it cannot measure held to a baseline that only shrinks and fails while it is still unmeasured; then the Postgres lane, every suite that boots the app on the real database module, found by `server/tests/postgres/lane.ts` rather than listed, plus PARITY-PG and the write lock; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit, in the Playwright container, in two slices), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers, on SQLite and on Postgres 18, and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (both in `docker`, each part when its area changed). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
|
||||
|
||||
- **Job names read "package: what"** (`Server: Types`, `Client: Tests 3/7`), and the list at the top of `test.yml` says what each job holds. A new job follows the scheme and joins that list, and the job-count note there says when a long job needs a slot freed first.
|
||||
- **Tests run beside the gates, in shards.** The client and server suites run in slices on parallel runners (`client-tests`, `server-tests`, through each package's `vitest.shard.config.ts`), and `client-coverage`/`server-coverage` merge their blob reports and check the thresholds against the whole. A red slice is usually a failing test, a red merge job usually a threshold.
|
||||
- **`ci-ok` is the required check.** The branch ruleset requires `ci-ok` (plus `lint` and `check-target` from their own workflows), and `ci-ok` needs every job above except the scan. It fails if any of them failed or was cancelled and passes if they passed or were skipped. A new gate job counts only once it is listed in `ci-ok`'s `needs:`.
|
||||
- **Job names read "<Area> <what>[ <variant>][ i/n]"** (`Server tests 3/10`, `Server Postgres 14 2/3`, `Docker and Helm`): the area first, one of Changes, Shared, Server, Client, Docker or Sonar, then lower case, with no colon, no parentheses and no middle dot, and a slice only at the end, so the checks list sorts by area. The workflow is named `CI`, so a check reads `CI / Server tests 3/10`. Job ids are the names in kebab-case (`server-tests`), the jobs stand in `test.yml` in area order, and the list at the top of `test.yml` says what each job holds. A new job follows the scheme and joins that list; `scripts/ci/workflow-jobs.test.mjs` fails on a name outside it. `ci-ok`, `lint` and `check-target` keep their names: the ruleset requires them by name.
|
||||
- **What the folded jobs hold.** `Shared tests` is the plugin SDK's typecheck and coverage, run before the root install so the SDK resolves only its own dependencies, then i18n parity and shared's coverage. `Client types` is the typecheck and the strict ratchet; `Client checks` the source ratchets, then the production build with `check:gl-split`. `Docker and Helm` builds and boots the image when the image area changed and checks the chart and compose files when the deploy area changed. Inside a folded job each group of steps runs after a failure in another, so one red check shows every gate that failed; the step names say which.
|
||||
- **Tests run beside the gates, in shards.** The client and server suites run in ten slices each on parallel runners (`client-tests`, `server-tests`, through each package's `vitest.shard.config.ts`), the Postgres lane in three per major, and the end-to-end flows in two, and `client-coverage`/`server-coverage` merge their blob reports and check the thresholds against the whole. A red slice is usually a failing test, a red merge job usually a threshold. A sliced job states its slice count in its matrix's shard axis, the `i/n` in its name and its `--shard=i/n`; `scripts/ci/workflow-jobs.test.mjs` fails until all three agree, and on any job naming `matrix.shard` or `--shard` whose axis is not the one-line `shard: [1, ..., n]` it reads.
|
||||
- **`ci-ok` is the required check.** The branch ruleset requires `ci-ok` (plus `lint` and `check-target` from their own workflows), and `ci-ok` needs every job above except the scan. It fails if any of them failed or was cancelled and passes if they passed or were skipped. A new gate job counts only once it is listed in `ci-ok`'s `needs:`, and `scripts/ci/workflow-jobs.test.mjs` (in `test:ci-scripts`) fails while a job other than the scan is missing there.
|
||||
- **The release pull request mirrors the push run.** On the pull request from `dev` into `main` (head branch in this repository), `changes` sets `mirror` and turns every area off (`scripts/ci/changed-areas.mjs`), so no test, gate or scan job runs, and `ci-ok` runs `scripts/ci/mirror-push-run.mjs`: it waits for the `ci-ok` of the push run of `test.yml` on `dev` for exactly the PR's head commit and passes or fails with it. No such push run, one that ended without a verdict, or a wait past 17 minutes fails with a re-run hint, never passes. A push to `dev` lists its changes against the merge base with `main`, not against the previous push, so the run it mirrors covers every area the pull request brings in, even when an earlier push's run was cancelled or red. Testing that commit twice doubled the jobs past the 60 slots.
|
||||
- **Guides name paths that exist**: the `changes` job runs `scripts/ci/doc-paths.mjs`, which resolves every backtick path in the CLAUDE.md files, `README.md`, `server/src/nest/README.md` and the wiki against the tracked files; the missing ones are listed in `scripts/ci/doc-paths-baseline.json`, which only shrinks (`--update` after a fix).
|
||||
- **What runs is decided by `changes`, not by `on.paths`**: `scripts/ci/changed-areas.mjs` maps the changed files to the `code`, `image` and `deploy` areas (tests: `npm run test:ci-scripts`). A path filter on the workflow would leave `ci-ok` unreported on a docs-only PR and block it. Add a new top-level file the build reads to the right area there.
|
||||
- **What runs is decided by `changes`, not by `on.paths`**: `scripts/ci/changed-areas.mjs` maps the changed files to the `code`, `image` and `deploy` areas (tests: `npm run test:ci-scripts`). A path filter on the workflow would leave `ci-ok` unreported on a docs-only PR and block it. Add a new top-level file the build reads to the right area there. A change to `test.yml`, to `scripts/ci/` or to a local action under `.github/actions/` runs everything.
|
||||
- **Setup goes through one local action.** Every job that installs dependencies uses `.github/actions/setup/action.yml` (`scope` full, client or shared; `build-shared`) instead of its own `npm ci`; `workflow-jobs.test.mjs` fails on a job that installs on its own (plugin-sdk's own install in its directory excepted). The action restores node_modules on an exact key (runner image, scope, Node ABI, `.nvmrc`, the lockfile and every workspace `package.json`, so npm ci still refuses a `package.json` out of step with the lockfile; no restore-keys) and shared/dist on a key over shared's sources and build config, and runs `npm ci` or the shared build on a miss. Only pushes to dev and main save, the npm download cache included; pull requests only read.
|
||||
- **End-to-end runs in the Playwright container**, `mcr.microsoft.com/playwright:v<version>-noble` pinned by digest, so no step installs browsers or system libraries. Dependabot bumps only the lockfile: on every Playwright PR move the tag and its digest in `client-e2e` by hand (`docker buildx imagetools inspect mcr.microsoft.com/playwright:v<version>-noble`); `workflow-jobs.test.mjs` fails until the tag names the lockfile's `@playwright/test` version.
|
||||
- **Budget: `ci-ok` within ten minutes.** One code run starts at most about 35 long jobs (gates, slices, Postgres, e2e, Docker), so two PR runs fit in the organisation's 60 concurrent jobs. Every job sets `timeout-minutes` of at most 20 (15 for the long ones, 10 for the short ones), which `workflow-jobs.test.mjs` holds. A new long job, slice or shard needs a reason that outweighs its slot; the job-count note at the top of `test.yml` has the numbers.
|
||||
- **Runners and Node**: jobs run on `ubuntu-24.04`, not `ubuntu-latest`, and every `setup-node` reads `.nvmrc`. Third-party actions (anything outside `actions/*`) are pinned by commit SHA with the tag in a comment; Dependabot keeps both current.
|
||||
- **Security scans are advisory.** `security.yml` runs `npm audit` (what the image installs, plus `plugin-sdk`) on every PR and push into dev and main, and Docker Scout on the built image for main. Neither is required: a newly published advisory would turn every open PR red at once. Fixes are held as floors in the root `package.json` `overrides`; npm ignores an `overrides` block in a workspace `package.json`, so never put one there.
|
||||
- **Releases** are dispatched by hand and refuse a commit whose `ci-ok` is not green. `docker-dev.yml` (any branch, usually dev) is the canary: it builds the dispatched commit as the next minor or major `-pre.N` and moves only `:latest-pre` and `:<major>-pre`. `docker.yml` (main only) bumps the version, commits and tags it, builds both platforms from exactly that commit and moves `:latest`, `:<major>`, `:<major>.<minor>` and `:<version>`. Its `bump=auto` only finalizes a prerelease in flight; without one it stops and asks for patch, minor or major. Ship a release that migrates or changes a lot as a prerelease first, and as a minor, so installs pinned to `:<major>.<minor>` can wait it out.
|
||||
|
||||
+20
-6
@@ -72,10 +72,23 @@ COPY server/package.json ./server/
|
||||
# package, and a telemetry ping.
|
||||
# The upgrade takes the Debian security fixes the base image was built before
|
||||
# (zlib, 11/2026, failed the image scan until node:24-trixie-slim caught up).
|
||||
RUN apt-get update && \
|
||||
#
|
||||
# postgresql-client-18 brings pg_dump, pg_restore and psql to
|
||||
# /usr/lib/postgresql/18/bin, which back up and restore an install on Postgres
|
||||
# (TREK_DB_URL). A client handles every server up to its own major and refuses
|
||||
# a newer one, so the image carries the newest major TREK supports (14 to 18).
|
||||
# Debian 13 ships 17 only, so it comes from the PostgreSQL project's apt
|
||||
# repository (PGDG): the `18` component lists that major's packages and no
|
||||
# other, and the repository's signing key (fingerprint B97B 0AFC AA1A 47F0 44F2
|
||||
# 44A0 7FCC 7D46 ACCC 4CF8) is kept beside the entrypoint instead of fetched at
|
||||
# build time. Raise both together when TREK supports a newer major.
|
||||
COPY server/scripts/pgdg-apt-key.asc /etc/apt/keyrings/pgdg.asc
|
||||
RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/pub/repos/apt trixie-pgdg main 18' \
|
||||
> /etc/apt/sources.list.d/pgdg.list && \
|
||||
apt-get update && \
|
||||
apt-get upgrade -y --no-install-recommends && \
|
||||
apt-get install -y --no-install-recommends tzdata dumb-init wget ca-certificates \
|
||||
libkitinerary-bin libsqlite3-0 && \
|
||||
libkitinerary-bin libsqlite3-0 postgresql-client-18 && \
|
||||
npm ci --workspace=server --omit=dev --ignore-scripts && \
|
||||
{ ln -sf "$(find /usr/lib -name kitinerary-extractor -type f | head -1)" /usr/local/bin/kitinerary-extractor || true; } && \
|
||||
rm -rf /var/lib/apt/lists/* /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx && \
|
||||
@@ -94,8 +107,9 @@ ENV KITINERARY_EXTRACTOR_PATH=/usr/local/bin/kitinerary-extractor
|
||||
|
||||
COPY --chown=node:node --from=server-builder /app/server/dist ./server/dist
|
||||
# Runtime data assets read from server/assets at runtime: airports.json (flight
|
||||
# transport search) and atlas/*.geojson.gz + atlas/admin1/*.geojson.gz (Atlas
|
||||
# country/region map). The build
|
||||
# transport search), atlas/*.geojson.gz + atlas/admin1/*.geojson.gz (Atlas
|
||||
# country/region map) and postgres/baseline.* (the schema a fresh Postgres
|
||||
# database starts from). The build
|
||||
# only emits dist, so these must be copied explicitly or the features silently
|
||||
# degrade to empty in the image.
|
||||
COPY --chown=node:node --from=server-builder /app/server/assets ./server/assets
|
||||
@@ -106,9 +120,9 @@ COPY --chown=node:node wiki ./wiki
|
||||
# tsconfig-paths/register reads this at runtime to resolve MCP SDK paths.
|
||||
COPY --chown=node:node server/tsconfig.json ./server/
|
||||
# Encryption-key rotation is run on demand via tsx (a prod dep) straight from the
|
||||
# raw .ts source — it never enters dist, so it must be copied in explicitly or
|
||||
# raw .ts source (the command and its stores module). They never enter dist, so they must be copied in explicitly or
|
||||
# `node --import tsx scripts/migrate-encryption.ts` fails with module-not-found.
|
||||
COPY --chown=node:node server/scripts/migrate-encryption.ts ./server/scripts/migrate-encryption.ts
|
||||
COPY --chown=node:node server/scripts/migrate-encryption.ts server/scripts/migrate-encryption-stores.ts ./server/scripts/
|
||||
# Admin recovery script (node server/reset-admin.js) for locked-out installs.
|
||||
COPY --chown=node:node server/reset-admin.js ./server/reset-admin.js
|
||||
COPY --chown=node:node --from=shared-builder /app/shared/dist ./shared/dist
|
||||
|
||||
@@ -321,6 +321,11 @@ docker compose up -d
|
||||
See [Install with Docker Compose](https://github.com/liketrek/TREK/wiki/Install-Docker-Compose)
|
||||
for the full walkthrough.
|
||||
|
||||
TREK stores its data in SQLite by default. Set `TREK_DB_URL` to run it on a PostgreSQL 14 to 18 database instead. The
|
||||
[`docker-compose.postgres.yml`](docker-compose.postgres.yml) example starts one beside TREK, and the
|
||||
[Postgres guide](https://github.com/liketrek/TREK/wiki/Database-Postgres) covers the requirements, the backups and
|
||||
how to move an existing SQLite install to Postgres with the command TREK ships for it.
|
||||
|
||||
<br />
|
||||
|
||||
<h2 id="helm-kubernetes">Helm (Kubernetes)</h2>
|
||||
|
||||
@@ -46,6 +46,7 @@ See `values.yaml` for more options.
|
||||
- Both PVCs are `ReadWriteOnce`. Set `persistence.data.accessModes` and/or `persistence.uploads.accessModes` to override, for example `[ReadWriteMany]` so a backup pod can mount the volume. On the data volume such a pod may only read: SQLite corrupts `travel.db` when a second process writes it over a network filesystem.
|
||||
- To use your own PVCs, set `persistence.data.existingClaim` and/or `persistence.uploads.existingClaim`. The other values for that volume (size, storageClassName, accessModes, annotations) are then ignored.
|
||||
- With `persistence.enabled: false`, the data and uploads volumes use an `emptyDir` — storage is ephemeral and lost on pod restart. Intended for testing only.
|
||||
- `database.url` runs TREK on a PostgreSQL database instead of the SQLite file. The chart writes it into its Secret as `TREK_DB_URL`; `database.existingSecret` and `database.existingSecretKey` read it from a Secret you manage. Leave both empty for SQLite. Keep `replicas: 1` either way. See the wiki page `Database-Postgres`.
|
||||
- `JWT_SECRET` is managed entirely by the server — auto-generated into the data PVC on first start and rotatable via the admin panel (Settings → Danger Zone). No Helm configuration needed.
|
||||
- `ENCRYPTION_KEY` encrypts stored secrets (API keys, MFA, SMTP, OIDC) at rest. Recommended: set via `secretEnv.ENCRYPTION_KEY` or `existingSecret`. If left empty, the server falls back automatically: existing installs use `data/.jwt_secret` (no action needed on upgrade); fresh installs auto-generate a key persisted to the data PVC.
|
||||
- Liveness and readiness probes are configurable under `probes`. Overrides are merged over the defaults, so `--set probes.liveness.initialDelaySeconds=60` keeps the `httpGet` handler. When switching to `exec` or `tcpSocket`, clear `httpGet` in the same override. Set `probes.liveness: null` to remove a probe.
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
{{- if and .Values.database.url (not .Values.database.existingSecret) .Values.existingSecret }}
|
||||
{{- fail "database.url is written into the chart's own Secret, which existingSecret replaces. Put TREK_DB_URL in your Secret and set database.existingSecret instead." }}
|
||||
{{- end }}
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
@@ -5,11 +8,13 @@ metadata:
|
||||
labels:
|
||||
app: {{ include "trek.name" . }}
|
||||
spec:
|
||||
# One replica. Its rate limits, pending codes, permission cache and WebSocket
|
||||
# connections live in the process's memory, so a second pod would not share them. That
|
||||
# holds with database.url (PostgreSQL) too; see updateStrategy in values.yaml.
|
||||
replicas: 1
|
||||
# TREK is a single-writer SQLite app on a ReadWriteOnce PVC, so the default
|
||||
# RollingUpdate would start a second pod holding the same volume before the old one
|
||||
# exits — a Multi-Attach deadlock, or two processes on one travel.db. Recreate tears
|
||||
# the old pod down first. Keep it, see updateStrategy in values.yaml.
|
||||
# The default RollingUpdate would start a second pod on the same ReadWriteOnce PVC
|
||||
# before the old one exits: a Multi-Attach deadlock, or two processes on one travel.db.
|
||||
# Recreate tears the old pod down first. Keep it, see updateStrategy in values.yaml.
|
||||
strategy:
|
||||
type: {{ .Values.updateStrategy | default "Recreate" }}
|
||||
selector:
|
||||
@@ -61,6 +66,14 @@ spec:
|
||||
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
|
||||
key: {{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}
|
||||
optional: true
|
||||
{{- if or .Values.database.url .Values.database.existingSecret }}
|
||||
# Required when set: a missing key stops the pod rather than starting it on SQLite.
|
||||
- name: TREK_DB_URL
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.database.existingSecret }}
|
||||
key: {{ if .Values.database.existingSecret }}{{ .Values.database.existingSecretKey | default "TREK_DB_URL" }}{{ else }}TREK_DB_URL{{ end }}
|
||||
{{- end }}
|
||||
- name: ADMIN_EMAIL
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
|
||||
@@ -8,6 +8,9 @@ metadata:
|
||||
type: Opaque
|
||||
data:
|
||||
{{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}: {{ .Values.secretEnv.ENCRYPTION_KEY | b64enc | quote }}
|
||||
{{- if .Values.database.url }}
|
||||
TREK_DB_URL: {{ .Values.database.url | b64enc | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.ADMIN_EMAIL }}
|
||||
ADMIN_EMAIL: {{ .Values.secretEnv.ADMIN_EMAIL | b64enc | quote }}
|
||||
{{- end }}
|
||||
@@ -65,6 +68,9 @@ stringData:
|
||||
{{- else }}
|
||||
{{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}: {{ randAlphaNum 32 | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.database.url }}
|
||||
TREK_DB_URL: {{ .Values.database.url | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.ADMIN_EMAIL }}
|
||||
ADMIN_EMAIL: {{ .Values.secretEnv.ADMIN_EMAIL | quote }}
|
||||
{{- end }}
|
||||
|
||||
+23
-4
@@ -4,10 +4,13 @@ image:
|
||||
# tag: latest
|
||||
pullPolicy: IfNotPresent
|
||||
|
||||
# Deployment update strategy. Keep Recreate: TREK is a single-writer SQLite app, and
|
||||
# during a RollingUpdate the new pod migrates the database while the old one still
|
||||
# writes to it. A ReadWriteMany volume does not make that safe; SQLite's WAL needs both
|
||||
# processes on one host, which network filesystems do not provide.
|
||||
# Deployment update strategy. Keep Recreate. The new pod migrates the database when it
|
||||
# starts, and during a RollingUpdate it would do that while the old pod still writes to
|
||||
# it. Recreate stops the old pod first. On SQLite two processes on one travel.db are
|
||||
# unsafe, and a ReadWriteOnce volume cannot be attached to both pods at once.
|
||||
# With database.url the database is PostgreSQL, but the reason for one replica stays: TREK
|
||||
# keeps rate limits, pending codes, the permission cache and WebSocket connections in
|
||||
# memory, so a second pod would not share them. Postgres does not make more replicas safe.
|
||||
updateStrategy: Recreate
|
||||
|
||||
# Pod-level security context. fsGroup gives the node user (uid/gid 1000) group access
|
||||
@@ -178,6 +181,22 @@ env:
|
||||
# address is sent unless you set one here.
|
||||
|
||||
|
||||
# Database. Empty (the default) keeps TREK on its SQLite file in the data volume. Set url to
|
||||
# run TREK on a PostgreSQL database instead (see the wiki page Database-Postgres). The URL
|
||||
# carries the password, so it is never a plain env value: with url, the chart writes it into
|
||||
# its own Secret as TREK_DB_URL; with existingSecret, TREK reads TREK_DB_URL from that Secret
|
||||
# under existingSecretKey and the chart writes nothing. existingSecret wins over url. The
|
||||
# variable is required when either is set: a missing Secret key stops the pod instead of
|
||||
# starting it on SQLite. The role in the URL owns TREK's database and must not be a superuser
|
||||
# (nor a member of one, nor hold a right that reaches the server's files or programs): a
|
||||
# restore runs the backup's SQL as that role and refuses one that could reach the database host. The wiki page shows the
|
||||
# SQL that creates such a role. PostgreSQL 14 to 18 is supported.
|
||||
# url: "postgres://trek:<password>@postgres.example.internal:5432/trek?sslmode=require"
|
||||
database:
|
||||
url: ""
|
||||
existingSecret: ""
|
||||
existingSecretKey: TREK_DB_URL
|
||||
|
||||
# Secret environment variables stored in a Kubernetes Secret.
|
||||
# JWT_SECRET is managed entirely by the server (auto-generated into the data PVC,
|
||||
# rotatable via the admin panel) — it is not configured here.
|
||||
|
||||
@@ -82,10 +82,12 @@ abstract class TrekWidget : GlanceAppWidget() {
|
||||
// Read inside the composition: a session outlives one update, and every
|
||||
// write (the dashboard's, then each trip's) must reach it.
|
||||
val version by WidgetStore.version.collectAsState()
|
||||
val snapshot = remember(version) {
|
||||
val stored = remember(version) {
|
||||
val tripId = if (perTrip && appWidgetId >= 0) WidgetStore.tripFor(context, appWidgetId) else WidgetStore.AUTO
|
||||
WidgetStore.load(context, tripId)
|
||||
}
|
||||
// The day of the trip is today's on every update, not the one the app last wrote.
|
||||
val snapshot = stored?.on(LocalDate.now())
|
||||
TrekWidgetTheme.Themed { Content(snapshot) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,28 @@ data class WidgetSnapshot(
|
||||
val labels: Labels,
|
||||
/** The trip's next flight or the one in the air; last and defaulted, so older callers keep compiling. */
|
||||
val flight: Flight? = null,
|
||||
/**
|
||||
* The trip's days from the day the app wrote this on, each with its date, so
|
||||
* the widget turns to the next day itself (see [on]); empty from an app
|
||||
* that predates them.
|
||||
*/
|
||||
val days: List<Today> = emptyList(),
|
||||
) {
|
||||
/**
|
||||
* The snapshot as it reads on [date]: that date's trip day out of [days],
|
||||
* none before or after the trip, and only the bookings from that date on.
|
||||
* The app writes its snapshot only while it runs, so without this a widget
|
||||
* showed the day it last ran. A snapshot without [days] reads as written.
|
||||
*/
|
||||
fun on(date: LocalDate): WidgetSnapshot {
|
||||
if (days.isEmpty()) return this
|
||||
val key = date.toString()
|
||||
return copy(
|
||||
today = days.firstOrNull { it.date == key },
|
||||
bookings = bookings.filter { (it.date ?: key) >= key },
|
||||
)
|
||||
}
|
||||
|
||||
data class Trip(
|
||||
val title: String,
|
||||
val start: String,
|
||||
@@ -52,7 +73,8 @@ data class WidgetSnapshot(
|
||||
val symbol: String?,
|
||||
)
|
||||
|
||||
data class Today(val dayLabel: String, val stops: List<Stop>, val index: Int?, val total: Int?)
|
||||
/** A trip day; [date] (yyyy-MM-dd) is absent from an app that predates the days ahead. */
|
||||
data class Today(val dayLabel: String, val stops: List<Stop>, val index: Int?, val total: Int?, val date: String? = null)
|
||||
|
||||
data class Weather(
|
||||
val temp: Int,
|
||||
@@ -212,6 +234,16 @@ data class WidgetSnapshot(
|
||||
null
|
||||
}
|
||||
|
||||
private fun dayOf(t: JSONObject): Today = Today(
|
||||
dayLabel = t.optString("dayLabel"),
|
||||
stops = t.optJSONArray("stops").objects().map {
|
||||
Stop(it.str("time"), it.optString("name"), it.int("minutes"), it.str("color"), it.str("symbol"))
|
||||
},
|
||||
index = t.int("index"),
|
||||
total = t.int("total"),
|
||||
date = t.str("date"),
|
||||
)
|
||||
|
||||
fun fromJson(o: JSONObject): WidgetSnapshot = WidgetSnapshot(
|
||||
trip = o.optJSONObject("trip")?.let {
|
||||
Trip(
|
||||
@@ -226,16 +258,8 @@ data class WidgetSnapshot(
|
||||
memberCount = it.int("memberCount"),
|
||||
)
|
||||
},
|
||||
today = o.optJSONObject("today")?.let { t ->
|
||||
Today(
|
||||
dayLabel = t.optString("dayLabel"),
|
||||
stops = t.optJSONArray("stops").objects().map {
|
||||
Stop(it.str("time"), it.optString("name"), it.int("minutes"), it.str("color"), it.str("symbol"))
|
||||
},
|
||||
index = t.int("index"),
|
||||
total = t.int("total"),
|
||||
)
|
||||
},
|
||||
today = o.optJSONObject("today")?.let(::dayOf),
|
||||
days = o.optJSONArray("days").objects().map(::dayOf),
|
||||
weather = o.optJSONObject("weather")?.let {
|
||||
Weather(it.optInt("temp"), it.int("high"), it.int("low"), it.optString("main"), it.optString("label"), it.str("place"), it.int("rain"))
|
||||
},
|
||||
|
||||
@@ -99,4 +99,34 @@ class WidgetSnapshotTest {
|
||||
assertEquals("ferry.fill", TrekIcons.booking("cruise").first)
|
||||
assertEquals("bookmark.fill", TrekIcons.booking("something").first)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun turnsToTheDayOfTheDateItIsReadOn() {
|
||||
val json = """{"trip":{"title":"T","start":"2026-11-06","end":"2026-11-08","path":"/trips/1"},
|
||||
"today":{"date":"2026-11-06","dayLabel":"Day 1 of 3","stops":[{"time":"09:00","name":"Museum","minutes":540}]},
|
||||
"days":[
|
||||
{"date":"2026-11-06","dayLabel":"Day 1 of 3","stops":[{"time":"09:00","name":"Museum","minutes":540}]},
|
||||
{"date":"2026-11-07","dayLabel":"Day 2 of 3","stops":[{"time":"10:00","name":"Harbour","minutes":600}]}
|
||||
],
|
||||
"bookings":[
|
||||
{"title":"Hotel","kind":"hotel","date":"2026-11-06","confirmed":true,"path":"/trips/1"},
|
||||
{"title":"Train","kind":"train","date":"2026-11-07","confirmed":true,"path":"/trips/1"}
|
||||
],
|
||||
"labels":{}}"""
|
||||
val snapshot = WidgetSnapshot.parse(json)!!
|
||||
assertEquals("Day 1 of 3", snapshot.on(LocalDate.of(2026, 11, 6)).today!!.dayLabel)
|
||||
val second = snapshot.on(LocalDate.of(2026, 11, 7))
|
||||
assertEquals("Day 2 of 3", second.today!!.dayLabel)
|
||||
assertEquals("Harbour", second.today!!.stops.single().name)
|
||||
assertEquals(listOf("Train"), second.bookings.map { it.title })
|
||||
// A day the app wrote nothing for (the trip is over) shows no day.
|
||||
assertNull(snapshot.on(LocalDate.of(2026, 11, 9)).today)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aSnapshotWithoutDaysReadsAsWritten() {
|
||||
val snapshot = WidgetSnapshot.parse(WidgetSamples.json(running = true, now = today))!!
|
||||
assertTrue(snapshot.days.isEmpty())
|
||||
assertEquals(snapshot, snapshot.on(today.plusDays(3)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -686,9 +686,8 @@ extension TrekShellPlugin {
|
||||
/// know are left out, so the shell offers only what can really be bought.
|
||||
@objc func storeProducts(_ call: CAPPluginCall) {
|
||||
let ids = call.getArray("ids", String.self) ?? []
|
||||
// TestFlight, App Review and Xcode builds buy in the sandbox; their receipt says so.
|
||||
let sandbox = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
|
||||
Task {
|
||||
let sandbox = await Self.buysInSandbox()
|
||||
guard AppStore.canMakePayments, let products = try? await Product.products(for: ids) else {
|
||||
call.resolve(["products": [], "sandbox": sandbox])
|
||||
return
|
||||
@@ -697,6 +696,26 @@ extension TrekShellPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this build buys in the App Store sandbox: TestFlight, App Review and
|
||||
/// Xcode builds do, and while TREK Cloud's orders are closed only they may buy.
|
||||
/// The signed app transaction names its environment; the receipt's file name,
|
||||
/// which App Review builds do not always carry, is only the fallback where the
|
||||
/// app transaction is missing (iOS 15) or cannot be read.
|
||||
static func buysInSandbox() async -> Bool {
|
||||
let receiptSaysSandbox = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
|
||||
guard #available(iOS 16.0, *), let result = try? await AppTransaction.shared else {
|
||||
return receiptSaysSandbox
|
||||
}
|
||||
// An unverified transaction still names the environment it was signed in;
|
||||
// it only decides whether the button shows, the cloud checks every purchase itself.
|
||||
let transaction: AppTransaction
|
||||
switch result {
|
||||
case .verified(let signed), .unverified(let signed, _):
|
||||
transaction = signed
|
||||
}
|
||||
return transaction.environment != .production || receiptSaysSandbox
|
||||
}
|
||||
|
||||
/// Feature storeKit: runs the App Store purchase sheet. Resolves with `kind`
|
||||
/// bought (with the signed transaction the control plane verifies), cancelled,
|
||||
/// pending (Ask to Buy, a payment the bank still has to approve) or failed.
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 104 KiB After Width: | Height: | Size: 49 KiB |
@@ -21,12 +21,14 @@ struct TrekProvider: TimelineProvider {
|
||||
func getSnapshot(in context: Context, completion: @escaping (TrekEntry) -> Void) {
|
||||
let stored = WidgetSnapshot.load()
|
||||
let snapshot: WidgetSnapshot? = (stored?.trip != nil || !context.isPreview) ? stored : WidgetSnapshot.sample(running: false)
|
||||
completion(TrekEntry(date: Date(), snapshot: snapshot))
|
||||
let now = Date()
|
||||
completion(TrekEntry(date: now, snapshot: snapshot?.on(now)))
|
||||
}
|
||||
|
||||
/// An entry every quarter hour for the next six hours, so the now line and
|
||||
/// the next stop move on without the app; the app reloads the timeline
|
||||
/// whenever it writes a new snapshot.
|
||||
/// the next stop move on without the app, each with the trip day of its own
|
||||
/// date: the one at midnight turns to the next day. The app reloads the
|
||||
/// timeline whenever it writes a new snapshot, WidgetKit when it runs out.
|
||||
func getTimeline(in context: Context, completion: @escaping (Timeline<TrekEntry>) -> Void) {
|
||||
completion(TrekProvider.timeline(WidgetSnapshot.load()))
|
||||
}
|
||||
@@ -36,10 +38,11 @@ struct TrekProvider: TimelineProvider {
|
||||
let calendar = Calendar.current
|
||||
let minute = calendar.component(.minute, from: now)
|
||||
let firstStep = calendar.date(byAdding: .minute, value: 15 - minute % 15, to: now) ?? now
|
||||
var entries = [TrekEntry(date: now, snapshot: snapshot)]
|
||||
var entries = [TrekEntry(date: now, snapshot: snapshot?.on(now))]
|
||||
for step in 0..<24 {
|
||||
if let date = calendar.date(byAdding: .minute, value: step * 15, to: firstStep) {
|
||||
entries.append(TrekEntry(date: calendar.date(bySetting: .second, value: 0, of: date) ?? date, snapshot: snapshot))
|
||||
let at = calendar.date(bySetting: .second, value: 0, of: date) ?? date
|
||||
entries.append(TrekEntry(date: at, snapshot: snapshot?.on(at)))
|
||||
}
|
||||
}
|
||||
return Timeline(entries: entries, policy: .atEnd)
|
||||
|
||||
@@ -63,7 +63,8 @@ struct TrekTripProvider: AppIntentTimelineProvider {
|
||||
func snapshot(for configuration: SelectTripIntent, in context: Context) async -> TrekEntry {
|
||||
let stored = WidgetSnapshot.load(trip: configuration.trip?.id)
|
||||
let snapshot: WidgetSnapshot? = (stored?.trip != nil || !context.isPreview) ? stored : WidgetSnapshot.sample(running: false)
|
||||
return TrekEntry(date: Date(), snapshot: snapshot)
|
||||
let now = Date()
|
||||
return TrekEntry(date: now, snapshot: snapshot?.on(now))
|
||||
}
|
||||
|
||||
func timeline(for configuration: SelectTripIntent, in context: Context) async -> Timeline<TrekEntry> {
|
||||
|
||||
@@ -35,6 +35,8 @@ struct WidgetSnapshot: Codable {
|
||||
}
|
||||
|
||||
struct Today: Codable {
|
||||
/// The calendar day it is, yyyy-MM-dd (absent from an app that predates `days`).
|
||||
var date: String?
|
||||
var dayLabel: String
|
||||
var stops: [Stop]
|
||||
/// 1-based position of today in the trip.
|
||||
@@ -245,6 +247,9 @@ struct WidgetSnapshot: Codable {
|
||||
|
||||
var trip: Trip?
|
||||
var today: Today?
|
||||
/// The trip's days from the day the app wrote this on, each with its date,
|
||||
/// so the widget turns to the next day itself (see `on(_:)`).
|
||||
var days: [Today]?
|
||||
var weather: Weather?
|
||||
var bookings: [Booking]?
|
||||
var todos: Todos?
|
||||
@@ -306,6 +311,26 @@ struct WidgetSnapshot: Codable {
|
||||
return days + 1
|
||||
}
|
||||
|
||||
/// The snapshot as it reads on `date`: that date's trip day out of `days`,
|
||||
/// none before or after the trip, and only the bookings from that date on.
|
||||
/// The app writes its snapshot only while it runs, so without this a widget
|
||||
/// showed the day it last ran (TestFlight feedback: "stuck on day 1"). A
|
||||
/// snapshot from an app without `days` reads as it was written.
|
||||
func on(_ date: Date) -> WidgetSnapshot {
|
||||
guard let days, !days.isEmpty else { return self }
|
||||
let key = WidgetSnapshot.key(date)
|
||||
var snapshot = self
|
||||
snapshot.today = days.first { $0.date == key }
|
||||
snapshot.bookings = bookings?.filter { ($0.date ?? key) >= key }
|
||||
return snapshot
|
||||
}
|
||||
|
||||
/// A date as the app writes one, yyyy-MM-dd in the device's calendar day.
|
||||
static func key(_ date: Date) -> String {
|
||||
let parts = Calendar.current.dateComponents([.year, .month, .day], from: date)
|
||||
return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0)
|
||||
}
|
||||
|
||||
static func daysBetween(_ from: Date, _ to: Date) -> Int? {
|
||||
let calendar = Calendar.current
|
||||
return calendar.dateComponents([.day], from: calendar.startOfDay(for: from), to: calendar.startOfDay(for: to)).day
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
"pdf.ts": 1,
|
||||
"perm.ts": 4,
|
||||
"places.ts": 9,
|
||||
"planner.ts": 53,
|
||||
"planner.ts": 52,
|
||||
"reservations.ts": 21,
|
||||
"roadtrip.ts": 36,
|
||||
"settings.ts": 37,
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { render, waitFor } from '../../../tests/helpers/render';
|
||||
import { offlineDb } from '../../db/offlineDb';
|
||||
import type { Day, Trip } from '../../types';
|
||||
|
||||
const published = vi.hoisted(() => ({ calls: [] as unknown[][] }));
|
||||
|
||||
vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn(async () => ({ remove: vi.fn() })) } }));
|
||||
vi.mock('../../native/capabilities', () => ({ useNativeCapabilities: () => ({ caps: {} }) }));
|
||||
vi.mock('../../native/watch', () => ({
|
||||
applyWatchActions: vi.fn(async () => []),
|
||||
buildWatchSnapshot: vi.fn(),
|
||||
publishWatch: vi.fn(async () => {}),
|
||||
takeWatchActions: vi.fn(async () => []),
|
||||
watchActive: () => false,
|
||||
}));
|
||||
vi.mock('../../native/widgetMedia', () => ({
|
||||
widgetCover: vi.fn(async () => null),
|
||||
widgetWeather: vi.fn(async () => null),
|
||||
}));
|
||||
vi.mock('../../native/widgetOnline', () => ({
|
||||
atlasSummary: vi.fn(async () => null),
|
||||
collabSummary: vi.fn(async () => null),
|
||||
packingDetail: vi.fn(async () => null),
|
||||
}));
|
||||
vi.mock('../../native/widgets', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../native/widgets')>();
|
||||
return {
|
||||
...actual,
|
||||
widgetsActive: () => true,
|
||||
publishWidgets: vi.fn(async (...args: unknown[]) => {
|
||||
published.calls.push(args);
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
import NativeWidgetsSync from './NativeWidgetsSync';
|
||||
|
||||
const trip = {
|
||||
id: 7,
|
||||
title: 'Lisbon',
|
||||
start_date: '2026-11-06',
|
||||
end_date: '2026-11-08',
|
||||
is_archived: 0,
|
||||
} as unknown as Trip;
|
||||
const day = (id: number, n: number, date: string, name: string) =>
|
||||
({
|
||||
id,
|
||||
trip_id: 7,
|
||||
day_number: n,
|
||||
date,
|
||||
assignments: [{ id: id * 10, order_index: 0, place: { name, place_time: '10:00' } }],
|
||||
}) as unknown as Day;
|
||||
|
||||
describe('NativeWidgetsSync', () => {
|
||||
beforeEach(async () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
vi.setSystemTime(new Date(2026, 10, 7, 9, 0));
|
||||
published.calls = [];
|
||||
await offlineDb.trips.put(trip as never);
|
||||
await offlineDb.days.bulkPut([
|
||||
day(1, 1, '2026-11-06', 'Castle'),
|
||||
day(2, 2, '2026-11-07', 'Harbour'),
|
||||
day(3, 3, '2026-11-08', 'Market'),
|
||||
] as never);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers();
|
||||
await offlineDb.trips.clear();
|
||||
await offlineDb.days.clear();
|
||||
});
|
||||
|
||||
it('FE-NATIVE-WSYNC-001: writes today and every day ahead, so the widgets turn the day without the app', async () => {
|
||||
render(<NativeWidgetsSync />);
|
||||
await waitFor(() => expect(published.calls.length).toBeGreaterThan(0));
|
||||
const snapshot = published.calls[0][0] as {
|
||||
today: { date: string; stops: { name: string }[] } | null;
|
||||
days: { date: string; stops: { name: string }[] }[];
|
||||
};
|
||||
expect(snapshot.today).toMatchObject({ date: '2026-11-07', stops: [{ name: 'Harbour' }] });
|
||||
expect(snapshot.days.map((d) => [d.date, d.stops[0]?.name])).toEqual([
|
||||
['2026-11-07', 'Harbour'],
|
||||
['2026-11-08', 'Market'],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -25,11 +25,10 @@ import {
|
||||
liveFlightOf,
|
||||
pickTrip,
|
||||
publishWidgets,
|
||||
todayOf,
|
||||
snapshotDays,
|
||||
tripDayState,
|
||||
widgetTripChoices,
|
||||
widgetsActive,
|
||||
withBookings,
|
||||
type TripWidgetSnapshot,
|
||||
type WidgetLabels,
|
||||
} from '../../native/widgets';
|
||||
@@ -191,11 +190,15 @@ export default function NativeWidgetsSync(): null {
|
||||
const tripSnapshot = async (trip: Trip | null, context: SyncContext, atlas: WidgetAtlas | null) => {
|
||||
const days = trip ? await offlineDb.days.where('trip_id').equals(trip.id).toArray() : [];
|
||||
const extra = trip ? await tripExtras(trip, days, context) : null;
|
||||
const plain = trip
|
||||
? todayOf(trip, days, context.today, (n, m) => t('native.widget.dayOf', { n, m }), context.time)
|
||||
: null;
|
||||
const day = plain ? withBookings(plain, extra?.reservations ?? [], context.today, context.time) : null;
|
||||
return { day, days, extra, snapshot: buildSnapshot(trip, day, labels(t), { ...extra?.extras, atlas }) };
|
||||
// Today and the days after it: the widgets turn to the next day at midnight by themselves.
|
||||
const { today: day, ahead } = snapshotDays(trip, days, {
|
||||
reservations: extra?.reservations ?? [],
|
||||
from: context.today,
|
||||
dayLabel: (n, m) => t('native.widget.dayOf', { n, m }),
|
||||
formatTime: context.time,
|
||||
});
|
||||
const snapshot = buildSnapshot(trip, day, labels(t), { ...extra?.extras, atlas, days: ahead });
|
||||
return { day, days, extra, snapshot };
|
||||
};
|
||||
|
||||
/** The hero trip in full for the watch, with the ticks from it applied so far. */
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-PLANNER-DPTRANSPORT-001 to FE-PLANNER-DPTRANSPORT-021
|
||||
// FE-PLANNER-DPTRANSPORT-001 to FE-PLANNER-DPTRANSPORT-024
|
||||
import { render, screen, fireEvent, within } from '../../../tests/helpers/render'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
|
||||
@@ -329,4 +329,29 @@ describe('DayPlanSidebarTransportDetailModal', () => {
|
||||
await user.click(screen.getByRole('button', { name: 'Close' }))
|
||||
expect(setTransportDetail).toHaveBeenCalledWith(null)
|
||||
})
|
||||
|
||||
// #3122: a transport holding only times showed them without the day they fall on.
|
||||
it('FE-PLANNER-DPTRANSPORT-022: a booking holding only times names the date of its linked day', () => {
|
||||
seedStore(useTripStore, { days: [{ id: 4, trip_id: 1, day_number: 2, date: '2025-06-16' }] as never })
|
||||
const res = { ...flight(), day_id: 4, reservation_time: '09:15', reservation_end_time: '11:00', endpoints: [] } as Reservation
|
||||
render(<DayPlanSidebarTransportDetailModal {...makeProps({ transportDetail: res })} />)
|
||||
expect(screen.getByText('09:15 → 11:00').parentElement).toHaveTextContent(/Mon, Jun 16/)
|
||||
})
|
||||
|
||||
it('FE-PLANNER-DPTRANSPORT-023: an overnight booking names the arrival date too', () => {
|
||||
const res = { ...flight(), reservation_time: '2025-06-15T22:30:00', reservation_end_time: '2025-06-16T06:05:00' } as Reservation
|
||||
render(<DayPlanSidebarTransportDetailModal {...makeProps({ transportDetail: res })} />)
|
||||
expect(screen.getByText('22:30 → 06:05').parentElement).toHaveTextContent(/Sun, Jun 15 → Mon, Jun 16/)
|
||||
})
|
||||
|
||||
it('FE-PLANNER-DPTRANSPORT-024: in a right-to-left UI the overnight days read in order', () => {
|
||||
document.documentElement.dir = 'rtl'
|
||||
try {
|
||||
const res = { ...flight(), reservation_time: '2025-06-15T22:30:00', reservation_end_time: '2025-06-16T06:05:00' } as Reservation
|
||||
render(<DayPlanSidebarTransportDetailModal {...makeProps({ transportDetail: res })} />)
|
||||
expect(screen.getByText('22:30 → 06:05').parentElement).toHaveTextContent('Sun, Jun 15 ← Mon, Jun 16')
|
||||
} finally {
|
||||
document.documentElement.dir = ''
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -14,7 +14,9 @@ import { BOX, Eyebrow, Field, fs, toneColor, toneOf } from './bookings/bookingPa
|
||||
import { filesFor } from '../../utils/reservationFiles'
|
||||
import { bookingDayLabel, segmentCodeLabel } from './transportDetailModel'
|
||||
import { TransitLegs, transitSummary } from './bookings/transitParts'
|
||||
import type { Reservation } from '../../types'
|
||||
import { bookingDates } from './bookings/bookingsModel'
|
||||
import { flowText } from '../../utils/flowText'
|
||||
import type { Day, Reservation } from '../../types'
|
||||
|
||||
type Translate = (key: string, params?: Record<string, string | number>) => string
|
||||
|
||||
@@ -50,11 +52,12 @@ export function DayPlanSidebarTransportDetailModal({ transportDetail, ...rest }:
|
||||
function TransportDetailDialog({ res, setTransportDetail, onNavigateToFiles, onEdit, t, locale, timeFormat }: Omit<DayPlanSidebarTransportDetailModalProps, 'transportDetail'> & { res: Reservation }) {
|
||||
const titleId = useId()
|
||||
const allFiles = useTripStore(s => s.files)
|
||||
const days = useTripStore(s => s.days)
|
||||
const close = () => setTransportDetail(null)
|
||||
const meta = parseReservationMetadata(res)
|
||||
const transit = transitSummary(meta)
|
||||
const files = filesFor(res, allFiles || [])
|
||||
const when = whenOf(res, locale, timeFormat)
|
||||
const when = whenOf(res, days, locale, timeFormat)
|
||||
const cells = detailCells(res, meta, t)
|
||||
const confirmed = res.status === 'confirmed'
|
||||
|
||||
@@ -192,11 +195,18 @@ function detailCells(res: Reservation, meta: Record<string, unknown>, t: Transla
|
||||
return cells
|
||||
}
|
||||
|
||||
/** The booking's day and its time or time range, each empty when the booking has none. */
|
||||
function whenOf(res: Reservation, locale: string, timeFormat: string): { day: string; time: string } {
|
||||
const { date, time } = splitReservationDateTime(res.reservation_time)
|
||||
/**
|
||||
* The booking's calendar day (both, when it arrives on a later one) and its time or
|
||||
* time range, each empty when the booking has none. A booking holding only times
|
||||
* takes the date of the day it is linked to (#3122).
|
||||
*/
|
||||
function whenOf(res: Reservation, days: Day[], locale: string, timeFormat: string): { day: string; time: string } {
|
||||
const { time } = splitReservationDateTime(res.reservation_time)
|
||||
const { time: endTime } = splitReservationDateTime(res.reservation_end_time)
|
||||
const day = date ? bookingDayLabel(date, locale) : ''
|
||||
const dates = bookingDates(res, days || [])
|
||||
// An arrival date alone would read as the departure, so it only joins a start date.
|
||||
const span = dates.start ? [dates.start, dates.end !== dates.start ? dates.end : null].filter((d): d is string => !!d) : []
|
||||
const day = span.length > 0 ? flowText(span.map(d => bookingDayLabel(d, locale))) : ''
|
||||
const start = time ? formatTime(time, locale, timeFormat) : ''
|
||||
const end = endTime ? formatTime(endTime, locale, timeFormat) : ''
|
||||
return { day, time: start && end ? `${start} → ${end}` : start }
|
||||
|
||||
@@ -357,7 +357,7 @@ describe('TransitSearchPanel', () => {
|
||||
await user.click(fromInput)
|
||||
const picks = (await screen.findAllByRole('button', { name: /Hotel Adlon|Stop \d|Hostel/ })).map(b => b.textContent)
|
||||
expect(picks[0]).toBe('Hotel Adlon')
|
||||
expect(picks.slice(1)).toEqual(['Stop 1', 'Stop 2', 'Stop 3', 'Stop 4', 'Stop 5', 'Stop 6', 'Stop 7', 'Stop 8'])
|
||||
expect(picks.slice(1)).toEqual([...places.map(p => p.name), 'Later Hostel'])
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Hotel Adlon' }))
|
||||
expect(fromInput).toHaveValue('Hotel Adlon')
|
||||
@@ -744,7 +744,7 @@ describe('quick picks from the bookings of the day (#1506)', () => {
|
||||
const places = Array.from({ length: 12 }, (_, i) => buildPlace({ id: 100 + i, name: `P${i}`, lat: 52 + i / 100, lng: 13 }))
|
||||
const picks = buildQuickPicks(day, [day], places as any, [], dayBookingStops(day, [flight] as any))
|
||||
expect(picks.slice(0, 2).map(p => p.name)).toEqual(['FRA', 'BER Airport'])
|
||||
expect(picks).toHaveLength(2 + 8)
|
||||
expect(picks).toHaveLength(2 + places.length)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -8,7 +8,8 @@ import { transitApi } from '../../api/client'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { getDayBookendHotels } from '../../utils/dayOrder'
|
||||
import { getDayBookendHotels, isDayInAccommodationRange } from '../../utils/dayOrder'
|
||||
import { orderTransitStaysByDate } from './transitStayOrder'
|
||||
import type { Day, Place, Accommodation, Reservation } from '../../types'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { isCarrierTransport } from '../../utils/dayMerge'
|
||||
@@ -110,7 +111,11 @@ function fmtDuration(seconds: number, t: (k: string, p?: Record<string, string |
|
||||
|
||||
// ── quick picks ──────────────────────────────────────────────────────────────
|
||||
|
||||
const MAX_QUICK_PICKS = 8
|
||||
const MAX_OTHER_DAY_STAYS = 8
|
||||
|
||||
function pickedPlaceKey(p: PickedPlace): string {
|
||||
return JSON.stringify([p.name.trim().toLowerCase(), p.lat, p.lng])
|
||||
}
|
||||
|
||||
function stayPick(a: Accommodation): PickedPlace | null {
|
||||
return a.place_lat != null && a.place_lng != null && a.place_name ? { name: a.place_name, lat: a.place_lat, lng: a.place_lng } : null
|
||||
@@ -143,28 +148,30 @@ export function dayBookingStops(day: Pick<Day, 'id' | 'date'>, reservations: Res
|
||||
* starts in and the one it ends in come first and are never cut, since most
|
||||
* connections of a day begin or end there (#2538); the day's airports and
|
||||
* stations follow and are not cut either (#1506); then the day's own located
|
||||
* places and the trip's other stays, up to MAX_QUICK_PICKS.
|
||||
* places and remaining stays covering the day, without a limit. Only stays
|
||||
* outside the selected day's range are capped, nearest in nights first.
|
||||
*/
|
||||
export function buildQuickPicks(day: Day, days: Day[], places: Place[], accommodations: Accommodation[], bookingStops: PickedPlace[] = []): PickedPlace[] {
|
||||
const { morning, evening } = getDayBookendHotels(day, days, accommodations)
|
||||
const dayStays = [morning, evening].filter((a): a is Accommodation => a != null)
|
||||
const bookendStays = [morning, evening].filter((a): a is Accommodation => a != null)
|
||||
const dayStays = accommodations.filter(a => isDayInAccommodationRange(day, a.start_day_id, a.end_day_id, days))
|
||||
|
||||
const seen = new Set<string>()
|
||||
const unique = (p: PickedPlace | null): p is PickedPlace => {
|
||||
if (!p) return false
|
||||
const k = `${p.name}:${p.lat}`
|
||||
const k = pickedPlaceKey(p)
|
||||
if (seen.has(k)) return false
|
||||
seen.add(k)
|
||||
return true
|
||||
}
|
||||
|
||||
const stays = dayStays.map(stayPick).filter(unique)
|
||||
const stays = bookendStays.map(stayPick).filter(unique)
|
||||
const stations = bookingStops.filter(unique)
|
||||
const rest = [
|
||||
...places.map(p => (p.lat != null && p.lng != null ? { name: p.name, lat: p.lat, lng: p.lng } : null)),
|
||||
...accommodations.filter(a => !dayStays.includes(a)).map(stayPick),
|
||||
].filter(unique)
|
||||
return [...stays, ...stations, ...rest.slice(0, MAX_QUICK_PICKS)]
|
||||
const dayPlaces = places.map(p => (p.lat != null && p.lng != null ? { name: p.name, lat: p.lat, lng: p.lng } : null)).filter(unique)
|
||||
const remainingDayStays = dayStays.map(stayPick).filter(unique)
|
||||
const otherStays = orderTransitStaysByDate(day, days, accommodations.filter(a => !dayStays.includes(a)))
|
||||
.map(stayPick).filter(unique).slice(0, MAX_OTHER_DAY_STAYS)
|
||||
return [...stays, ...stations, ...dayPlaces, ...remainingDayStays, ...otherStays]
|
||||
}
|
||||
|
||||
// ── from/to stop picker ──────────────────────────────────────────────────────
|
||||
@@ -221,6 +228,8 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
|
||||
const [results, setResults] = useState<TransitPlaceResult[]>([])
|
||||
const [open, setOpen] = useState(false)
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
// Ignore lookups superseded by another query, a saved pick, or leaving this day.
|
||||
const requestId = useRef(0)
|
||||
const rootRef = useRef<HTMLDivElement>(null)
|
||||
const fieldRef = useRef<HTMLDivElement>(null)
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
@@ -235,21 +244,45 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
|
||||
return () => document.removeEventListener('mousedown', close)
|
||||
}, [])
|
||||
|
||||
useEffect(() => () => { if (debounceRef.current) clearTimeout(debounceRef.current) }, [])
|
||||
useEffect(() => () => {
|
||||
requestId.current += 1
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current)
|
||||
}, [])
|
||||
|
||||
const search = (q: string) => {
|
||||
const id = ++requestId.current
|
||||
setText(q)
|
||||
setResults([])
|
||||
onPick(null)
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current)
|
||||
if (q.trim().length < 2) { setResults([]); return }
|
||||
if (q.trim().length < 2) return
|
||||
debounceRef.current = setTimeout(() => {
|
||||
transitApi.geocode(q, { lang: language, near: near || undefined })
|
||||
.then((d: { results: TransitPlaceResult[] }) => setResults(d.results || []))
|
||||
.catch(() => setResults([]))
|
||||
.then((d: { results: TransitPlaceResult[] }) => { if (id === requestId.current) setResults(d.results || []) })
|
||||
.catch(() => { if (id === requestId.current) setResults([]) })
|
||||
}, 300)
|
||||
}
|
||||
|
||||
const display = value ? value.name : text
|
||||
const query = text.trim().toLowerCase()
|
||||
const saved = quickPicks.filter(p => p.name.toLowerCase().includes(query))
|
||||
const seen = new Set(saved.map(pickedPlaceKey))
|
||||
const external = results.filter(p => {
|
||||
const key = pickedPlaceKey(p)
|
||||
if (seen.has(key)) return false
|
||||
seen.add(key)
|
||||
return true
|
||||
})
|
||||
const suggestions: (PickedPlace & { area?: string | null })[] = value ? [] : [...saved, ...external]
|
||||
|
||||
const pick = (p: PickedPlace) => {
|
||||
requestId.current += 1
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current)
|
||||
onPick({ name: p.name, lat: p.lat, lng: p.lng })
|
||||
setText('')
|
||||
setResults([])
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={rootRef} style={{ position: 'relative', flex: 1, minWidth: 0 }}>
|
||||
@@ -267,34 +300,23 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
|
||||
style={{ border: 0, background: 'none', outline: 'none', fontSize: 'calc(13px * var(--fs-scale-body, 1))', width: '100%', fontFamily: 'inherit' }}
|
||||
/>
|
||||
</div>
|
||||
{open && listPos && (results.length > 0 || (!value && text.trim().length < 2 && quickPicks.length > 0)) && createPortal(
|
||||
{open && listPos && suggestions.length > 0 && createPortal(
|
||||
// On the page rather than inside the dialog, so a dialog that scrolls or clips
|
||||
// its content cannot cut the list off before anything is typed.
|
||||
<div ref={listRef} className="bg-surface-card border border-edge z-[var(--z-toast)]" style={{ position: 'fixed', left: listPos.left, width: listPos.width, ...(listPos.above ? { bottom: listPos.bottom } : { top: listPos.top }), borderRadius: 10, boxShadow: 'var(--shadow-dropdown)', overflow: 'hidden', maxHeight: listPos.maxHeight, overflowY: 'auto' }}>
|
||||
{results.length > 0
|
||||
? results.map((r, i) => (
|
||||
<button type="button" key={i} onClick={() => { onPick({ name: r.name, lat: r.lat, lng: r.lng }); setText(''); setResults([]); setOpen(false) }}
|
||||
className="text-content"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'start', padding: '8px 10px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}
|
||||
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
|
||||
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
|
||||
<MapPin size={13} className="text-content-faint" style={{ flexShrink: 0 }} />
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{r.name}
|
||||
{r.area && <span className="ms-1.5 text-content-faint">{r.area}</span>}
|
||||
</span>
|
||||
</button>
|
||||
))
|
||||
: quickPicks.map((p, i) => (
|
||||
<button type="button" key={i} onClick={() => { onPick(p); setText(''); setOpen(false) }}
|
||||
className="text-content"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'start', padding: '8px 10px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}
|
||||
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
|
||||
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
|
||||
<MapPin size={13} className="text-content-faint" style={{ flexShrink: 0 }} />
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.name}</span>
|
||||
</button>
|
||||
))}
|
||||
{suggestions.map(r => (
|
||||
<button type="button" key={pickedPlaceKey(r)} onClick={() => pick(r)}
|
||||
className="text-content"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'start', padding: '8px 10px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}
|
||||
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
|
||||
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
|
||||
<MapPin size={13} className="text-content-faint" style={{ flexShrink: 0 }} />
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{r.name}
|
||||
{r.area && <span className="ms-1.5 text-content-faint">{r.area}</span>}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,684 @@
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { buildAssignment, buildDay, buildPlace, buildTrip, buildUser } from '../../../tests/helpers/factories';
|
||||
import { buildPlanner } from '../../../tests/helpers/mobileTrip';
|
||||
import { act, fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import MTransportFormSheet from '../../mobile/screens/trip/sheets/MTransportFormSheet';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import type { Accommodation, AssignmentsMap, Day, Place } from '../../types';
|
||||
import type { TransitPrefill } from './transitLeg';
|
||||
import { TransportModal } from './TransportModal';
|
||||
|
||||
// Keep the real day selectors, wrappers and shared stop picker. Only the external
|
||||
// geocoder is controlled: a saved private place need not exist in that service.
|
||||
const { geocode, plan } = vi.hoisted(() => ({ geocode: vi.fn(), plan: vi.fn() }));
|
||||
vi.mock('../../api/client', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../api/client')>()),
|
||||
transitApi: { geocode, plan },
|
||||
}));
|
||||
|
||||
type Surface = 'desktop' | 'phone';
|
||||
interface Fixture {
|
||||
days: Day[];
|
||||
places: Place[];
|
||||
assignments: AssignmentsMap;
|
||||
accommodations: Accommodation[];
|
||||
transitPrefill?: TransitPrefill;
|
||||
selectedDayId?: number;
|
||||
}
|
||||
|
||||
function fixture(): Fixture {
|
||||
const days = [
|
||||
buildDay({ id: 101, trip_id: 1, day_number: 1, date: '2027-06-01', title: 'First day' }),
|
||||
buildDay({ id: 205, trip_id: 1, day_number: 2, date: '2027-06-02', title: 'Second day' }),
|
||||
buildDay({ id: 309, trip_id: 1, day_number: 3, date: '2027-06-03', title: 'Empty day' }),
|
||||
];
|
||||
const places = ['First private stop', 'Second private stop', 'Shared private stop'].map((name, i) =>
|
||||
buildPlace({ id: 11 + i, trip_id: 1, name, lat: 52.5 + i / 100, lng: 13.4 })
|
||||
);
|
||||
const visit = (dayId: number, p: Place, order: number) =>
|
||||
buildAssignment({ day_id: dayId, place_id: p.id, place: p, order_index: order });
|
||||
return {
|
||||
days,
|
||||
places,
|
||||
assignments: {
|
||||
'101': [visit(101, places[0], 0), visit(101, places[2], 1)],
|
||||
'205': [visit(205, places[1], 0), visit(205, places[2], 1)],
|
||||
'309': [],
|
||||
},
|
||||
accommodations: [],
|
||||
};
|
||||
}
|
||||
|
||||
function buildStay(id: number, name: string, start: number, end: number): Accommodation {
|
||||
return {
|
||||
id,
|
||||
trip_id: 1,
|
||||
place_id: 1000 + id,
|
||||
start_day_id: start,
|
||||
end_day_id: end,
|
||||
place_name: name,
|
||||
place_lat: 52 + id / 1000,
|
||||
place_lng: 13,
|
||||
} as Accommodation;
|
||||
}
|
||||
|
||||
function longTripFixture(): Fixture {
|
||||
const days = Array.from({ length: 30 }, (_, i) =>
|
||||
buildDay({
|
||||
id: 5000 - i * 97,
|
||||
trip_id: 1,
|
||||
day_number: i + 1,
|
||||
date: new Date(Date.UTC(2027, 2, i + 1)).toISOString().slice(0, 10),
|
||||
title: `Day ${i + 1}`,
|
||||
})
|
||||
);
|
||||
days[28] = { ...days[28], date: null };
|
||||
const stay = (id: number, name: string, start: number, end: number) =>
|
||||
buildStay(id, name, days[start - 1].id, days[end - 1].id);
|
||||
const nearby = Array.from({ length: 4 }, (_, i) => [
|
||||
stay(10 + i * 2, `Nearby before ${i + 1}`, 18 - i, 20 - i),
|
||||
stay(11 + i * 2, `Nearby after ${i + 1}`, 22 + i, 24 + i),
|
||||
]).flat();
|
||||
return {
|
||||
days,
|
||||
places: [],
|
||||
assignments: {},
|
||||
selectedDayId: days[20].id,
|
||||
accommodations: [
|
||||
stay(1, 'First-week hotel created first', 1, 7),
|
||||
stay(2, 'Undated hotel', 29, 30),
|
||||
...nearby.slice().reverse(),
|
||||
{ ...nearby[0], id: 99 },
|
||||
stay(100, 'Morning hotel', 20, 21),
|
||||
stay(101, 'Evening hotel', 21, 22),
|
||||
...Array.from({ length: 10 }, (_, i) => stay(200 + i, `Current stay ${i + 1}`, 19, 23)),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function Harness({ surface, data }: { surface: Surface; data: Fixture }) {
|
||||
const { t } = useTranslation();
|
||||
if (surface === 'phone') {
|
||||
const planner = buildPlanner({
|
||||
t,
|
||||
trip: buildTrip({ id: 1 }),
|
||||
days: data.days,
|
||||
places: data.places,
|
||||
assignments: data.assignments,
|
||||
storedAssignments: data.assignments,
|
||||
tripAccommodations: data.accommodations,
|
||||
showTransportModal: true,
|
||||
transportModalDayId: data.selectedDayId ?? 101,
|
||||
transportModalAutomated: true,
|
||||
transitPrefill: data.transitPrefill ?? null,
|
||||
});
|
||||
return <MTransportFormSheet planner={planner} onOpenExpense={vi.fn()} />;
|
||||
}
|
||||
return (
|
||||
<TransportModal
|
||||
isOpen
|
||||
onClose={vi.fn()}
|
||||
onSave={vi.fn()}
|
||||
reservation={null}
|
||||
days={data.days}
|
||||
selectedDayId={data.selectedDayId ?? 101}
|
||||
initialAutomated
|
||||
places={data.places}
|
||||
assignments={data.assignments}
|
||||
accommodations={data.accommodations}
|
||||
transitPrefill={data.transitPrefill}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const inputs = () => screen.getAllByPlaceholderText('Search stop or station…');
|
||||
async function switchDay(user: ReturnType<typeof userEvent.setup>, current: string, next: string) {
|
||||
await user.click(screen.getByText(current));
|
||||
await user.click(screen.getByRole('button', { name: new RegExp(`^${next}`) }));
|
||||
}
|
||||
const pickNames = () => screen.queryAllByRole('button', { name: /private stop/ }).map((b) => b.textContent);
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
geocode.mockReset().mockResolvedValue({ results: [] });
|
||||
plan.mockReset();
|
||||
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
|
||||
seedStore(useTripStore, { trip: buildTrip({ id: 1 }), reservations: [] });
|
||||
});
|
||||
|
||||
describe.each<Surface>(['desktop', 'phone'])('Automated transport day selection: %s', (surface) => {
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(window, 'innerWidth', { configurable: true, value: surface === 'phone' ? 390 : 1440 });
|
||||
fireEvent(window, new Event('resize'));
|
||||
});
|
||||
|
||||
it('scopes both pickers by day id and keeps a shared place when switching back and forth', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<Harness surface={surface} data={fixture()} />);
|
||||
await user.click(inputs()[0]);
|
||||
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
await user.click(inputs()[1]);
|
||||
expect(pickNames()).toEqual(['Second private stop', 'Shared private stop']);
|
||||
await switchDay(user, 'Second day', 'First day');
|
||||
await user.click(inputs()[0]);
|
||||
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
|
||||
});
|
||||
|
||||
it('keeps all nine eligible day places available in the dropdown', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const stops = Array.from({ length: 9 }, (_, i) => buildPlace({ id: 50 + i, name: `Day stop ${i + 1}` }));
|
||||
data.places.push(...stops);
|
||||
data.assignments['101'] = stops.map((p, i) =>
|
||||
buildAssignment({ day_id: 101, place_id: p.id, place: p, order_index: i })
|
||||
);
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
await user.click(inputs()[0]);
|
||||
expect(screen.queryAllByRole('button', { name: /^Day stop/ }).map((b) => b.textContent)).toEqual(
|
||||
stops.map((p) => p.name)
|
||||
);
|
||||
expect(screen.queryByRole('button', { name: 'Second private stop' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('finds an assigned private place when the geocoder has no result', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<Harness surface={surface} data={fixture()} />);
|
||||
await user.click(inputs()[0]);
|
||||
await user.type(inputs()[0], 'First private');
|
||||
await waitFor(() => expect(geocode).toHaveBeenCalled());
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(screen.queryByRole('button', { name: 'First private stop' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Second private stop' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('ranks matching saved places before external matches and deduplicates by name and both coordinates', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const saved = data.places[0];
|
||||
const other = { name: 'External private stop', lat: 52.8, lng: 13.8, area: 'Berlin' };
|
||||
geocode.mockResolvedValue({
|
||||
results: [
|
||||
other,
|
||||
{ name: saved.name.toUpperCase(), lat: saved.lat, lng: saved.lng, area: 'Duplicate' },
|
||||
{ ...other },
|
||||
{ name: saved.name, lat: saved.lat, lng: 13.9, area: 'Other longitude' },
|
||||
],
|
||||
});
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
await user.type(inputs()[0], 'private');
|
||||
await screen.findByRole('button', { name: /External private stop/ });
|
||||
const rows = screen.getAllByRole('button', { name: /private stop/i });
|
||||
expect(rows.map((row) => row.textContent)).toEqual([
|
||||
'First private stop',
|
||||
'Shared private stop',
|
||||
'External private stopBerlin',
|
||||
'First private stopOther longitude',
|
||||
]);
|
||||
expect(geocode).toHaveBeenCalledTimes(1);
|
||||
await user.click(rows[0]);
|
||||
expect(inputs()[0]).toHaveValue(saved.name);
|
||||
});
|
||||
|
||||
it('limits only other-day stays, keeping current hotels, terminals and every selected-day place first', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const stops = Array.from({ length: 12 }, (_, i) => buildPlace({ id: 50 + i, name: `Day stop ${i + 1}` }));
|
||||
// A same-name stop at a different longitude must not be dropped as a duplicate.
|
||||
stops.push(buildPlace({ id: 62, name: stops[0].name, lat: stops[0].lat, lng: 10 }));
|
||||
data.places.push(...stops);
|
||||
data.assignments['101'] = stops.map((p, i) =>
|
||||
buildAssignment({ day_id: 101, place_id: p.id, place: p, order_index: i })
|
||||
);
|
||||
data.accommodations = Array.from(
|
||||
{ length: 12 },
|
||||
(_, i) =>
|
||||
({
|
||||
id: 70 + i,
|
||||
trip_id: 1,
|
||||
place_id: 70 + i,
|
||||
start_day_id: i === 0 ? 101 : 205,
|
||||
end_day_id: i === 0 ? 101 : 205,
|
||||
place_name: i === 0 ? 'Current hotel' : `Other hotel ${i}`,
|
||||
place_lat: 52 + i / 100,
|
||||
place_lng: 13,
|
||||
}) as Accommodation
|
||||
);
|
||||
// Duplicate stays must not consume another slot of the other-day allowance.
|
||||
data.accommodations.splice(2, 0, { ...data.accommodations[1], id: 90 });
|
||||
seedStore(useTripStore, {
|
||||
reservations: [
|
||||
{
|
||||
id: 81,
|
||||
trip_id: 1,
|
||||
type: 'train',
|
||||
day_id: 101,
|
||||
end_day_id: 101,
|
||||
endpoints: [{ role: 'from', name: 'Current terminal', lat: 52, lng: 13, local_date: '2027-06-01' }],
|
||||
},
|
||||
] as ReturnType<typeof useTripStore.getState>['reservations'],
|
||||
});
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
for (const input of inputs()) {
|
||||
await user.click(input);
|
||||
const rows = screen.getAllByRole('button', { name: /Current hotel|Current terminal|Day stop|Other hotel/ });
|
||||
expect(rows.map((row) => row.textContent)).toEqual([
|
||||
'Current hotel',
|
||||
'Current terminal',
|
||||
...stops.map((p) => p.name),
|
||||
...Array.from({ length: 8 }, (_, i) => `Other hotel ${i + 1}`),
|
||||
]);
|
||||
expect(screen.queryByRole('button', { name: 'Second private stop' })).not.toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps more than eight current-day hotels selectable and searchable despite earlier other-day stays', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const current = Array.from({ length: 12 }, (_, i) => buildStay(200 + i, `Current day hotel ${i + 1}`, 101, 101));
|
||||
const other = Array.from({ length: 9 }, (_, i) => buildStay(100 + i, `Other day hotel ${i + 1}`, 205, 205));
|
||||
data.accommodations = [
|
||||
...other,
|
||||
...current,
|
||||
{ ...current[8], id: 999 },
|
||||
{ ...buildStay(300, 'Unlocated current hotel', 101, 101), place_lat: null },
|
||||
];
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
for (const input of inputs()) {
|
||||
await user.click(input);
|
||||
expect(screen.getAllByRole('button', { name: /^Current day hotel/ }).map((b) => b.textContent)).toEqual(
|
||||
current.map((a) => a.place_name)
|
||||
);
|
||||
expect(screen.getAllByRole('button', { name: /^Other day hotel/ }).map((b) => b.textContent)).toEqual(
|
||||
other.slice(0, 8).map((a) => a.place_name)
|
||||
);
|
||||
expect(screen.queryByRole('button', { name: 'Unlocated current hotel' })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'First private stop' })).toBeInTheDocument();
|
||||
}
|
||||
await user.type(inputs()[1], 'current day hotel 12');
|
||||
await user.click(screen.getByRole('button', { name: 'Current day hotel 12' }));
|
||||
expect(inputs()[1]).toHaveValue('Current day hotel 12');
|
||||
});
|
||||
|
||||
it('offers Hotel 09 on Day 3 for the manual-review booking pattern without using mirrored day places', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const a = buildStay(1, 'Hotel A — first night', 101, 205);
|
||||
const b = buildStay(2, 'Hotel B — second night', 205, 309);
|
||||
const sameDay = Array.from({ length: 9 }, (_, i) =>
|
||||
buildStay(3 + i, `Other night hotel ${String(i + 1).padStart(2, '0')}`, 309, 309)
|
||||
);
|
||||
data.accommodations = [a, b, ...sameDay];
|
||||
// Days hides accommodation-owned mirror assignments: hotels must come from the stays themselves.
|
||||
data.assignments['309'] = [];
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
await switchDay(user, 'First day', 'Empty day');
|
||||
for (const input of inputs()) {
|
||||
await user.click(input);
|
||||
expect(
|
||||
screen.getAllByRole('button', { name: /Hotel A|Hotel B|Other night hotel/ }).map((row) => row.textContent)
|
||||
).toEqual([b.place_name, ...sameDay.map((stay) => stay.place_name), a.place_name]);
|
||||
}
|
||||
await user.click(screen.getByRole('button', { name: 'Other night hotel 09' }));
|
||||
expect(inputs()[1]).toHaveValue('Other night hotel 09');
|
||||
});
|
||||
|
||||
it('keeps multi-night stays and checkout-day stays uncapped, with bookends before the other current stays', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const other = Array.from({ length: 9 }, (_, i) => buildStay(100 + i, `Future hotel ${i + 1}`, 309, 309));
|
||||
const spanning = Array.from({ length: 10 }, (_, i) => buildStay(200 + i, `Multi-night hotel ${i + 1}`, 101, 309));
|
||||
const checkout = buildStay(300, 'Checks out today', 101, 205);
|
||||
const checkin = buildStay(301, 'Checks in today', 205, 309);
|
||||
data.accommodations = [...other, ...spanning, checkout, checkin];
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
await user.click(inputs()[0]);
|
||||
expect(
|
||||
screen
|
||||
.getAllByRole('button', { name: /Multi-night hotel|Checks (in|out) today|Future hotel/ })
|
||||
.map((row) => row.textContent)
|
||||
).toEqual([
|
||||
spanning[0].place_name,
|
||||
checkin.place_name,
|
||||
...spanning.slice(1).map((stay) => stay.place_name),
|
||||
checkout.place_name,
|
||||
...other.slice(0, 8).map((stay) => stay.place_name),
|
||||
]);
|
||||
expect(screen.queryByRole('button', { name: 'Future hotel 9' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not let a first-week hotel take a Day 21 slot from eight closer stays on a 30-day trip', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<Harness surface={surface} data={longTripFixture()} />);
|
||||
for (const input of inputs()) {
|
||||
await user.click(input);
|
||||
expect(screen.queryByRole('button', { name: 'First-week hotel created first' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Undated hotel' })).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen
|
||||
.getAllByRole('button', { name: /Morning hotel|Evening hotel|Current stay|Nearby/ })
|
||||
.map((row) => row.textContent)
|
||||
).toEqual([
|
||||
'Morning hotel',
|
||||
'Evening hotel',
|
||||
...Array.from({ length: 10 }, (_, i) => `Current stay ${i + 1}`),
|
||||
...Array.from({ length: 4 }, (_, i) => [`Nearby before ${i + 1}`, `Nearby after ${i + 1}`]).flat(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it('puts undated stays last and orders identical dated intervals by stay id independently of input order', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = longTripFixture();
|
||||
const dated = data.accommodations.find((stay) => stay.place_name === 'Nearby after 1');
|
||||
if (!dated) throw new Error('Missing dated fixture');
|
||||
const undated = data.accommodations.find((stay) => stay.place_name === 'Undated hotel');
|
||||
if (!undated) throw new Error('Missing undated fixture');
|
||||
data.accommodations = [
|
||||
undated,
|
||||
{ ...dated, id: 90, place_name: 'Same dates higher id', place_lng: 14 },
|
||||
{ ...dated, id: 80, place_name: 'Same dates lower id', place_lng: 15 },
|
||||
];
|
||||
const view = render(<Harness surface={surface} data={data} />);
|
||||
await user.click(inputs()[0]);
|
||||
const names = () =>
|
||||
screen.getAllByRole('button', { name: /Same dates|Undated hotel/ }).map((row) => row.textContent);
|
||||
expect(names()).toEqual(['Same dates lower id', 'Same dates higher id', 'Undated hotel']);
|
||||
view.rerender(
|
||||
<Harness surface={surface} data={{ ...data, accommodations: data.accommodations.slice().reverse() }} />
|
||||
);
|
||||
expect(names()).toEqual(['Same dates lower id', 'Same dates higher id', 'Undated hotel']);
|
||||
});
|
||||
|
||||
it('refreshes an open dropdown after places are added, removed and reordered', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const view = render(<Harness surface={surface} data={data} />);
|
||||
await user.click(inputs()[0]);
|
||||
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
|
||||
const added = buildPlace({ id: 99, name: 'Added private stop' });
|
||||
const next = {
|
||||
...data,
|
||||
places: [...data.places, added],
|
||||
assignments: {
|
||||
...data.assignments,
|
||||
'101': [
|
||||
{ ...data.assignments['101'][1], order_index: 2 },
|
||||
buildAssignment({ day_id: 101, place_id: added.id, place: added, order_index: 0 }),
|
||||
],
|
||||
},
|
||||
};
|
||||
view.rerender(<Harness surface={surface} data={next} />);
|
||||
expect(pickNames()).toEqual(['Added private stop', 'Shared private stop']);
|
||||
});
|
||||
|
||||
it('keeps place membership tied to ids when days and their dates are reordered', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const view = render(<Harness surface={surface} data={data} />);
|
||||
const reordered = {
|
||||
...data,
|
||||
days: [
|
||||
{ ...data.days[1], day_number: 1, date: data.days[0].date },
|
||||
{ ...data.days[0], day_number: 2, date: data.days[1].date },
|
||||
data.days[2],
|
||||
],
|
||||
};
|
||||
view.rerender(<Harness surface={surface} data={reordered} />);
|
||||
await user.click(inputs()[0]);
|
||||
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
await user.click(inputs()[0]);
|
||||
expect(pickNames()).toEqual(['Second private stop', 'Shared private stop']);
|
||||
});
|
||||
|
||||
it('does not retain endpoints from an unrelated day after selecting from and to', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
// Make the first day's two endpoints exclusive to that day.
|
||||
data.assignments['205'] = [data.assignments['205'][0]];
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
await user.click(inputs()[0]);
|
||||
await user.click(screen.getByRole('button', { name: 'First private stop' }));
|
||||
await user.click(inputs()[1]);
|
||||
await user.click(screen.getByRole('button', { name: 'Shared private stop' }));
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
|
||||
});
|
||||
|
||||
it('clears search state when changing days so the next day offers its own places', async () => {
|
||||
const user = userEvent.setup();
|
||||
geocode.mockResolvedValue({ results: [{ name: 'Old external station', lat: 52, lng: 13, area: null }] });
|
||||
render(<Harness surface={surface} data={fixture()} />);
|
||||
await user.type(inputs()[0], 'Old station');
|
||||
await screen.findByRole('button', { name: 'Old external station' });
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
await user.click(inputs()[0]);
|
||||
expect(screen.queryByRole('button', { name: 'Old external station' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Second private stop' })).toBeInTheDocument();
|
||||
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
|
||||
});
|
||||
|
||||
it('scopes day-plan endpoint, time and walk prefills to the opening day', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
data.transitPrefill = {
|
||||
from: { name: 'Walk end', lat: 52.5, lng: 13.4 },
|
||||
to: { name: 'Next walk start', lat: 52.6, lng: 13.5 },
|
||||
time: '12:15',
|
||||
walk: {
|
||||
dayId: 101,
|
||||
fromWalk: 'Old town',
|
||||
toWalk: 'Harbour',
|
||||
ends: '12:15',
|
||||
endsNextDay: false,
|
||||
endsAtLeast: false,
|
||||
nextStarts: '13:00',
|
||||
},
|
||||
};
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['Walk end', 'Next walk start']);
|
||||
expect(screen.getByTestId('transit-walk-end')).toHaveTextContent('Old town');
|
||||
expect(screen.getByDisplayValue('12:15')).toBeInTheDocument();
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
|
||||
expect(screen.queryByTestId('transit-walk-end')).not.toBeInTheDocument();
|
||||
expect(screen.queryByDisplayValue('12:15')).not.toBeInTheDocument();
|
||||
await switchDay(user, 'Second day', 'First day');
|
||||
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['Walk end', 'Next walk start']);
|
||||
expect(screen.getByTestId('transit-walk-end')).toHaveTextContent('Old town');
|
||||
});
|
||||
|
||||
it('drops old itineraries when changing the day', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const stop = (name: string, time: string) => ({
|
||||
name,
|
||||
lat: 52.5,
|
||||
lng: 13.4,
|
||||
time,
|
||||
scheduledTime: null,
|
||||
track: null,
|
||||
});
|
||||
plan.mockResolvedValue({
|
||||
itineraries: [
|
||||
{
|
||||
startTime: '2027-06-01T07:00:00Z',
|
||||
endTime: '2027-06-01T07:30:00Z',
|
||||
duration: 1800,
|
||||
transfers: 0,
|
||||
walkSeconds: 0,
|
||||
legs: [
|
||||
{
|
||||
mode: 'SUBWAY',
|
||||
from: stop('A', '2027-06-01T07:00:00Z'),
|
||||
to: stop('B', '2027-06-01T07:30:00Z'),
|
||||
duration: 1800,
|
||||
distance: null,
|
||||
headsign: null,
|
||||
line: 'U88',
|
||||
lineColor: null,
|
||||
lineTextColor: null,
|
||||
agency: null,
|
||||
intermediateStops: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
await user.click(inputs()[0]);
|
||||
await user.click(screen.getByRole('button', { name: 'First private stop' }));
|
||||
await user.click(inputs()[1]);
|
||||
await user.click(screen.getByRole('button', { name: 'Shared private stop' }));
|
||||
await user.click(screen.getByRole('button', { name: /^Search$/ }));
|
||||
await screen.findByText('U88');
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
expect(screen.queryByText('U88')).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Add to day' })).not.toBeInTheDocument();
|
||||
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
|
||||
});
|
||||
|
||||
it('ignores an old geocoder response after the day changes', async () => {
|
||||
const user = userEvent.setup();
|
||||
let finish: (value: { results: { name: string; lat: number; lng: number; area: null }[] }) => void = () => {
|
||||
throw new Error('lookup not started');
|
||||
};
|
||||
geocode.mockReturnValueOnce(
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
})
|
||||
);
|
||||
render(<Harness surface={surface} data={fixture()} />);
|
||||
await user.type(inputs()[0], 'Old station');
|
||||
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(1));
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
await user.click(inputs()[0]);
|
||||
await act(async () => {
|
||||
finish({ results: [{ name: 'Late old station', lat: 52, lng: 13, area: null }] });
|
||||
});
|
||||
expect(screen.queryByRole('button', { name: 'Late old station' })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Second private stop' })).toBeInTheDocument();
|
||||
expect(inputs()[0]).toHaveValue('');
|
||||
});
|
||||
|
||||
it('keeps the newest search results when an older lookup answers last', async () => {
|
||||
type Answer = { results: { name: string; lat: number; lng: number; area: null }[] };
|
||||
const pending: ((value: Answer) => void)[] = [];
|
||||
geocode.mockImplementation(() => new Promise<Answer>((resolve) => pending.push(resolve)));
|
||||
render(<Harness surface={surface} data={fixture()} />);
|
||||
fireEvent.focus(inputs()[0]);
|
||||
fireEvent.change(inputs()[0], { target: { value: 'Old' } });
|
||||
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(1));
|
||||
fireEvent.change(inputs()[0], { target: { value: 'New' } });
|
||||
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(2));
|
||||
await act(async () => {
|
||||
pending[1]({ results: [{ name: 'New station', lat: 52.5, lng: 13.4, area: null }] });
|
||||
});
|
||||
await act(async () => {
|
||||
pending[0]({ results: [{ name: 'Old station', lat: 52.6, lng: 13.5, area: null }] });
|
||||
});
|
||||
expect(screen.getByRole('button', { name: 'New station' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Old station' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('ignores a superseded geocoder response after a saved place is picked', async () => {
|
||||
const user = userEvent.setup();
|
||||
let finish: (value: { results: { name: string; lat: number; lng: number; area: null }[] }) => void = () => {
|
||||
throw new Error('lookup not started');
|
||||
};
|
||||
geocode.mockReturnValueOnce(
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
})
|
||||
);
|
||||
render(<Harness surface={surface} data={fixture()} />);
|
||||
fireEvent.change(inputs()[0], { target: { value: 'Old' } });
|
||||
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(1));
|
||||
fireEvent.change(inputs()[0], { target: { value: 'First private' } });
|
||||
fireEvent.focus(inputs()[0]);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'First private stop' }));
|
||||
await act(async () => {
|
||||
finish({ results: [{ name: 'Superseded station', lat: 52, lng: 13, area: null }] });
|
||||
});
|
||||
await user.clear(inputs()[0]);
|
||||
expect(screen.queryByRole('button', { name: 'Superseded station' })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'First private stop' })).toBeInTheDocument();
|
||||
expect(geocode).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('offers no unrelated regular places on an empty day', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<Harness surface={surface} data={fixture()} />);
|
||||
await switchDay(user, 'First day', 'Empty day');
|
||||
await user.click(inputs()[0]);
|
||||
expect(pickNames()).toEqual([]);
|
||||
});
|
||||
|
||||
it('offers the active stay and other trip stays intentionally, even on a booking-only day', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
data.assignments['101'] = [];
|
||||
const stay = (id: number, name: string, dayId: number): Accommodation =>
|
||||
({
|
||||
id,
|
||||
trip_id: 1,
|
||||
place_id: id,
|
||||
start_day_id: dayId,
|
||||
end_day_id: dayId,
|
||||
place_name: name,
|
||||
place_lat: 52 + id / 100,
|
||||
place_lng: 13,
|
||||
}) as Accommodation;
|
||||
data.accommodations = [stay(70, 'Current hotel', 101), stay(71, 'Later hotel', 205)];
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
await user.click(inputs()[0]);
|
||||
expect(screen.getByRole('button', { name: 'Current hotel' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Later hotel' })).toBeInTheDocument();
|
||||
expect(pickNames()).toEqual([]);
|
||||
});
|
||||
|
||||
it('offers only the selected day transport terminals on a transport-only day', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
data.assignments['101'] = [];
|
||||
const endpoint = (role: 'from' | 'to', name: string, date: string) => ({
|
||||
role,
|
||||
name,
|
||||
lat: 52,
|
||||
lng: 13,
|
||||
local_date: date,
|
||||
});
|
||||
seedStore(useTripStore, {
|
||||
reservations: [
|
||||
{
|
||||
id: 81,
|
||||
trip_id: 1,
|
||||
type: 'train',
|
||||
day_id: 101,
|
||||
end_day_id: 205,
|
||||
endpoints: [
|
||||
endpoint('from', 'First terminal', '2027-06-01'),
|
||||
endpoint('to', 'Second terminal', '2027-06-02'),
|
||||
],
|
||||
},
|
||||
] as ReturnType<typeof useTripStore.getState>['reservations'],
|
||||
});
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
await user.click(inputs()[0]);
|
||||
expect(screen.getByRole('button', { name: 'First terminal' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Second terminal' })).not.toBeInTheDocument();
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
await user.click(inputs()[0]);
|
||||
expect(screen.getByRole('button', { name: 'Second terminal' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'First terminal' })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -20,6 +20,7 @@ import type { TripMember } from '../Budget/BudgetPanelMemberChips'
|
||||
import type { BookingExpenseRequest } from './BookingCostsSection.types'
|
||||
import type { BookingReviewDraft } from './parsedItemToDraft'
|
||||
import TransitSearchPanel from './TransitSearchPanel'
|
||||
import { getTransitDayPlaces } from './transitDayPlaces'
|
||||
import type { TransitPrefill } from './transitLeg'
|
||||
import { BookingDialogHeader, StatusPill } from './bookings/BookingDialogShell'
|
||||
import { DialogShell, DialogSection, DialogFooter, FooterSpacer, DialogButton, DeleteButton } from '../shared/DialogShell'
|
||||
@@ -287,22 +288,20 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
|
||||
const transitSearch = () => {
|
||||
const transitDay = days.find(d => d.id === Number(form.start_day_id))
|
||||
if (!transitDay) return <p className="m-0 text-content-faint" style={fs(13, 'body')}>{t('transit.pickDay')}</p>
|
||||
// Quick picks offer the chosen day's itinerary, not the whole trip (#1460).
|
||||
const dayPlaces = (assignments[String(transitDay.id)] || [])
|
||||
.slice().sort((a, b) => a.order_index - b.order_index)
|
||||
.map(a => places.find(p => p.id === a.place_id))
|
||||
.filter((p): p is Place => p != null)
|
||||
const dayPlaces = getTransitDayPlaces(transitDay.id, assignments, places)
|
||||
const dayPrefill = transitDay.id === selectedDayId ? transitPrefill : null
|
||||
return (
|
||||
<TransitSearchPanel
|
||||
key={transitDay.id}
|
||||
day={transitDay}
|
||||
days={days}
|
||||
places={dayPlaces}
|
||||
accommodations={accommodations}
|
||||
onAdd={(payload) => onSave(payload as Record<string, any> & { title: string })}
|
||||
initialFrom={transitPrefill?.from ?? null}
|
||||
initialTo={transitPrefill?.to ?? null}
|
||||
initialTime={transitPrefill?.time ?? null}
|
||||
walk={transitPrefill?.walk ?? null}
|
||||
initialFrom={dayPrefill?.from ?? null}
|
||||
initialTo={dayPrefill?.to ?? null}
|
||||
initialTime={dayPrefill?.time ?? null}
|
||||
walk={dayPrefill?.walk ?? null}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { Day, Reservation, ReservationEndpoint } from '../../../types'
|
||||
import { formatPriceText, formatTime, splitReservationDateTime } from '../../../utils/formatters'
|
||||
import { getFlightLegs, getTrainLegs, usesStationRoute } from '../../../utils/flightLegs'
|
||||
import { safeExternalHref } from '../../../utils/safeUrl'
|
||||
import { daySpan, hotelStayTimes, parseMeta, type AssignmentLookupEntry } from './bookingsModel'
|
||||
import { bookingDates, daySpan, hotelStayTimes, parseMeta, type AssignmentLookupEntry } from './bookingsModel'
|
||||
|
||||
export interface FactsContext {
|
||||
t: (key: string, params?: Record<string, string | number>) => string
|
||||
@@ -84,6 +84,7 @@ export function bookingFacts(r: Reservation, c: FactsContext): BookingFacts {
|
||||
const eps = (r.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0))
|
||||
const from = eps.find(e => e.role === 'from')
|
||||
const to = eps.find(e => e.role === 'to')
|
||||
const dates = bookingDates(r, c.days)
|
||||
const startTime = startDt.time || from?.local_time || null
|
||||
const endTime = endDt.time || to?.local_time || null
|
||||
// A stay backed by an accommodation says its times as check-in and check-out;
|
||||
@@ -124,8 +125,8 @@ export function bookingFacts(r: Reservation, c: FactsContext): BookingFacts {
|
||||
|
||||
return {
|
||||
day, time, startTime, endTime,
|
||||
startDate: startDt.date || from?.local_date || span.start?.date || null,
|
||||
endDate: endDt.date || to?.local_date || span.end?.date || null,
|
||||
startDate: dates.start,
|
||||
endDate: dates.end,
|
||||
cells, endpoints: eps.length >= 2 ? eps : [], legCodes,
|
||||
place: r.location || r.place_name || null,
|
||||
accommodation: r.accommodation_name || null,
|
||||
|
||||
@@ -132,6 +132,23 @@ export function daySpan(r: Reservation, days: Day[]): DaySpan {
|
||||
return { start: byId(r.day_id), end: byId(r.end_day_id) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The calendar dates a booking starts and ends on, as "YYYY-MM-DD", or null where it
|
||||
* knows none: its own date first, then the local date of its first or last stop,
|
||||
* then the date of the day it is linked to. A day-linked transport often carries
|
||||
* only times, so its day stands in.
|
||||
*/
|
||||
export function bookingDates(r: Reservation, days: Day[]): { start: string | null; end: string | null } {
|
||||
const span = daySpan(r, days)
|
||||
const eps = (r.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0))
|
||||
const from = eps.find(e => e.role === 'from')
|
||||
const to = eps.find(e => e.role === 'to')
|
||||
return {
|
||||
start: splitReservationDateTime(r.reservation_time).date || from?.local_date || span.start?.date || null,
|
||||
end: splitReservationDateTime(r.reservation_end_time).date || to?.local_date || span.end?.date || null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The moment a booking starts, as "YYYY-MM-DDTHH:MM" in its own local time, or null
|
||||
* without any date. A day-linked transport often carries no date in reservation_time,
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { AssignmentsMap, Place } from '../../types';
|
||||
|
||||
/** Resolve the chosen day's places by day id, in itinerary order (#1460). */
|
||||
export function getTransitDayPlaces(dayId: number, assignments: AssignmentsMap, places: Place[]): Place[] {
|
||||
return (assignments[String(dayId)] ?? [])
|
||||
.slice()
|
||||
.sort((a, b) => a.order_index - b.order_index)
|
||||
.map((a) => places.find((p) => p.id === a.place_id))
|
||||
.filter((p): p is Place => p != null);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { buildDay } from '../../../tests/helpers/factories';
|
||||
import type { Accommodation } from '../../types';
|
||||
import { orderTransitStaysByDate } from './transitStayOrder';
|
||||
|
||||
const day = buildDay({ id: 500, date: '2027-03-21', day_number: 21 });
|
||||
const stay = (id: number, start: number, end = start) =>
|
||||
({ id, start_day_id: start, end_day_id: end }) as Accommodation;
|
||||
const refs = [
|
||||
buildDay({ id: 900, date: '2027-03-01', day_number: 1 }),
|
||||
buildDay({ id: 700, date: '2027-03-19', day_number: 19 }),
|
||||
buildDay({ id: 600, date: '2027-03-20', day_number: 20 }),
|
||||
day,
|
||||
buildDay({ id: 400, date: '2027-03-22', day_number: 22 }),
|
||||
buildDay({ id: 300, date: '2027-03-23', day_number: 23 }),
|
||||
];
|
||||
const ids = (stays: Accommodation[]) => stays.map((a) => a.id);
|
||||
|
||||
describe('orderTransitStaysByDate', () => {
|
||||
it('uses the whole interval: an early check-in with a nearby checkout is close', () => {
|
||||
const spanning = stay(1, 900, 600);
|
||||
const future = stay(2, 400, 300);
|
||||
const farther = stay(3, 700);
|
||||
expect(ids(orderTransitStaysByDate(day, refs, [farther, future, spanning]))).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it('puts the earlier interval first at equal distance, then earlier checkout and stable stay id', () => {
|
||||
const list = [stay(90, 400, 300), stay(2, 600), stay(80, 400, 300), stay(100, 400)];
|
||||
expect(ids(orderTransitStaysByDate(day, refs, list))).toEqual([2, 100, 80, 90]);
|
||||
expect(ids(orderTransitStaysByDate(day, refs, list.slice().reverse()))).toEqual([2, 100, 80, 90]);
|
||||
});
|
||||
|
||||
it('places missing, incomplete and invalid calendar dates after dated stays', () => {
|
||||
const dates = [
|
||||
...refs,
|
||||
buildDay({ id: 10, date: null }),
|
||||
buildDay({ id: 11, date: '2027-02-30' }),
|
||||
buildDay({ id: 12, date: 'not-a-date' }),
|
||||
];
|
||||
const list = [stay(4, 10), stay(3, 11), stay(2, 12), stay(5, 600, 10), stay(6, 99999), stay(9, 900)];
|
||||
expect(ids(orderTransitStaysByDate(day, dates, list))).toEqual([9, 2, 3, 4, 5, 6]);
|
||||
});
|
||||
|
||||
it('handles leap days without accepting a normalized invalid date', () => {
|
||||
const selected = buildDay({ id: 1, date: '2028-03-01' });
|
||||
const dates = [selected, buildDay({ id: 2, date: '2028-02-29' }), buildDay({ id: 3, date: '2027-02-29' })];
|
||||
expect(ids(orderTransitStaysByDate(selected, dates, [stay(1, 3), stay(2, 2)]))).toEqual([2, 1]);
|
||||
});
|
||||
|
||||
it('uses updated calendar dates after days are reordered, regardless of array order or numeric ids', () => {
|
||||
const before = stay(1, 600);
|
||||
const after = stay(2, 400);
|
||||
const reordered = refs
|
||||
.map((d) =>
|
||||
d.id === 600
|
||||
? { ...d, date: '2027-03-22', day_number: 22 }
|
||||
: d.id === 400
|
||||
? { ...d, date: '2027-03-20', day_number: 20 }
|
||||
: d
|
||||
)
|
||||
.reverse();
|
||||
expect(ids(orderTransitStaysByDate(day, refs, [after, before]))).toEqual([1, 2]);
|
||||
expect(ids(orderTransitStaysByDate(day, reordered, [before, after]))).toEqual([2, 1]);
|
||||
});
|
||||
|
||||
it('counts calendar nights equally across the spring DST boundary', () => {
|
||||
const selected = buildDay({ id: 1, date: '2027-03-29' });
|
||||
const dates = [selected, buildDay({ id: 2, date: '2027-03-28' }), buildDay({ id: 3, date: '2027-03-30' })];
|
||||
expect(ids(orderTransitStaysByDate(selected, dates, [stay(1, 3), stay(2, 2)]))).toEqual([2, 1]);
|
||||
});
|
||||
|
||||
it('normalizes reversed interval endpoints consistently with day-range membership', () => {
|
||||
expect(ids(orderTransitStaysByDate(day, refs, [stay(1, 700), stay(2, 300, 600)]))).toEqual([2, 1]);
|
||||
});
|
||||
|
||||
it('keeps dated stays ahead of undated ones when the selected day has no usable date', () => {
|
||||
const selected = { ...day, date: null };
|
||||
expect(ids(orderTransitStaysByDate(selected, refs, [stay(1, 99999), stay(3, 300), stay(2, 900)]))).toEqual([
|
||||
2, 3, 1,
|
||||
]);
|
||||
});
|
||||
|
||||
it('does not mutate the caller list', () => {
|
||||
const list = Object.freeze([stay(1, 300), stay(2, 600)]);
|
||||
expect(ids(orderTransitStaysByDate(day, refs, list))).toEqual([2, 1]);
|
||||
expect(ids([...list])).toEqual([1, 2]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { Accommodation, Day } from '../../types';
|
||||
|
||||
/** A strict calendar date as a UTC day number, so DST never changes the number of nights. */
|
||||
function nightNumber(value: string | null | undefined): number | null {
|
||||
if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
|
||||
const time = Date.parse(`${value}T00:00:00Z`);
|
||||
if (!Number.isFinite(time) || new Date(time).toISOString().slice(0, 10) !== value) return null;
|
||||
return time / 86_400_000;
|
||||
}
|
||||
|
||||
/** Rank other-day stays by the closest boundary of their complete booking interval. */
|
||||
export function orderTransitStaysByDate(
|
||||
day: Pick<Day, 'date'>,
|
||||
days: readonly Pick<Day, 'id' | 'date'>[],
|
||||
stays: readonly Accommodation[]
|
||||
): Accommodation[] {
|
||||
const selected = nightNumber(day.date);
|
||||
const dates = new Map(days.map((d) => [d.id, nightNumber(d.date)]));
|
||||
return stays
|
||||
.map((stay) => {
|
||||
const start = dates.get(stay.start_day_id);
|
||||
const end = dates.get(stay.end_day_id);
|
||||
// A partial or invalid interval has no usable proximity and follows every dated stay.
|
||||
const lo = start != null && end != null ? Math.min(start, end) : Infinity;
|
||||
const hi = start != null && end != null ? Math.max(start, end) : Infinity;
|
||||
const distance = selected != null && lo !== Infinity ? Math.max(lo - selected, selected - hi, 0) : Infinity;
|
||||
// Earlier check-in, then earlier check-out, then stable booking identity break ties.
|
||||
return { stay, rank: [distance, lo, hi, stay.id] };
|
||||
})
|
||||
.sort((a, b) => {
|
||||
for (let i = 0; i < a.rank.length; i++) {
|
||||
if (a.rank[i] !== b.rank[i]) return a.rank[i] < b.rank[i] ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
})
|
||||
.map((row) => row.stay);
|
||||
}
|
||||
@@ -125,14 +125,15 @@ describe('stageMapData with a stage', () => {
|
||||
expect(stageMapData(routes(), stage, true).lines).toEqual([LINES[1], LINES[2]])
|
||||
})
|
||||
|
||||
it('FE-RTSTAGE-016: the drive into the next day is left off the stage', () => {
|
||||
// With "connect the days" on, that leg is drawn in the colour of the day it leaves, so
|
||||
it('FE-RTSTAGE-016: the drive in from the day before is left off the stage', () => {
|
||||
// With "connect the days" on, that leg is drawn as the day it arrives on (#3123), so
|
||||
// filtering by day number alone handed the stage a line running off it to a place the
|
||||
// day never visits. On a phone, where the stage IS the map, it was the longest thing
|
||||
// on screen and read as the day's own route.
|
||||
const withJoin = routes({ lineJoins: [false, false, true, false] })
|
||||
// on screen and read as the day's own route. The assembler emits it first among the
|
||||
// lines of the day it reaches, ahead of that day's own legs.
|
||||
const withJoin = routes({ lineJoins: [false, true, false, false] })
|
||||
|
||||
expect(stageMapData(withJoin, stage, true).lines).toEqual([LINES[1]])
|
||||
expect(stageMapData(withJoin, stage, true).lines).toEqual([LINES[2]])
|
||||
})
|
||||
|
||||
it('FE-RTSTAGE-020: a day that is nothing but driving keeps its connection rather than going blank', () => {
|
||||
@@ -144,7 +145,7 @@ describe('stageMapData with a stage', () => {
|
||||
})
|
||||
|
||||
it('FE-RTSTAGE-017: the colours still line up once a join has been dropped', () => {
|
||||
const data = stageMapData(routes({ lineJoins: [false, false, true, false] }), stage, true)
|
||||
const data = stageMapData(routes({ lineJoins: [false, true, false, false] }), stage, true)
|
||||
|
||||
expect(data.lineColors).toHaveLength(data.lines.length)
|
||||
expect(data.lineColors).toEqual([dayColor(2)])
|
||||
@@ -153,7 +154,7 @@ describe('stageMapData with a stage', () => {
|
||||
it('FE-RTSTAGE-018: the all-days view keeps the joins, which is the view they are for', () => {
|
||||
// The setting draws the whole drive as one connected line; that is what it is for, and
|
||||
// on this map the connection has the other days beside it.
|
||||
expect(stageMapData(routes({ lineJoins: [false, false, true, false] }), null, true).lines).toEqual(LINES)
|
||||
expect(stageMapData(routes({ lineJoins: [false, true, false, false] }), null, true).lines).toEqual(LINES)
|
||||
})
|
||||
|
||||
it('FE-RTSTAGE-019: routes from before the flag existed are drawn as they were', () => {
|
||||
|
||||
@@ -50,15 +50,15 @@ export function stageMapData(
|
||||
}
|
||||
if (!routes.lines.length) return { ...EMPTY, placeIds: stagePlaceIds(stage), focusPoints: stagePoints(stage) }
|
||||
|
||||
// A stage is ONE day, so the drive into the next day is left off it.
|
||||
// A stage is ONE day, so the drive in from the day before is left off it.
|
||||
//
|
||||
// With "connect the days" on, that leg is drawn in the colour of the day it leaves, so
|
||||
// on the whole-drive map it reads as that day carrying on. Filtering by day number
|
||||
// alone therefore handed a stage a line that runs off it to a place the day never
|
||||
// visits: on a phone, where the stage IS the map, that read as the day's own route and
|
||||
// was the longest thing on screen. The desktop has the same connection, but it has it
|
||||
// beside every other day, which is the view the setting exists for; here that view is
|
||||
// the "all days" one, a tap away on the same map.
|
||||
// With "connect the days" on, that leg is drawn as the day it arrives on, the day whose
|
||||
// distance counts it. Filtering by day number alone therefore handed a stage a line
|
||||
// that runs off it to a place the day never visits: on a phone, where the stage IS the
|
||||
// map, that read as the day's own route and was the longest thing on screen. The
|
||||
// desktop has the same connection, but it has it beside every other day, which is the
|
||||
// view the setting exists for; here that view is the "all days" one, a tap away on the
|
||||
// same map.
|
||||
const ofDay: number[] = []
|
||||
routes.lineDays.forEach((n, i) => { if (n === stage.dayNumber) ofDay.push(i) })
|
||||
const own = ofDay.filter(i => !routes.lineJoins?.[i])
|
||||
|
||||
@@ -631,7 +631,7 @@ describe('useRoadtripRoutes', () => {
|
||||
expect(result.current.totalDistance).toBe(300000)
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-ROUTES-022: the joining stroke wears the day it leaves, its kilometres the day it reaches', async () => {
|
||||
it('FE-ROADTRIP-ROUTES-022: the joining stroke wears the day it reaches, like its kilometres (#3123)', async () => {
|
||||
setting({ roadtrip_connect_days: true })
|
||||
const { days: daysList, assignments } = twoDays()
|
||||
const { result } = renderHook(() => useRoadtripRoutes(7, daysList, assignments))
|
||||
@@ -639,10 +639,9 @@ describe('useRoadtripRoutes', () => {
|
||||
|
||||
// Same length and same order as `lines`, or a colour lands on the wrong day.
|
||||
expect(result.current.lineDays).toHaveLength(result.current.lines.length)
|
||||
// The stroke starts at a stop on day 1, so drawing it as day 2 would make day 2
|
||||
// look like it begins somewhere it has no stop.
|
||||
expect(result.current.lineDays).toEqual([1, 1, 2])
|
||||
// The kilometres go the other way: they are driven on the day they arrive.
|
||||
// Day 1 ends at its last stop, so the drive on to day 2 is driven on day 2: its
|
||||
// kilometres are counted there, and drawn in day 1's colour the map said otherwise.
|
||||
expect(result.current.lineDays).toEqual([1, 2, 2])
|
||||
expect(result.current.days.map(d => d.distance)).toEqual([100000, 200000])
|
||||
})
|
||||
|
||||
@@ -666,7 +665,8 @@ describe('useRoadtripRoutes', () => {
|
||||
|
||||
setting({ roadtrip_connect_days: true })
|
||||
expect(result.current.lines).toHaveLength(3)
|
||||
expect(result.current.lineDays).toEqual([1, 2, 2])
|
||||
// The drive past midnight lands on day 2 and is drawn there, like day 2's own legs.
|
||||
expect(result.current.lineDays).toEqual([2, 2, 2])
|
||||
expect(result.current.days[0].distance).toBe(300000)
|
||||
})
|
||||
|
||||
|
||||
@@ -69,6 +69,10 @@ export function useTripRangeGuard(): { checking: boolean; check: (trip: Pick<Tri
|
||||
startDate: range.newStart,
|
||||
endDate: range.newEnd,
|
||||
dayCount: range.dayCount,
|
||||
// The rule the server lays the days out by when bookings keep their dates,
|
||||
// the default either dialog saves with. Shifting everything moves no day
|
||||
// that this keeps, so the dated days it removes are the same.
|
||||
keepDates: true,
|
||||
})
|
||||
if (plan.removed.length === 0) return null
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import { useNativeCapabilities } from '../native/capabilities'
|
||||
import { isNativeIos } from '../native/platform'
|
||||
import { useWindowFold } from '../native/windowFold'
|
||||
import './mobile.css'
|
||||
import './corner.css'
|
||||
|
||||
interface MobileShellProps {
|
||||
isPhone: boolean
|
||||
|
||||
@@ -48,7 +48,7 @@ export default function MImageViewer({
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label={t('collab.chat.closeImage')}
|
||||
className="absolute end-4 top-[calc(var(--m-safe-top,12px)+4px)] z-10 flex h-10 w-10 items-center justify-center rounded-full bg-[color:var(--m-viewer-btn)] text-[color:var(--m-viewer-ink)]"
|
||||
className="m-corner-beside absolute end-4 top-[calc(var(--m-safe-top,12px)+4px)] z-10 flex h-10 w-10 items-center justify-center rounded-full bg-[color:var(--m-viewer-btn)] text-[color:var(--m-viewer-ink)]"
|
||||
>
|
||||
<X size={20} strokeWidth={2} />
|
||||
</button>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useLayoutEffect, useRef, useState, type ReactNode, type RefObject } from 'react';
|
||||
import { useCallback, useLayoutEffect, useRef, useState, type ReactNode, type RefObject } from 'react';
|
||||
import { edgeFadeClass, useEdgeFade } from './useEdgeFade';
|
||||
|
||||
/**
|
||||
@@ -30,6 +30,13 @@ export function MRail({
|
||||
useEvenLines(listRef);
|
||||
// On a short window the entries scroll; the cut edge fades, so the foot's entries read as more below.
|
||||
const [list, setList] = useState<HTMLDivElement | null>(null);
|
||||
// One function for the rail's lifetime: React 19 detaches and attaches a ref
|
||||
// whose function changed, so an inline one set the state to null and back on
|
||||
// every render and the trip's rail rendered itself into React's update limit.
|
||||
const listNode = useCallback((node: HTMLDivElement | null) => {
|
||||
listRef.current = node;
|
||||
setList(node);
|
||||
}, []);
|
||||
const fade = useEdgeFade(list, 'y');
|
||||
return (
|
||||
<nav
|
||||
@@ -38,10 +45,7 @@ export function MRail({
|
||||
>
|
||||
{head && <div className="mb-2 flex flex-none justify-center">{head}</div>}
|
||||
<div
|
||||
ref={(node) => {
|
||||
listRef.current = node;
|
||||
setList(node);
|
||||
}}
|
||||
ref={listNode}
|
||||
className={`flex min-h-0 w-full flex-1 flex-col items-center gap-1 overflow-y-auto px-1 [scrollbar-width:none] ${edgeFadeClass(fade, 'y')}`}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -89,7 +89,7 @@ export function MSectionList({
|
||||
* width on both screens.
|
||||
*/
|
||||
export const SECTION_SCREEN =
|
||||
'px-4 pb-[calc(var(--bottom-nav-h,84px)+16px)] pt-[var(--m-safe-top,12px)] wide:mx-auto wide:max-w-[1040px] wide:px-6 split:grid split:max-w-[1240px] split:grid-cols-[260px_minmax(0,1fr)] split:items-start split:gap-8';
|
||||
'm-corner-flow px-4 pb-[calc(var(--bottom-nav-h,84px)+16px)] pt-[var(--m-safe-top,12px)] wide:mx-auto wide:max-w-[1040px] wide:px-6 split:grid split:max-w-[1240px] split:grid-cols-[260px_minmax(0,1fr)] split:items-start split:gap-8';
|
||||
|
||||
interface MSectionNavProps {
|
||||
title: string;
|
||||
|
||||
@@ -86,11 +86,11 @@ type MSheetWideAnchor = 'center' | 'rail-foot'
|
||||
* docked sheet just above the dock; neither lies across the dock.
|
||||
*/
|
||||
const REGION: Record<MSheetVariant, string> = {
|
||||
card: 'inset-x-[14px] top-[var(--m-safe-top,12px)] bottom-[calc(var(--bottom-nav-h,84px)+12px)] justify-center',
|
||||
card: 'inset-x-[14px] top-[max(var(--m-safe-top,12px),var(--m-corner-clear,0px))] bottom-[calc(var(--bottom-nav-h,84px)+12px)] justify-center',
|
||||
// On a phone on its side the gap it keeps at the top would leave it a strip
|
||||
// of a few rows, so there it may rise nearly to the top.
|
||||
bottom:
|
||||
'inset-x-4 top-[calc(var(--m-safe-top,12px)+56px)] bottom-[calc(var(--bottom-nav-h,84px)+16px)] justify-end short:top-[calc(var(--m-safe-top,12px)+8px)]',
|
||||
'inset-x-4 top-[max(calc(var(--m-safe-top,12px)+56px),var(--m-corner-clear,0px))] bottom-[calc(var(--bottom-nav-h,84px)+16px)] justify-end short:top-[calc(var(--m-safe-top,12px)+8px)]',
|
||||
drawer: 'start-0 top-0 bottom-0 w-[78%] max-w-[320px]',
|
||||
}
|
||||
|
||||
@@ -116,7 +116,8 @@ const SHORT_FORM_BOX = 'short:max-w-[640px] short:flex-1'
|
||||
function regionClass(variant: MSheetVariant, anchor: MSheetWideAnchor = 'center', form = false): string {
|
||||
const base = 'pointer-events-none absolute flex flex-col'
|
||||
if (variant === 'drawer') return `${base} ${REGION.drawer}`
|
||||
return `${base} ${REGION[variant]} ${WIDE_REGION[anchor]}${form ? ` ${SHORT_FORM_REGION}` : ''}`
|
||||
// m-corner-side: on a wide window the sheet keeps off a corner element's side (a Duo's status capsule).
|
||||
return `${base} m-corner-side ${REGION[variant]} ${WIDE_REGION[anchor]}${form ? ` ${SHORT_FORM_REGION}` : ''}`
|
||||
}
|
||||
|
||||
/** The sheet's own box inside the region: its width, and the arrow when it has one. */
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/* ── An element in a top corner (an iPhone Duo's status capsule) ──────────────
|
||||
Beside mobile.css, which holds the variables these read (--m-corner-*).
|
||||
For the screens that place their own controls rather than sit in .m-page
|
||||
(the trip, its map). Every variable is 0 without such an element, so these
|
||||
change nothing on any other device.
|
||||
m-corner-beside: a control row in the corner's height ends before it.
|
||||
m-corner-side: a layer that fills the page ends before the corner's side on
|
||||
a wide window (--m-corner-side-*, 0 upright, where content starts below the
|
||||
corner through --m-corner-clear instead).
|
||||
The element sits where the hardware puts it, whatever the reading
|
||||
direction, so right to left swaps the two sides back. */
|
||||
.m-corner-beside {
|
||||
margin-inline: var(--m-corner-l-gap, 0px) var(--m-corner-r-gap, 0px);
|
||||
}
|
||||
html[dir='rtl'] .m-corner-beside {
|
||||
margin-inline: var(--m-corner-r-gap, 0px) var(--m-corner-l-gap, 0px);
|
||||
}
|
||||
.m-corner-side {
|
||||
margin-inline: var(--m-corner-side-l, 0px) var(--m-corner-side-r, 0px);
|
||||
}
|
||||
html[dir='rtl'] .m-corner-side {
|
||||
margin-inline: var(--m-corner-side-r, 0px) var(--m-corner-side-l, 0px);
|
||||
}
|
||||
/* m-corner-beside-in: m-corner-beside for a row inside .m-page, upright only
|
||||
(on a wide window the page itself already ends before the corner). */
|
||||
.m-corner-beside-in {
|
||||
margin-inline: var(--m-corner-in-l, 0px) var(--m-corner-in-r, 0px);
|
||||
}
|
||||
html[dir='rtl'] .m-corner-beside-in {
|
||||
margin-inline: var(--m-corner-in-r, 0px) var(--m-corner-in-l, 0px);
|
||||
}
|
||||
@@ -86,6 +86,23 @@
|
||||
* the air is 0 too (min() of 0 and 8px). */
|
||||
--m-safe-l-gap: calc(var(--m-bar-l) + min(var(--m-bar-l), 8px));
|
||||
--m-safe-r-gap: calc(var(--m-bar-r) + min(var(--m-bar-r), 8px));
|
||||
/* The corner element alone, with the same air, for the screens that place
|
||||
* their own controls (the trip, the map): a control row in the corner's
|
||||
* height ends this far from the screen's side (m-corner-beside). Physical
|
||||
* sides, as the element is: right to left does not move it. */
|
||||
--m-corner-l-gap: calc(var(--trek-native-corner-left, 0px) + min(var(--trek-native-corner-left, 0px), 8px));
|
||||
--m-corner-r-gap: calc(var(--trek-native-corner-right, 0px) + min(var(--trek-native-corner-right, 0px), 8px));
|
||||
/* Where the content of a screen that places its own scroll body begins at
|
||||
* the latest, so its first row is not under the corner element: just below
|
||||
* it (m-corner-below). Upright that is the cheaper way round; on a wide
|
||||
* window the page gives up the corner's side instead (below). 0 elsewhere. */
|
||||
--m-corner-clear: calc(var(--m-corner-b) + min(var(--m-corner-b), 10px));
|
||||
--m-corner-side-l: 0px;
|
||||
--m-corner-side-r: 0px;
|
||||
/* The same air for a control row inside .m-page, which on a wide window has
|
||||
* already given up the corner's side (m-corner-beside-in). */
|
||||
--m-corner-in-l: var(--m-corner-l-gap);
|
||||
--m-corner-in-r: var(--m-corner-r-gap);
|
||||
/* The navigation rail's share of the leading edge (wide windows only), what
|
||||
* every full-width fixed bar and the page column start after. */
|
||||
--m-rail-w: 0px;
|
||||
@@ -98,10 +115,21 @@
|
||||
* reads the same values as the shell. */
|
||||
html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {
|
||||
--bottom-nav-h: env(safe-area-inset-bottom, 0px);
|
||||
--m-rail-w: calc(var(--m-safe-l) + 100px);
|
||||
--m-rail-w: calc(var(--m-bar-l) + 100px);
|
||||
/* A wide window gives up the corner element's side over the whole height,
|
||||
* as an iPhone on its side does for its camera: on an unfolded Duo lifting
|
||||
* every page below the status capsule cost a quarter of the height. The
|
||||
* rail already takes the leading side, so only the trailing side's corner
|
||||
* counts here. */
|
||||
--m-corner-clear: 0px;
|
||||
--m-corner-side-r: var(--m-corner-r-gap);
|
||||
--m-corner-in-l: 0px;
|
||||
--m-corner-in-r: 0px;
|
||||
}
|
||||
html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {
|
||||
--m-rail-w: calc(var(--m-safe-r) + 100px);
|
||||
--m-rail-w: calc(var(--m-bar-r) + 100px);
|
||||
--m-corner-side-l: var(--m-corner-l-gap);
|
||||
--m-corner-side-r: 0px;
|
||||
}
|
||||
|
||||
.dark .m-root {
|
||||
@@ -631,13 +659,30 @@ html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-
|
||||
the leading inset on a wide window. */
|
||||
.m-page {
|
||||
margin-inline: var(--m-page-l, 0px) var(--m-page-r, 0px);
|
||||
padding-top: max(0px, calc(var(--m-corner-b, 0px) + 12px - var(--m-safe-top, 12px) - 70px));
|
||||
padding-top: max(0px, calc(var(--m-corner-clear, 0px) + 2px - var(--m-safe-top, 12px) - 70px));
|
||||
}
|
||||
html[dir='rtl'] .m-page {
|
||||
margin-inline: var(--m-page-r, 0px) var(--m-page-l, 0px);
|
||||
}
|
||||
/* The lift above counts on a floating top bar over the page. A screen whose
|
||||
first row is part of the page (m-corner-flow: settings, administration,
|
||||
collections) is lifted until that row starts below the corner element; one
|
||||
that keeps clear of it by itself (m-corner-own: a map under its own bars, a
|
||||
calendar under its own header) is not lifted at all. */
|
||||
.m-page:has(.m-corner-flow) {
|
||||
padding-top: max(0px, calc(var(--m-corner-clear, 0px) - var(--m-safe-top, 12px)));
|
||||
}
|
||||
.m-page:has(.m-corner-own) {
|
||||
padding-top: 0;
|
||||
}
|
||||
/* On a wide window the page starts at the top and ends before the corner
|
||||
element instead (--m-corner-side-*, 0 without one). */
|
||||
html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-page {
|
||||
margin-inline-start: 0;
|
||||
margin-inline-end: max(var(--m-page-r, 0px), var(--m-corner-side-r, 0px));
|
||||
}
|
||||
html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-page {
|
||||
margin-inline-end: max(var(--m-page-l, 0px), var(--m-corner-side-l, 0px));
|
||||
}
|
||||
/* A screen whose background is a map reaches under the rail: the map runs to
|
||||
the window's edge and the rail floats over it like the top controls do. Its
|
||||
|
||||
@@ -122,7 +122,7 @@ export default function MAtlas() {
|
||||
return (
|
||||
// h-dvh, not h-full: the shell stopped providing a definite height (#1809)
|
||||
// and a map on a percentage of an auto-height parent collapses to zero.
|
||||
<div ref={rootRef} className="m-bleed relative h-dvh overflow-hidden">
|
||||
<div ref={rootRef} className="m-bleed m-corner-own relative h-dvh overflow-hidden">
|
||||
<div ref={mapRef} className="absolute inset-0 z-[1] bg-[color:var(--m-mapb)] [&_.leaflet-control-zoom]:hidden" />
|
||||
{/* Region hover tooltip — positioned imperatively by useAtlas. */}
|
||||
<div
|
||||
|
||||
@@ -50,7 +50,7 @@ export default function MAtlasSearch({
|
||||
const q = query.trim().toLowerCase()
|
||||
const rows = q ? options.filter((o) => o.label.toLowerCase().includes(q)).slice(0, 6) : suggestions
|
||||
|
||||
const scrimCls = 'm-fade-in fixed inset-0 z-[70] flex flex-col bg-[rgba(16,16,19,.28)] px-[18px] pt-[calc(var(--m-safe-top,12px)+12px)] backdrop-blur-[22px] backdrop-saturate-[1.6] wide:pt-[calc(var(--m-safe-top,12px)+72px)] wide:[&>*]:mx-auto wide:[&>*]:w-full wide:[&>*]:max-w-[640px]' // theme-lint-disable — fixed scrim value from the design
|
||||
const scrimCls = 'm-fade-in fixed inset-0 z-[70] flex flex-col bg-[rgba(16,16,19,.28)] px-[18px] pt-[max(calc(var(--m-safe-top,12px)+12px),var(--m-corner-clear,0px))] backdrop-blur-[22px] backdrop-saturate-[1.6] wide:pt-[calc(var(--m-safe-top,12px)+72px)] wide:[&>*]:mx-auto wide:[&>*]:w-full wide:[&>*]:max-w-[640px]' // theme-lint-disable — fixed scrim value from the design
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -220,7 +220,7 @@ export default function MCollections() {
|
||||
// Map view fills the viewport like the trip and journal maps do (#2104);
|
||||
// h-dvh because the shell owns no scroll container (#1809). List view
|
||||
// keeps the document as the scroller.
|
||||
className={`px-4 pb-[calc(var(--bottom-nav-h,84px)+12px)] pt-[var(--m-safe-top,12px)] wide:px-6 split:grid split:grid-cols-[260px_minmax(0,1fr)] split:gap-8 ${c.view === 'map' ? 'flex h-dvh flex-col overflow-hidden' : 'wide:mx-auto wide:max-w-[1040px] split:max-w-[1240px] split:items-start'}`}
|
||||
className={`m-corner-flow px-4 pb-[calc(var(--bottom-nav-h,84px)+12px)] pt-[var(--m-safe-top,12px)] wide:px-6 split:grid split:grid-cols-[260px_minmax(0,1fr)] split:gap-8 ${c.view === 'map' ? 'flex h-dvh flex-col overflow-hidden' : 'wide:mx-auto wide:max-w-[1040px] split:max-w-[1240px] split:items-start'}`}
|
||||
>
|
||||
{split && (
|
||||
<nav
|
||||
|
||||
@@ -66,7 +66,7 @@ export default function MUserMenu({ open, onClose }: MUserMenuProps): React.Reac
|
||||
}
|
||||
|
||||
return (
|
||||
<MDropdownPanel open={open} onClose={onClose} className="end-4 top-[calc(var(--m-safe-top,12px)+68px)]">
|
||||
<MDropdownPanel open={open} onClose={onClose} className="m-corner-beside end-4 top-[calc(var(--m-safe-top,12px)+68px)]">
|
||||
<div className="flex items-center gap-[10px] p-[10px_10px_12px]">
|
||||
<span className="flex h-10 w-10 flex-none items-center justify-center overflow-hidden rounded-full bg-[image:linear-gradient(135deg,#6A6A74,#1A1A1E)] text-[0.9375rem] font-bold text-white">
|
||||
{user?.avatar_url
|
||||
|
||||
@@ -346,7 +346,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
return (
|
||||
// h-dvh, not h-full: the shell stopped providing a definite height (#1809)
|
||||
// and a map on a percentage of an auto-height parent collapses to zero.
|
||||
<div ref={rootRef} className="m-bleed relative h-dvh overflow-hidden" style={headSlot ? IN_SHELL_ROW : undefined}>
|
||||
<div ref={rootRef} className="m-bleed m-corner-own relative h-dvh overflow-hidden" style={headSlot ? IN_SHELL_ROW : undefined}>
|
||||
{/* Integrated map — always mounted, the gallery overlays it. Beside the feed
|
||||
it begins where the feed ends, so its controls and its framing stay in
|
||||
the part that can be seen. */}
|
||||
@@ -358,7 +358,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
ref={mapRef}
|
||||
layers={mapLayers}
|
||||
hideLayerControl
|
||||
controlsTop="calc(var(--m-safe-top, 12px) + 50px)"
|
||||
controlsTop="max(calc(var(--m-safe-top, 12px) + 50px), var(--m-corner-clear, 0px))"
|
||||
// Its satellite switch sits in the bar above, beside the menu.
|
||||
baseLayer={mapBase}
|
||||
onOpenEntry={handleMarkerClick}
|
||||
@@ -382,7 +382,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
|
||||
{/* Gallery tab overlay */}
|
||||
{view === 'gallery' && (
|
||||
<div className="m-span-x absolute inset-y-0 z-[5] overflow-y-auto bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] px-4 pt-[calc(var(--m-safe-top,12px)+56px)] pb-[calc(var(--bottom-nav-h,84px)+16px)] wide:px-6">
|
||||
<div className="m-span-x absolute inset-y-0 z-[5] overflow-y-auto bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] px-4 pt-[max(calc(var(--m-safe-top,12px)+56px),var(--m-corner-clear,0px))] pb-[calc(var(--bottom-nav-h,84px)+16px)] wide:px-6">
|
||||
{gallery.length === 0 ? (
|
||||
<div className="flex min-h-full flex-col items-center justify-center px-8 py-10 text-center">
|
||||
<MDancingTrek scene="journey" className="mb-2" />
|
||||
|
||||
@@ -29,7 +29,7 @@ import { useDayPreviewStore } from '../../dayPreviewStore'
|
||||
import { useIsSplit, useIsWide } from '../../../hooks/sizeClass'
|
||||
import MTripRail from './MTripRail'
|
||||
import {
|
||||
CollabSegment, CompactToggle, DockMoreButton, DocSyncButton, GlassSegment, HeaderActions, PrimaryPill, ROW_AFTER_BACK, ROW_CENTRED,
|
||||
CHROME_ROW, CollabSegment, CompactToggle, DockMoreButton, DocSyncButton, GlassSegment, HeaderActions, PrimaryPill, ROW_AFTER_BACK, ROW_CENTRED,
|
||||
} from './MTripShellParts'
|
||||
import { edgeFadeClass, useEdgeFade } from '../../components/useEdgeFade'
|
||||
import { useShortcuts } from '../../keyboard/useShortcuts'
|
||||
@@ -634,13 +634,15 @@ export default function MTripShell({
|
||||
)}
|
||||
{!MAP_TABS.has(trTab) && (
|
||||
<div className="absolute inset-0 z-30 bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] wide:start-[var(--m-rail-w)]">
|
||||
<TabPanel planner={planner} shell={shell} tab={trTab} />
|
||||
<div className="m-corner-side relative h-full">
|
||||
<TabPanel planner={planner} shell={shell} tab={trTab} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Day chips (z-25 — covered by non-plan tab overlays, stays mounted) ── */}
|
||||
{days.length > 0 && (
|
||||
<div className={`absolute end-4 start-[calc(var(--m-rail-w,0px)+16px)] z-[25] flex gap-[6px] top-[calc(var(--m-safe-top,12px)+50px)] ${chromeSpan}`}>
|
||||
<div className={`${CHROME_ROW} z-[25] flex gap-[6px] top-[calc(var(--m-safe-top,12px)+50px)] ${chromeSpan}`}>
|
||||
{/* The glass is the outer box, the scroller sits inside its padding: that way
|
||||
the fade at an edge that runs on takes the chips, not the glass's rim. */}
|
||||
<div className="relative flex min-w-0 flex-1 rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] p-[3px] backdrop-blur-[24px] backdrop-saturate-[1.7]">
|
||||
@@ -711,7 +713,7 @@ export default function MTripShell({
|
||||
)}
|
||||
|
||||
{/* ── Top controls (z-42 — above every layer incl. tab overlays) ── */}
|
||||
<div className={`absolute end-4 start-[calc(var(--m-rail-w,0px)+16px)] z-[42] flex h-10 items-center justify-between top-[var(--m-safe-top,12px)] ${chromeSpan}`}>
|
||||
<div className={`${CHROME_ROW} z-[42] flex h-10 items-center justify-between top-[var(--m-safe-top,12px)] ${chromeSpan}`}>
|
||||
<MIconBtn ariaLabel={t('common.back')} onClick={() => navigate('/dashboard')} className="backdrop-blur-[24px] backdrop-saturate-[1.7]">
|
||||
<ChevronLeft size={19} strokeWidth={2.2} />
|
||||
</MIconBtn>
|
||||
|
||||
@@ -64,6 +64,12 @@ export function GlassSegment({ children, activeKey }: { children: ReactNode; act
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The box of the trip's floating rows (the top controls, the day chips): the page's width after
|
||||
* the rail, beside an element in a top corner such as a Duo's status capsule (mobile.css).
|
||||
*/
|
||||
export const CHROME_ROW = 'm-corner-beside absolute end-4 start-[calc(var(--m-rail-w,0px)+16px)]';
|
||||
|
||||
/** A phone's header group: after the back button (transports, bookings), or centred on the bar (costs, files). */
|
||||
export const ROW_AFTER_BACK = 'absolute start-[52px] end-2 justify-center';
|
||||
export const ROW_CENTRED = 'absolute inset-x-0 mx-auto w-fit';
|
||||
|
||||
@@ -216,10 +216,10 @@ export function AssistantScreen({ tripId, tripTitle, hidden, hops, onOpenTripCha
|
||||
hidden={hidden}
|
||||
tabIndex={-1}
|
||||
onKeyDown={(e) => keepTabInside(e, sectionRef.current)}
|
||||
className={`fixed inset-0 z-[var(--z-bar)] ${hidden ? 'hidden' : 'flex'} m-panel-in flex-col bg-[var(--m-bg)] bg-[image:var(--m-scr)] text-m-ink outline-none wide:inset-auto wide:bottom-3 wide:end-3 wide:top-3 wide:w-[min(500px,calc(100vw-var(--m-rail-w,0px)-24px))] wide:overflow-hidden wide:rounded-[28px] wide:border wide:border-[color:var(--m-shbr)] wide:shadow-modal`}
|
||||
className={`m-corner-side fixed inset-0 z-[var(--z-bar)] ${hidden ? 'hidden' : 'flex'} m-panel-in flex-col bg-[var(--m-bg)] bg-[image:var(--m-scr)] text-m-ink outline-none wide:inset-auto wide:bottom-3 wide:end-3 wide:top-3 wide:w-[min(500px,calc(100vw-var(--m-rail-w,0px)-24px))] wide:overflow-hidden wide:rounded-[28px] wide:border wide:border-[color:var(--m-shbr)] wide:shadow-modal`}
|
||||
style={{ paddingBottom: `max(env(safe-area-inset-bottom, 0px), ${keyboard}px)` }}
|
||||
>
|
||||
<header className="flex flex-none items-center gap-2 px-4 pb-2 pt-[var(--m-safe-top,12px)] wide:pt-3">
|
||||
<header className="m-corner-beside-in flex flex-none items-center gap-2 px-4 pb-2 pt-[var(--m-safe-top,12px)] wide:pt-3">
|
||||
<MIconBtn ariaLabel={t('common.back')} onClick={close}>
|
||||
<ChevronLeft size={19} strokeWidth={2.2} />
|
||||
</MIconBtn>
|
||||
@@ -256,7 +256,7 @@ export function AssistantScreen({ tripId, tripTitle, hidden, hops, onOpenTripCha
|
||||
<MDropdownPanel
|
||||
open={panel === 'history'}
|
||||
onClose={() => setPanel(null)}
|
||||
className="end-4 top-[calc(var(--m-safe-top,12px)+48px)] max-h-[60vh] overflow-y-auto"
|
||||
className="m-corner-beside-in end-4 top-[calc(var(--m-safe-top,12px)+48px)] max-h-[60vh] overflow-y-auto"
|
||||
>
|
||||
<MListRow icon={Plus} label={t('assistant.history.new')} onClick={() => pick(thread.newThread)} />
|
||||
{threads.length === 0 ? (
|
||||
@@ -285,7 +285,7 @@ export function AssistantScreen({ tripId, tripTitle, hidden, hops, onOpenTripCha
|
||||
<MDropdownPanel
|
||||
open={panel === 'menu'}
|
||||
onClose={() => setPanel(null)}
|
||||
className="end-4 top-[calc(var(--m-safe-top,12px)+48px)]"
|
||||
className="m-corner-beside-in end-4 top-[calc(var(--m-safe-top,12px)+48px)]"
|
||||
>
|
||||
{tripChat && (
|
||||
<MListRow
|
||||
|
||||
@@ -457,7 +457,7 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
|
||||
<div
|
||||
// Beside the trip's pane nothing lies over the map, so the bar takes the
|
||||
// top edge, level with the pane's own top row.
|
||||
className={`pointer-events-none absolute end-4 start-[calc(var(--trip-map-inset,0px)+16px)] z-[25] flex flex-col items-center gap-2 ${
|
||||
className={`m-corner-beside pointer-events-none absolute end-4 start-[calc(var(--trip-map-inset,0px)+16px)] z-[25] flex flex-col items-center gap-2 ${
|
||||
shell.paneOpen ? 'top-[var(--m-safe-top,12px)]' : 'top-[calc(var(--m-safe-top,12px)+96px)]'
|
||||
}`}
|
||||
>
|
||||
|
||||
@@ -117,7 +117,7 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto px-4 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[calc(var(--m-safe-top,12px)+58px)]">
|
||||
<div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto px-4 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]">
|
||||
{/* ── Places/Tours, the filter chips and Import (Add sits in the search row
|
||||
below to free space). The switch has a row of its own, except where the
|
||||
screen is short (a phone on its side): there it shares the chips' row,
|
||||
|
||||
@@ -212,7 +212,7 @@ function PlanDayPage({ planner, shell, dayId: pageDayId, active, editing, legMen
|
||||
Beside the map the card is the pane and runs down to that line, as the
|
||||
places list does; across the page it is as tall as its day, so a short
|
||||
day leaves no empty card under it. */}
|
||||
<div className="absolute inset-x-4 flex flex-col gap-3 top-[calc(var(--m-safe-top,12px)+102px)] bottom-[calc(env(safe-area-inset-bottom,0px)+90px)] wide:bottom-[calc(env(safe-area-inset-bottom,0px)+12px)]">
|
||||
<div className="absolute inset-x-4 flex flex-col gap-3 top-[max(calc(var(--m-safe-top,12px)+102px),var(--m-corner-clear,0px))] bottom-[calc(env(safe-area-inset-bottom,0px)+90px)] wide:bottom-[calc(env(safe-area-inset-bottom,0px)+12px)]">
|
||||
{!editing && <UpNextCard tl={tl} t={t} onOpen={openPlace} />}
|
||||
{editing && <EditHeader tl={tl} planner={planner} shell={shell} />}
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ export default function MRoadtripTab({ planner, shell }: MTripTabPanelProps) {
|
||||
// fall back to the trip's first routed day, which is not the one on screen, and every
|
||||
// distance it answered with would be measured against a road nobody is looking at.
|
||||
const searchBar = stage && (
|
||||
<div className="pointer-events-auto absolute inset-x-4 top-[calc(var(--m-safe-top,12px)+96px)] z-[26]">
|
||||
<div className="m-corner-beside pointer-events-auto absolute inset-x-4 top-[calc(var(--m-safe-top,12px)+96px)] z-[26]">
|
||||
<MRtCorridorBar planner={planner} corridor={corridor} onOpen={() => shell.openSheet('rtsearch')} />
|
||||
</div>
|
||||
)
|
||||
@@ -197,7 +197,7 @@ function RoadtripStagePage({ planner, shell, dayId: pageDayId, alts, chrome }: O
|
||||
return (
|
||||
<div
|
||||
className={`absolute inset-0 overflow-x-hidden overflow-y-auto overscroll-y-contain px-4 pb-[calc(var(--bottom-nav-h,84px)+22px)] ${
|
||||
stage ? 'pt-[calc(var(--m-safe-top,12px)+150px)]' : 'pt-[calc(var(--m-safe-top,12px)+102px)]'
|
||||
stage ? 'pt-[max(calc(var(--m-safe-top,12px)+150px),var(--m-corner-clear,0px))]' : 'pt-[max(calc(var(--m-safe-top,12px)+102px),var(--m-corner-clear,0px))]'
|
||||
}`}
|
||||
>
|
||||
<UndatedRides rides={undated} t={t} onOpen={openBooking} />
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { ArrowRight, Check, Hotel, MapPin, X } from 'lucide-react'
|
||||
import { ArrowRight, Check, Hotel, MapPin, Plus, X } from 'lucide-react'
|
||||
import MSheet from '../../../components/MSheet'
|
||||
import MIconBtn from '../../../components/MIconBtn'
|
||||
import CustomSelect from '../../../../components/shared/CustomSelect'
|
||||
@@ -88,6 +88,15 @@ export default function MAccommodationSheet({ planner, shell }: MTripSheetsProps
|
||||
|
||||
const filteredPlaces = stayPlaceChoices(places, form.place_id, categoryFilter)
|
||||
|
||||
// Same opener as the places tab's add button: a blank form, no prefilled position.
|
||||
const canAddPlace = planner.can('place_edit', planner.trip)
|
||||
const openAddPlace = () => {
|
||||
planner.setEditingPlace(null)
|
||||
planner.setEditingAssignmentId(null)
|
||||
planner.setPrefillCoords(null)
|
||||
planner.setShowPlaceForm(true)
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true)
|
||||
const body = stayRequestBody(form, range)
|
||||
@@ -204,9 +213,21 @@ export default function MAccommodationSheet({ planner, shell }: MTripSheetsProps
|
||||
{/* Place picker */}
|
||||
<Eyebrow className="mb-[6px] mt-3">{t('reservations.meta.pickHotel')}</Eyebrow>
|
||||
{filteredPlaces.length === 0 ? (
|
||||
<p className="rounded-[14px] bg-[color:var(--m-ic)] px-3 py-6 text-center font-geist text-[0.75rem] text-m-faint">
|
||||
{t('day.noPlacesForHotel')}
|
||||
</p>
|
||||
<div className="flex flex-col items-center gap-2.5 rounded-[14px] bg-[color:var(--m-ic)] px-3 py-5 text-center">
|
||||
<p className="font-geist text-[0.75rem] text-m-faint">{t('day.noPlacesForHotel')}</p>
|
||||
{/* A new trip has no place yet, and the stay needs one: the place form
|
||||
opens over this sheet and its place is listed here once saved. */}
|
||||
{canAddPlace && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={openAddPlace}
|
||||
className="flex items-center gap-1.5 rounded-full bg-m-act px-3.5 py-[7px] text-caption font-semibold text-m-actfg"
|
||||
>
|
||||
<Plus size={13} strokeWidth={2.4} />
|
||||
{t('planner.addPlace')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{filteredPlaces.map(p => {
|
||||
|
||||
@@ -11,6 +11,7 @@ import AirportSelect from '../../../../components/Planner/AirportSelect'
|
||||
import LocationSelect from '../../../../components/Planner/LocationSelect'
|
||||
import { toLocationPicks } from '../../../../components/Planner/locationPicks'
|
||||
import TransitSearchPanel from '../../../../components/Planner/TransitSearchPanel'
|
||||
import { getTransitDayPlaces } from '../../../../components/Planner/transitDayPlaces'
|
||||
import {
|
||||
EMPTY_TRANSPORT_FIELDS, TRANSPORT_TYPE_OPTIONS as TYPE_OPTIONS, emptyCarStop, emptyStationWaypoint, emptyWaypoint,
|
||||
transportDayOptions, type StationWaypointForm, type WaypointForm,
|
||||
@@ -21,7 +22,7 @@ import { useBookingFollowUp } from '../../../../components/Planner/useBookingFol
|
||||
import { useBookingExpenseIntent } from '../../../../components/Planner/useBookingExpenseIntent'
|
||||
import { Eyebrow, FIELD_CLS, FormSheetBody, FormSheetFooter, FormSheetHeader } from './PlSheetChrome'
|
||||
import MBookingFilesCosts from './MBookingFilesCosts'
|
||||
import type { Place, Reservation } from '../../../../types'
|
||||
import type { Reservation } from '../../../../types'
|
||||
import type { BookingReviewDraft } from '../../../../components/Planner/parsedItemToDraft'
|
||||
import type { BookingExpenseRequest } from '../../../../components/Planner/BookingCostsSection.types'
|
||||
import type { TripPlanner } from '../MTripShell'
|
||||
@@ -226,23 +227,21 @@ export default function MTransportFormSheet({ planner, onOpenExpense }: MTranspo
|
||||
if (!transitDay) {
|
||||
return <div className="mt-3 font-geist text-[0.78125rem] text-m-faint">{t('transit.pickDay')}</div>
|
||||
}
|
||||
// Quick picks offer the chosen day's itinerary, not the whole trip.
|
||||
const dayPlaces = (assignments[String(transitDay.id)] || [])
|
||||
.slice().sort((a, b) => a.order_index - b.order_index)
|
||||
.map(a => places.find(p => p.id === a.place_id))
|
||||
.filter((p): p is Place => p != null)
|
||||
const dayPlaces = getTransitDayPlaces(transitDay.id, assignments, places)
|
||||
const dayPrefill = transitDay.id === transportModalDayId ? transitPrefill : null
|
||||
return (
|
||||
<div className="mt-4">
|
||||
<TransitSearchPanel
|
||||
key={transitDay.id}
|
||||
day={transitDay}
|
||||
days={days}
|
||||
places={dayPlaces}
|
||||
accommodations={tripAccommodations}
|
||||
onAdd={(p) => saveTransport(p as Record<string, unknown> & { title: string })}
|
||||
initialFrom={transitPrefill?.from ?? null}
|
||||
initialTo={transitPrefill?.to ?? null}
|
||||
initialTime={transitPrefill?.time ?? null}
|
||||
walk={transitPrefill?.walk ?? null}
|
||||
initialFrom={dayPrefill?.from ?? null}
|
||||
initialTo={dayPrefill?.to ?? null}
|
||||
initialTime={dayPrefill?.time ?? null}
|
||||
walk={dayPrefill?.walk ?? null}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -16,7 +16,7 @@ import { useSearchParams } from 'react-router'
|
||||
import { isTransportReservationType } from '@trek/shared'
|
||||
import { useBookingLink } from '../../../../hooks/useBookingLink'
|
||||
import { bookingFacts, stayStats } from '../../../../components/Planner/bookings/bookingFacts'
|
||||
import { parseMeta } from '../../../../components/Planner/bookings/bookingsModel'
|
||||
import { bookingDates, parseMeta } from '../../../../components/Planner/bookings/bookingsModel'
|
||||
import { ActionCircle, Eyebrow, INNER_CLS, StatBox, TileHeader, displayTime } from './MTripSheetUi'
|
||||
import { CardFiles } from '../tabs/MReservationCardParts'
|
||||
import { downloadAttachment, openAttachment } from '../../../../components/Planner/bookings/openAttachment'
|
||||
@@ -131,9 +131,10 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
|
||||
const canEdit = liveRes != null && (isTransportReservationType(liveRes.type) ? canEditDays : canEditBookings)
|
||||
const ResIcon = RES_ICONS[res.type as keyof typeof RES_ICONS] || RES_ICONS.other
|
||||
|
||||
const from = (res.endpoints || []).find(e => e.role === 'from')
|
||||
const to = (res.endpoints || []).find(e => e.role === 'to')
|
||||
const { date, time: startTime } = splitReservationDateTime(res.reservation_time)
|
||||
const endpoints = res.endpoints || []
|
||||
const from = endpoints.find(e => e.role === 'from')
|
||||
const to = endpoints.find(e => e.role === 'to')
|
||||
const { time: startTime } = splitReservationDateTime(res.reservation_time)
|
||||
const { time: endTime } = splitReservationDateTime(res.reservation_end_time)
|
||||
const bookingDepTime = from?.local_time || startTime
|
||||
const bookingArrTime = to?.local_time || endTime
|
||||
@@ -151,6 +152,12 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
|
||||
const arrTime = leg ? leg.arr_time || '' : bookingArrTime
|
||||
const depLabel = (leg ? leg.from : from?.name) || t('reservations.time')
|
||||
const arrLabel = (leg ? leg.to : to?.name) || t('reservations.time')
|
||||
// The calendar date each time falls on (#3122): a time alone cannot be placed
|
||||
// when the sheet is opened from a compact list that shows nothing else.
|
||||
const legDate = (dayId?: number | null) => (dayId != null ? planner.days.find(d => d.id === dayId)?.date : null) || null
|
||||
const dates = leg ? { start: legDate(leg.dep_day_id), end: legDate(leg.arr_day_id) } : bookingDates(res, planner.days)
|
||||
const depDate = dates.start ? bookingDayLabel(dates.start, locale) : null
|
||||
const arrDate = dates.end ? bookingDayLabel(dates.end, locale) : null
|
||||
|
||||
const subParts: string[] = []
|
||||
const airline = leg ? legDetail.airline : meta.airline
|
||||
@@ -161,7 +168,6 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
|
||||
if (trainNumber) subParts.push(trainNumber)
|
||||
if (leg && (leg.from || leg.to)) subParts.push(flowText([leg.from, leg.to].filter((n): n is string => !!n)))
|
||||
else if (from?.name && to?.name) subParts.push(flowText([from.name, to.name]))
|
||||
else if (date) subParts.push(bookingDayLabel(date, locale))
|
||||
|
||||
// A flight's legs carry no seat or platform of their own, so those stay the booking's.
|
||||
const seat = leg && !isFlight ? legDetail.seat : meta.seat
|
||||
@@ -170,6 +176,11 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
|
||||
|
||||
// Opened from one leg's row, only that leg's live card; from the booking, every followed leg.
|
||||
const shownLive = leg ? liveLegs.filter(l => l.leg_index === payload.legIndex) : liveLegs
|
||||
const showTimes = shownLive.length === 0
|
||||
// A shown time box carries its own date. Without one (no time entered yet, or the
|
||||
// live card in its place) the subline names the day, route and airline or not.
|
||||
const datedTime = showTimes && ((depTime && depDate) || (arrTime && arrDate))
|
||||
if (depDate && !datedTime) subParts.push(depDate)
|
||||
|
||||
const resFiles = filesFor(res, planner.files || [])
|
||||
|
||||
@@ -263,13 +274,13 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
|
||||
))}
|
||||
|
||||
{/* ── Times / seat stats (the live card already shows the times) ── */}
|
||||
{hotelStats.length === 0 && ((shownLive.length === 0 && (depTime || arrTime)) || seat || platform) && (
|
||||
{hotelStats.length === 0 && ((showTimes && (depTime || arrTime)) || seat || platform) && (
|
||||
<div className="mt-[14px] flex gap-[6px]">
|
||||
{shownLive.length === 0 && depTime && (
|
||||
<StatBox value={displayTime(depTime, locale, timeFormat)} label={depLabel} />
|
||||
{showTimes && depTime && (
|
||||
<StatBox caption={depDate} value={displayTime(depTime, locale, timeFormat)} label={depLabel} />
|
||||
)}
|
||||
{shownLive.length === 0 && arrTime && (
|
||||
<StatBox value={displayTime(arrTime, locale, timeFormat)} label={arrLabel} />
|
||||
{showTimes && arrTime && (
|
||||
<StatBox caption={arrDate} value={displayTime(arrTime, locale, timeFormat)} label={arrLabel} />
|
||||
)}
|
||||
{platform && <StatBox value={platform} label={t('reservations.meta.platform')} />}
|
||||
{seat && <StatBox value={seat} label={t('reservations.meta.seat')} />}
|
||||
|
||||
@@ -121,6 +121,8 @@ export function TileHeader({ icon, title, sub, subWrap = false, onClose, closeLa
|
||||
interface StatBoxProps {
|
||||
value: ReactNode
|
||||
label: ReactNode
|
||||
/** A line above the value, such as the calendar date a time falls on. */
|
||||
caption?: ReactNode
|
||||
blurred?: boolean
|
||||
onClick?: () => void
|
||||
/** Colours the label, so a check-in or check-out time carries its own state. */
|
||||
@@ -133,10 +135,11 @@ const LABEL_TONE: Record<NonNullable<StatBoxProps['labelTone']>, string> = {
|
||||
}
|
||||
|
||||
/** Small stat box (check-in / times / code): value 700 tabular over a faint Geist label. */
|
||||
export function StatBox({ value, label, blurred = false, onClick, labelTone }: StatBoxProps) {
|
||||
export function StatBox({ value, label, caption, blurred = false, onClick, labelTone }: StatBoxProps) {
|
||||
const box = 'min-w-0 flex-1 rounded-[10px] bg-[color:var(--m-ic)] px-[9px] py-[7px] text-center'
|
||||
const inner = (
|
||||
<>
|
||||
{caption && <div className="truncate font-geist text-caption leading-tight text-m-muted">{caption}</div>}
|
||||
<div
|
||||
className={`truncate text-[0.8125rem] font-bold tabular-nums leading-tight ${blurred ? 'blur-[4px] select-none' : ''}`}
|
||||
>
|
||||
|
||||
@@ -91,7 +91,7 @@ export default function MCollabChat({ planner }: MCollabChatProps) {
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex h-full flex-col px-4 pb-[var(--bottom-nav-h,84px)] pt-[calc(var(--m-safe-top,12px)+58px)] wide:mx-auto wide:w-full wide:max-w-[808px] wide:px-6 wide:pb-[calc(var(--bottom-nav-h,0px)+12px)]"
|
||||
className="flex h-full flex-col px-4 pb-[var(--bottom-nav-h,84px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))] wide:mx-auto wide:w-full wide:max-w-[808px] wide:px-6 wide:pb-[calc(var(--bottom-nav-h,0px)+12px)]"
|
||||
style={keyboard > 0 ? { paddingBottom: keyboard + 8 } : undefined}
|
||||
>
|
||||
{loading ? (
|
||||
|
||||
@@ -74,7 +74,7 @@ function CollabPanel({ planner, tab }: { planner: MTabScreenProps['planner']; ta
|
||||
if (tab === 'chat') {
|
||||
if (!planner.collabFeatures.chat) {
|
||||
return (
|
||||
<div className="flex h-full flex-col px-4 pb-[var(--bottom-nav-h,84px)] pt-[calc(var(--m-safe-top,12px)+58px)]">
|
||||
<div className="flex h-full flex-col px-4 pb-[var(--bottom-nav-h,84px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]">
|
||||
<CollabDisabledNotice icon={MessageCircle} label={label} />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -265,12 +265,12 @@ export default function MFilesTab({ planner, shell }: MTabScreenProps) {
|
||||
if (split && picked) {
|
||||
return (
|
||||
<div className="flex h-full">
|
||||
<div className="min-h-0 min-w-0 flex-1 overflow-y-auto overflow-x-hidden pb-[calc(var(--bottom-nav-h,84px)+22px)] pe-3 ps-6 pt-[calc(var(--m-safe-top,12px)+58px)]">
|
||||
<div className="min-h-0 min-w-0 flex-1 overflow-y-auto overflow-x-hidden pb-[calc(var(--bottom-nav-h,84px)+22px)] pe-3 ps-6 pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]">
|
||||
{body}
|
||||
</div>
|
||||
<aside
|
||||
aria-label={t('common.preview')}
|
||||
className="m-pane-trail min-h-0 flex-none overflow-y-auto overflow-x-hidden border-s border-[color:var(--m-rowbr)] px-5 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[calc(var(--m-safe-top,12px)+58px)]"
|
||||
className="m-pane-trail min-h-0 flex-none overflow-y-auto overflow-x-hidden border-s border-[color:var(--m-rowbr)] px-5 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]"
|
||||
>
|
||||
<FilePreviewPane
|
||||
file={picked}
|
||||
|
||||
@@ -37,7 +37,7 @@ export default function MTripTabPanel({ planner, shell, tab }: MTripTabPanelProp
|
||||
if (tab.startsWith('plugin:')) {
|
||||
return (
|
||||
<div
|
||||
className="absolute inset-0 pt-[calc(var(--m-safe-top,12px)+58px)] pb-[calc(var(--bottom-nav-h,84px)+22px)]"
|
||||
className="absolute inset-0 pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))] pb-[calc(var(--bottom-nav-h,84px)+22px)]"
|
||||
>
|
||||
<PluginFrame
|
||||
pluginId={tab.slice('plugin:'.length)}
|
||||
|
||||
@@ -33,8 +33,8 @@ export function TabScroller({ children, wide = 'readable' }: { children: ReactNo
|
||||
}
|
||||
|
||||
/** The room a tab's scroll body keeps clear: the floating top controls above, the dock (or the home indicator) below. */
|
||||
const TAB_INSETS = 'px-4 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[calc(var(--m-safe-top,12px)+58px)] wide:px-6'
|
||||
const PANE_INSETS = 'pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[calc(var(--m-safe-top,12px)+58px)]'
|
||||
const TAB_INSETS = 'px-4 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))] wide:px-6'
|
||||
const PANE_INSETS = 'pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]'
|
||||
|
||||
/**
|
||||
* The cards of a list tab (transports, bookings, tasks, polls): one column on a
|
||||
|
||||
@@ -91,9 +91,9 @@ export default function MVacay() {
|
||||
|
||||
return (
|
||||
// h-dvh, not h-full: the shell stopped providing a definite height (#1809).
|
||||
<div className="relative h-dvh">
|
||||
{/* Header */}
|
||||
<div className="absolute inset-x-4 z-[5] flex items-center gap-2 top-[var(--m-safe-top,12px)]">
|
||||
<div className="m-corner-own relative h-dvh">
|
||||
{/* Header, beside a corner element (a Duo's status capsule) upright */}
|
||||
<div className="m-corner-beside-in absolute inset-x-4 z-[5] flex items-center gap-2 top-[var(--m-safe-top,12px)]">
|
||||
<MIconBtn onClick={() => v.setSheet('invite')} ariaLabel={t('vacay.inviteUser')}>
|
||||
<UserPlus size={16} strokeWidth={2} className="text-m-muted" />
|
||||
</MIconBtn>
|
||||
@@ -115,7 +115,7 @@ export default function MVacay() {
|
||||
</div>
|
||||
|
||||
{/* Scroll container */}
|
||||
<div className={`absolute inset-0 overflow-y-auto px-4 pt-[calc(var(--m-safe-top,12px)+44px)] pb-[calc(var(--bottom-nav-h,84px)+12px)] ${edit ? 'wide:pb-[calc(env(safe-area-inset-bottom,0px)+84px)]' : ''}`}>
|
||||
<div className={`absolute inset-0 overflow-y-auto px-4 pt-[max(calc(var(--m-safe-top,12px)+44px),var(--m-corner-clear,0px))] pb-[calc(var(--bottom-nav-h,84px)+12px)] ${edit ? 'wide:pb-[calc(env(safe-area-inset-bottom,0px)+84px)]' : ''}`}>
|
||||
{/* Selected person card */}
|
||||
{v.selectedUser && stat && (
|
||||
<div className="mt-2 flex items-center gap-3 rounded-[18px] border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] px-[14px] py-[9px]">
|
||||
|
||||
@@ -143,3 +143,56 @@ describe('closeOnDone', () => {
|
||||
expect(document.activeElement).toBe(handled);
|
||||
});
|
||||
});
|
||||
|
||||
describe('closeOnTapAway', () => {
|
||||
function touch(target: Element, type: 'touchstart' | 'touchend', x: number, y: number) {
|
||||
const e = new Event(type, { bubbles: true, cancelable: true });
|
||||
const point = [{ clientX: x, clientY: y }];
|
||||
Object.defineProperty(e, type === 'touchstart' ? 'touches' : 'changedTouches', { value: point });
|
||||
if (type === 'touchend') Object.defineProperty(e, 'touches', { value: [] });
|
||||
target.dispatchEvent(e);
|
||||
}
|
||||
function tap(target: Element, moveBy = 0) {
|
||||
touch(target, 'touchstart', 100, 100);
|
||||
touch(target, 'touchend', 100, 100 + moveBy);
|
||||
}
|
||||
function sheet(): { notes: HTMLTextAreaElement; title: HTMLInputElement; label: HTMLElement; stop: () => void } {
|
||||
document.body.innerHTML =
|
||||
'<div><p id="label">Notes for this day</p><textarea id="notes"></textarea><input id="title"></div>';
|
||||
const stop = prepareKeyboardFields(document);
|
||||
return {
|
||||
notes: document.getElementById('notes') as HTMLTextAreaElement,
|
||||
title: document.getElementById('title') as HTMLInputElement,
|
||||
label: document.getElementById('label') as HTMLElement,
|
||||
stop,
|
||||
};
|
||||
}
|
||||
|
||||
it('closes the keyboard of a textarea when the sheet beside it is tapped', () => {
|
||||
const { notes, label, stop } = sheet();
|
||||
notes.focus();
|
||||
tap(label);
|
||||
expect(document.activeElement).not.toBe(notes);
|
||||
stop();
|
||||
});
|
||||
|
||||
it('keeps it while the finger scrolls, taps the field itself or moves to another field', () => {
|
||||
const { notes, title, label, stop } = sheet();
|
||||
notes.focus();
|
||||
tap(label, 40);
|
||||
expect(document.activeElement).toBe(notes);
|
||||
tap(notes);
|
||||
expect(document.activeElement).toBe(notes);
|
||||
tap(title);
|
||||
expect(document.activeElement).toBe(notes);
|
||||
stop();
|
||||
});
|
||||
|
||||
it('stops listening when told to', () => {
|
||||
const { notes, label, stop } = sheet();
|
||||
stop();
|
||||
notes.focus();
|
||||
tap(label);
|
||||
expect(document.activeElement).toBe(notes);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,6 +24,9 @@
|
||||
* nothing. When no handler took the Enter (the field still has focus and the
|
||||
* same text a moment later) the field lets go of the focus. A field that acts
|
||||
* on Enter and clears itself, such as a list that adds the next item, keeps it.
|
||||
*
|
||||
* A tap away from any field closes the keyboard too, which is the only way out of
|
||||
* a textarea: its return key writes a new line.
|
||||
*/
|
||||
|
||||
const SKIP_TYPES = new Set([
|
||||
@@ -127,6 +130,43 @@ function closeOnDone(e: KeyboardEvent): void {
|
||||
}, 0);
|
||||
}
|
||||
|
||||
/** A field that holds the keyboard open while it has the focus. */
|
||||
function typedInto(el: Element | null): el is HTMLElement {
|
||||
if (el instanceof HTMLTextAreaElement) return !el.readOnly;
|
||||
if (el instanceof HTMLInputElement) return !SKIP_TYPES.has(el.type) && !el.readOnly;
|
||||
return el instanceof HTMLElement && el.isContentEditable;
|
||||
}
|
||||
|
||||
const EDITABLE = 'input, textarea, select, [contenteditable]:not([contenteditable="false"])';
|
||||
/** How far a finger may travel and still count as a tap rather than a scroll, in CSS pixels. */
|
||||
const TAP_SLOP = 10;
|
||||
|
||||
/**
|
||||
* A tap away from the field closes the keyboard. A textarea keeps its return key
|
||||
* for new lines, and the app hides the keyboard's bar with its "done" button, so
|
||||
* otherwise nothing closes it and it covers the rest of the sheet. A tap on another
|
||||
* field moves the focus there instead, and a scroll leaves the keyboard open.
|
||||
*/
|
||||
function closeOnTapAway(doc: Document): { start: (e: TouchEvent) => void; end: (e: TouchEvent) => void } {
|
||||
let from: { x: number; y: number } | null = null;
|
||||
return {
|
||||
start(e) {
|
||||
const touch = e.touches[0];
|
||||
from = e.touches.length === 1 && touch ? { x: touch.clientX, y: touch.clientY } : null;
|
||||
},
|
||||
end(e) {
|
||||
const touch = e.changedTouches[0];
|
||||
const tapped = from && touch && Math.hypot(touch.clientX - from.x, touch.clientY - from.y) <= TAP_SLOP;
|
||||
from = null;
|
||||
const field = doc.activeElement;
|
||||
if (!tapped || !typedInto(field)) return;
|
||||
const target = e.target instanceof Element ? e.target : null;
|
||||
if (target && (field.contains(target) || target.closest(EDITABLE))) return;
|
||||
field.blur();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function prepareKeyboardFields(doc: Document = document): () => void {
|
||||
// On the touch, before the focus: the keyboard is set up as the field takes it.
|
||||
const onTouch = (e: Event) => prepareField(e.target instanceof Element ? e.target.closest('input') : null);
|
||||
@@ -135,7 +175,12 @@ export function prepareKeyboardFields(doc: Document = document): () => void {
|
||||
doc.addEventListener('focusin', onFocus, true);
|
||||
// Capturing, so the text is read before the field's own handler can change it.
|
||||
doc.addEventListener('keydown', closeOnDone, true);
|
||||
const tapAway = closeOnTapAway(doc);
|
||||
doc.addEventListener('touchstart', tapAway.start, { capture: true, passive: true });
|
||||
doc.addEventListener('touchend', tapAway.end, { capture: true, passive: true });
|
||||
return () => {
|
||||
doc.removeEventListener('touchstart', tapAway.start, { capture: true });
|
||||
doc.removeEventListener('touchend', tapAway.end, { capture: true });
|
||||
doc.removeEventListener('touchstart', onTouch, { capture: true });
|
||||
doc.removeEventListener('focusin', onFocus, true);
|
||||
doc.removeEventListener('keydown', closeOnDone, true);
|
||||
|
||||
@@ -18,8 +18,11 @@ import {
|
||||
liveDayDue,
|
||||
pickTrip,
|
||||
publishWidgets,
|
||||
snapshotDays,
|
||||
todayOf,
|
||||
tripDaysFrom,
|
||||
tripDayState,
|
||||
WIDGET_DAYS_AHEAD,
|
||||
widgetTripChoices,
|
||||
withBookings,
|
||||
} from './widgets';
|
||||
@@ -405,3 +408,90 @@ describe('widgets set to a trip', () => {
|
||||
expect(JSON.parse(calls[2].json)).toEqual([{ id: 2, title: 'Trip 2', start: '2026-12-01', end: '2026-12-05' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the days ahead, for a widget that turns the day itself', () => {
|
||||
const tripDays = [
|
||||
day(1, 1, '2026-11-06', [{ name: 'Museum', time: '09:00' }]),
|
||||
day(2, 2, '2026-11-07', [{ name: 'Harbour', time: '10:00' }, { name: 'Market' }]),
|
||||
day(3, 3, '2026-11-08', []),
|
||||
];
|
||||
const label = (n: number, m: number) => `${n}/${m}`;
|
||||
|
||||
it('FE-NATIVE-WDAYS-001: carries every day from today on with its date, label and stops', () => {
|
||||
const ahead = tripDaysFrom(trip(1, '2026-11-06', '2026-11-08'), tripDays, {
|
||||
reservations: [],
|
||||
from: '2026-11-07',
|
||||
dayLabel: label,
|
||||
formatTime: (t) => t,
|
||||
});
|
||||
expect(ahead.map((d) => [d.date, d.dayLabel, d.stops.map((s) => s.name)])).toEqual([
|
||||
['2026-11-07', '2/3', ['Harbour', 'Market']],
|
||||
['2026-11-08', '3/3', []],
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-NATIVE-WDAYS-002: joins each day to the bookings of its own date', () => {
|
||||
const reservations = [
|
||||
{ id: 1, type: 'restaurant', title: 'Dinner', status: 'confirmed', reservation_time: '2026-11-08T19:30' },
|
||||
] as never;
|
||||
const ahead = tripDaysFrom(trip(1, '2026-11-06', '2026-11-08'), tripDays, {
|
||||
reservations,
|
||||
from: '2026-11-06',
|
||||
dayLabel: label,
|
||||
formatTime: (t) => t,
|
||||
});
|
||||
expect(ahead.find((d) => d.date === '2026-11-08')?.stops.map((s) => s.name)).toEqual(['Dinner']);
|
||||
expect(ahead.find((d) => d.date === '2026-11-06')?.stops.map((s) => s.name)).toEqual(['Museum']);
|
||||
});
|
||||
|
||||
it('FE-NATIVE-WDAYS-003: holds a month at most and nothing of a trip that is over', () => {
|
||||
const long = Array.from({ length: 40 }, (_, i) =>
|
||||
day(i + 1, i + 1, `2026-12-${String(i + 1).padStart(2, '0')}`, [])
|
||||
).map((d, i) => (i >= 31 ? { ...d, date: `2027-01-${String(i - 30).padStart(2, '0')}` } : d)) as Day[];
|
||||
const t = trip(1, '2026-12-01', '2027-01-09');
|
||||
expect(
|
||||
tripDaysFrom(t, long, { reservations: [], from: '2026-12-01', dayLabel: label, formatTime: (x) => x })
|
||||
).toHaveLength(WIDGET_DAYS_AHEAD);
|
||||
expect(
|
||||
tripDaysFrom(t, long, { reservations: [], from: '2027-02-01', dayLabel: label, formatTime: (x) => x })
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it('FE-NATIVE-WDAYS-004: the snapshot has today with its date and the days ahead, each held to 16 stops', () => {
|
||||
const busy = day(
|
||||
4,
|
||||
1,
|
||||
'2026-11-06',
|
||||
Array.from({ length: 20 }, (_, i) => ({ name: `Stop ${i}` }))
|
||||
);
|
||||
const t = trip(1, '2026-11-06', '2026-11-06');
|
||||
const ahead = tripDaysFrom(t, [busy], {
|
||||
reservations: [],
|
||||
from: '2026-11-06',
|
||||
dayLabel: label,
|
||||
formatTime: (x) => x,
|
||||
});
|
||||
const snapshot = buildSnapshot(t, ahead[0] ?? null, labels, { days: ahead });
|
||||
expect(snapshot.today?.date).toBe('2026-11-06');
|
||||
// Today stays whole, as the app has always written it; the days ahead keep their first 16.
|
||||
expect(snapshot.today?.stops).toHaveLength(20);
|
||||
expect(snapshot.days?.[0]).toMatchObject({ date: '2026-11-06', dayLabel: '1/1' });
|
||||
expect(snapshot.days?.[0]?.stops).toHaveLength(16);
|
||||
});
|
||||
|
||||
it('FE-NATIVE-WDAYS-005: a snapshot without days ahead leaves the field out', () => {
|
||||
expect(buildSnapshot(trip(1, '2026-11-06', '2026-11-08'), null, labels, { days: [] })).not.toHaveProperty('days');
|
||||
});
|
||||
|
||||
it('FE-NATIVE-WDAYS-006: today is the first day ahead while the trip runs today, none before it starts or without a trip', () => {
|
||||
const options = { reservations: [], dayLabel: label, formatTime: (x: string) => x };
|
||||
const t = trip(1, '2026-11-06', '2026-11-08');
|
||||
const running = snapshotDays(t, tripDays, { ...options, from: '2026-11-07' });
|
||||
expect(running.today?.date).toBe('2026-11-07');
|
||||
expect(running.ahead).toHaveLength(2);
|
||||
const before = snapshotDays(t, tripDays, { ...options, from: '2026-11-01' });
|
||||
expect(before.today).toBeNull();
|
||||
expect(before.ahead.map((d) => d.date)).toEqual(['2026-11-06', '2026-11-07', '2026-11-08']);
|
||||
expect(snapshotDays(null, tripDays, { ...options, from: '2026-11-07' })).toEqual({ today: null, ahead: [] });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -104,7 +104,14 @@ export interface WidgetSnapshot {
|
||||
placeCount?: number;
|
||||
memberCount?: number;
|
||||
} | null;
|
||||
today: { dayLabel: string; stops: SnapshotStop[]; index?: number; total?: number } | null;
|
||||
today: SnapshotDay | null;
|
||||
/**
|
||||
* Every day of the trip from the day it was written on, each with its date,
|
||||
* so a widget turns to the next day by itself at midnight instead of showing
|
||||
* the day the app last ran until it is opened again. A binary without it
|
||||
* reads `today` as before.
|
||||
*/
|
||||
days?: SnapshotDay[];
|
||||
weather?: WidgetWeather;
|
||||
bookings?: WidgetBooking[];
|
||||
todos?: WidgetTodos;
|
||||
@@ -128,7 +135,18 @@ export interface WidgetWeather {
|
||||
}
|
||||
|
||||
/** What goes along with the trip beyond its day; each part optional. */
|
||||
/** A trip day as the widgets read it; `date` (yyyy-MM-dd) says which day of the calendar it is. */
|
||||
interface SnapshotDay {
|
||||
date?: string;
|
||||
dayLabel: string;
|
||||
stops: SnapshotStop[];
|
||||
index?: number;
|
||||
total?: number;
|
||||
}
|
||||
|
||||
interface SnapshotExtras {
|
||||
/** The trip's days from today on (tripDaysFrom), for the widgets to turn the day themselves. */
|
||||
days?: TripDay[];
|
||||
place?: string | null;
|
||||
cover?: string | null;
|
||||
placeCount?: number;
|
||||
@@ -152,8 +170,15 @@ export interface TripDay {
|
||||
/** 1-based position of the day in the trip, and the trip's day count. */
|
||||
index?: number;
|
||||
total?: number;
|
||||
/** The calendar day it is, yyyy-MM-dd. */
|
||||
date?: string;
|
||||
}
|
||||
|
||||
/** How many days ahead a snapshot carries: a month of a trip without the app being opened. */
|
||||
export const WIDGET_DAYS_AHEAD = 31;
|
||||
/** The stops a day carries at most, which is more than the largest widget shows. */
|
||||
const WIDGET_DAY_STOPS = 16;
|
||||
|
||||
/** iOS (WidgetKit) and Android (Glance) read the same snapshot. */
|
||||
export function widgetsActive(): boolean {
|
||||
return isNativeApp() && hasNativeFeature('widgets');
|
||||
@@ -243,9 +268,45 @@ export function todayOf(
|
||||
dayId: day.id,
|
||||
index: index + 1,
|
||||
total: ordered.length,
|
||||
date: today,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The trip's days from `from` on, each with its stops and its timed bookings, at
|
||||
* most WIDGET_DAYS_AHEAD of them: what a widget needs to show the right day on
|
||||
* the days the app is not opened.
|
||||
*/
|
||||
/** What tripDaysFrom reads besides the trip and its days. */
|
||||
interface DaysFromOptions {
|
||||
reservations: Reservation[];
|
||||
/** The first date, yyyy-MM-dd: today. */
|
||||
from: string;
|
||||
dayLabel: (index: number, total: number) => string;
|
||||
formatTime: (time: string) => string;
|
||||
}
|
||||
|
||||
export function tripDaysFrom(
|
||||
trip: Trip,
|
||||
days: Day[],
|
||||
{ reservations, from, dayLabel, formatTime }: DaysFromOptions
|
||||
): TripDay[] {
|
||||
const dates = [
|
||||
...new Set(
|
||||
days
|
||||
.filter((d) => d.trip_id === trip.id)
|
||||
.map((d) => (d.date ?? '').slice(0, 10))
|
||||
.filter((date) => date >= from)
|
||||
),
|
||||
]
|
||||
.sort((a, b) => a.localeCompare(b))
|
||||
.slice(0, WIDGET_DAYS_AHEAD);
|
||||
return dates.flatMap((date) => {
|
||||
const day = todayOf(trip, days, date, dayLabel, formatTime);
|
||||
return day ? [withBookings(day, reservations, date, formatTime)] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** The day with its timed bookings (a flight, the table tonight) joined to the stops in time order. */
|
||||
export function withBookings(
|
||||
day: TripDay,
|
||||
@@ -303,6 +364,29 @@ function snapshotStop({ time, name, minutes, color, symbol }: WidgetStop): Snaps
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The days a trip's snapshot carries: `today` while the trip runs today, and
|
||||
* every day from today on for the widgets to turn to by themselves.
|
||||
*/
|
||||
export function snapshotDays(
|
||||
trip: Trip | null,
|
||||
days: Day[],
|
||||
options: DaysFromOptions
|
||||
): { today: TripDay | null; ahead: TripDay[] } {
|
||||
const ahead = trip ? tripDaysFrom(trip, days, options) : [];
|
||||
return { today: ahead[0]?.date === options.from ? ahead[0] : null, ahead };
|
||||
}
|
||||
|
||||
/** A day for the snapshot; the days ahead keep their first `limit` stops, so a month of them stays small. */
|
||||
function snapshotDay(day: TripDay, limit = day.stops.length): SnapshotDay {
|
||||
return {
|
||||
...(day.date ? { date: day.date } : {}),
|
||||
dayLabel: day.dayLabel,
|
||||
stops: day.stops.slice(0, limit).map(snapshotStop),
|
||||
...(day.index ? { index: day.index, total: day.total } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildSnapshot(
|
||||
trip: Trip | null,
|
||||
day: TripDay | null,
|
||||
@@ -323,15 +407,10 @@ export function buildSnapshot(
|
||||
...(extras.memberCount ? { memberCount: extras.memberCount } : {}),
|
||||
}
|
||||
: null,
|
||||
today: day
|
||||
? {
|
||||
dayLabel: day.dayLabel,
|
||||
stops: day.stops.map(snapshotStop),
|
||||
...(day.index ? { index: day.index, total: day.total } : {}),
|
||||
}
|
||||
: null,
|
||||
today: day ? snapshotDay(day) : null,
|
||||
labels,
|
||||
};
|
||||
if (extras.days?.length) snapshot.days = extras.days.map((d) => snapshotDay(d, WIDGET_DAY_STOPS));
|
||||
if (extras.weather) snapshot.weather = extras.weather;
|
||||
if (extras.bookings) snapshot.bookings = extras.bookings;
|
||||
if (extras.todos) snapshot.todos = extras.todos;
|
||||
|
||||
@@ -96,4 +96,47 @@ describe('useAssistantTabLink', () => {
|
||||
expect(setupTab('tab=collab', 'plan').onLinked).toHaveBeenCalledWith('collab');
|
||||
expect(setupTab('tab=collab', 'collab').onLinked).toHaveBeenCalledWith('collab');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-ASSISTLINK-008: a link is taken once while the cleaned URL is still on its way', () => {
|
||||
// React Router lands the URL without the link as a transition: until then
|
||||
// the hook keeps reading the link, with a new selectTab on every render.
|
||||
const searchParams = new URLSearchParams('tab=collab');
|
||||
const setSearchParams = vi.fn();
|
||||
const onLinked = vi.fn();
|
||||
const selects: ReturnType<typeof vi.fn>[] = [];
|
||||
const { rerender } = renderHook(() => {
|
||||
const selectTab = vi.fn();
|
||||
selects.push(selectTab);
|
||||
useAssistantTabLink({
|
||||
searchParams,
|
||||
setSearchParams: setSearchParams as never,
|
||||
activeTab: 'plan',
|
||||
selectTab,
|
||||
onLinked,
|
||||
});
|
||||
});
|
||||
rerender();
|
||||
rerender();
|
||||
expect(selects.filter((select) => select.mock.calls.length > 0)).toHaveLength(1);
|
||||
expect(onLinked).toHaveBeenCalledTimes(1);
|
||||
expect(setSearchParams).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-ASSISTLINK-009: the same link in a new URL is taken again', () => {
|
||||
const setSearchParams = vi.fn();
|
||||
const onLinked = vi.fn();
|
||||
const { rerender } = renderHook(
|
||||
({ query }) =>
|
||||
useAssistantTabLink({
|
||||
searchParams: new URLSearchParams(query),
|
||||
setSearchParams: setSearchParams as never,
|
||||
activeTab: 'plan',
|
||||
selectTab: vi.fn(),
|
||||
onLinked,
|
||||
}),
|
||||
{ initialProps: { query: 'tab=collab' } }
|
||||
);
|
||||
rerender({ query: 'tab=collab' });
|
||||
expect(onLinked).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
import { isDeepLinkableTripTab } from '../../constants/tripTabs';
|
||||
import { useAssistantStore } from '../../store/assistantStore';
|
||||
@@ -37,8 +37,14 @@ export function useAssistantDeepLink({
|
||||
const known = requestedDay !== null && tripDays.some((day) => day.id === Number(requestedDay));
|
||||
const dayDone = requestedDay !== null && (known || tripDays.length > 0);
|
||||
|
||||
const taken = useRef<URLSearchParams | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!openRequested && !dayDone) return;
|
||||
// Once per URL: React Router lands the cleaned URL as a transition, and
|
||||
// until it does the link must not be taken again (see useAssistantTabLink).
|
||||
if (taken.current === searchParams) return;
|
||||
taken.current = searchParams;
|
||||
if (openRequested) useAssistantStore.getState().open();
|
||||
if (known) selectDay(Number(requestedDay));
|
||||
setSearchParams(
|
||||
@@ -49,7 +55,7 @@ export function useAssistantDeepLink({
|
||||
},
|
||||
{ replace: true }
|
||||
);
|
||||
}, [openRequested, requestedDay, known, dayDone, selectDay, setSearchParams]);
|
||||
}, [searchParams, openRequested, requestedDay, known, dayDone, selectDay, setSearchParams]);
|
||||
}
|
||||
|
||||
interface AssistantTabLinkOptions {
|
||||
@@ -79,9 +85,17 @@ export function useAssistantTabLink({
|
||||
}: AssistantTabLinkOptions): void {
|
||||
const requested = searchParams.get('tab');
|
||||
const linkable = requested !== null && isDeepLinkableTripTab(requested);
|
||||
const taken = useRef<URLSearchParams | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (requested === null) return;
|
||||
// Once per URL. React Router lands the URL without the link as a
|
||||
// transition, so the renders before it still read the link; selectTab is a
|
||||
// new function on each of them and onLinked sets state, and taking the link
|
||||
// again on every one of them rendered the planner into React's update limit
|
||||
// (a ?tab= link on an iPad or an unfolded Duo).
|
||||
if (taken.current === searchParams) return;
|
||||
taken.current = searchParams;
|
||||
if (linkable) {
|
||||
if (requested !== activeTab) selectTab(requested);
|
||||
onLinked?.(requested);
|
||||
@@ -93,5 +107,5 @@ export function useAssistantTabLink({
|
||||
},
|
||||
{ replace: true }
|
||||
);
|
||||
}, [linkable, requested, activeTab, selectTab, onLinked, setSearchParams]);
|
||||
}, [searchParams, linkable, requested, activeTab, selectTab, onLinked, setSearchParams]);
|
||||
}
|
||||
|
||||
@@ -507,7 +507,7 @@ describe('MSheet', () => {
|
||||
<span>body</span>
|
||||
</MSheet>,
|
||||
);
|
||||
expect(region().className).toContain('top-[var(--m-safe-top,12px)]');
|
||||
expect(region().className).toContain('top-[max(var(--m-safe-top,12px),var(--m-corner-clear,0px))]');
|
||||
expect(region().className).toContain('bottom-[calc(var(--bottom-nav-h,84px)+12px)]');
|
||||
expect(panel().className).toContain('max-h-full');
|
||||
});
|
||||
|
||||
@@ -108,9 +108,58 @@ describe('safe area in the touch shell', () => {
|
||||
expect(css).toContain('--m-page-r: max(0px, var(--m-safe-r) - var(--trek-native-corner-right, 0px));');
|
||||
expect(css).toContain('--m-page-l: max(0px, var(--m-safe-l) - var(--trek-native-corner-left, 0px));');
|
||||
expect(css.split('\n.m-page {')[1]?.split('}')[0] ?? '').toContain(
|
||||
'padding-top: max(0px, calc(var(--m-corner-b, 0px) + 12px - var(--m-safe-top, 12px) - 70px));'
|
||||
'padding-top: max(0px, calc(var(--m-corner-clear, 0px) + 2px - var(--m-safe-top, 12px) - 70px));'
|
||||
);
|
||||
expect(css).toContain('--m-corner-clear: calc(var(--m-corner-b) + min(var(--m-corner-b), 10px));');
|
||||
// Without a corner element (every other device, iOS before 26) nothing moves.
|
||||
expect(css).toContain('--m-corner-b: var(--trek-native-corner-bottom, 0px);');
|
||||
});
|
||||
|
||||
it('FE-MOB-CHROME-010: on a wide window the page ends before a corner element instead of starting below it', () => {
|
||||
const wideRoot = "html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {";
|
||||
const block = css.split(wideRoot)[1]?.split('}')[0] ?? '';
|
||||
expect(block).toContain('--m-corner-clear: 0px;');
|
||||
expect(block).toContain('--m-corner-side-r: var(--m-corner-r-gap);');
|
||||
expect(block).toContain('--m-rail-w: calc(var(--m-bar-l) + 100px);');
|
||||
const widePage = "html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-page {";
|
||||
expect(css.split(widePage)[1]?.split('}')[0] ?? '').toContain(
|
||||
'margin-inline-end: max(var(--m-page-r, 0px), var(--m-corner-side-r, 0px));'
|
||||
);
|
||||
// Right to left the rail stands on the corner's side and takes it.
|
||||
const rtlRoot = "html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {";
|
||||
const rtl = css.split(rtlRoot)[1]?.split('}')[0] ?? '';
|
||||
expect(rtl).toContain('--m-rail-w: calc(var(--m-bar-r) + 100px);');
|
||||
expect(rtl).toContain('--m-corner-side-r: 0px;');
|
||||
});
|
||||
|
||||
it('FE-MOB-CHROME-011: the screens that place their own controls keep them beside a corner element and their content below it', () => {
|
||||
const corner = readFileSync(resolve(root, 'src/mobile/corner.css'), 'utf8');
|
||||
expect(corner).toMatch(
|
||||
/\.m-corner-beside \{\s*margin-inline: var\(--m-corner-l-gap, 0px\) var\(--m-corner-r-gap, 0px\);/
|
||||
);
|
||||
// The element stays where the hardware has it, so right to left swaps the sides back.
|
||||
expect(corner).toMatch(
|
||||
/html\[dir='rtl'\] \.m-corner-beside \{\s*margin-inline: var\(--m-corner-r-gap, 0px\) var\(--m-corner-l-gap, 0px\);/
|
||||
);
|
||||
expect(corner).toMatch(
|
||||
/\.m-corner-side \{\s*margin-inline: var\(--m-corner-side-l, 0px\) var\(--m-corner-side-r, 0px\);/
|
||||
);
|
||||
expect(css).toMatch(/\.m-page:has\(\.m-corner-own\) \{\s*padding-top: 0;/);
|
||||
expect(readFileSync(resolve(root, 'src/mobile/MobileShell.tsx'), 'utf8')).toContain("import './corner.css'");
|
||||
const src = (file: string) => readFileSync(resolve(root, 'src', file), 'utf8');
|
||||
const shell = src('mobile/screens/trip/MTripShell.tsx');
|
||||
// The top row and the day chips stand beside it, a list tab ends before it on a wide window.
|
||||
expect(src('mobile/screens/trip/MTripShellParts.tsx')).toContain("CHROME_ROW = 'm-corner-beside absolute end-4");
|
||||
expect(shell.match(/\$\{CHROME_ROW\}/g)).toHaveLength(2);
|
||||
expect(shell).toContain('<div className="m-corner-side relative h-full">');
|
||||
expect(src('mobile/screens/trip/map/MMapArea.tsx')).toContain('m-corner-beside pointer-events-none absolute end-4');
|
||||
// A list tab's first row and a docked sheet start below it.
|
||||
expect(src('mobile/screens/trip/tabs/tabChrome.tsx')).toContain(
|
||||
'pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]'
|
||||
);
|
||||
expect(src('mobile/components/MSheet.tsx')).toContain(
|
||||
'top-[max(calc(var(--m-safe-top,12px)+56px),var(--m-corner-clear,0px))]'
|
||||
);
|
||||
expect(src('mobile/components/MSectionNav.tsx')).toContain("'m-corner-flow px-4 ");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,7 +8,7 @@ import { useSettingsStore } from '../../../../src/store/settingsStore'
|
||||
import { isBlurred } from '../../../helpers/bookingCodeBlur'
|
||||
import { act, fireEvent, render, screen, waitFor } from '../../../helpers/render'
|
||||
|
||||
// FE-MOB-ACCSH-001 to FE-MOB-ACCSH-031
|
||||
// FE-MOB-ACCSH-001 to FE-MOB-ACCSH-033
|
||||
|
||||
// The pickers have their own suites; here they only need to be addressable, so
|
||||
// they render as plain controls. data-value keeps the requested value readable
|
||||
@@ -256,6 +256,22 @@ describe('MAccommodationSheet', () => {
|
||||
expect(screen.getByText('Add places to your trip first')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-MOB-ACCSH-032: a trip without places offers to add one instead of a dead end', () => {
|
||||
const { planner } = setup(makePlanner({ places: [] }))
|
||||
expect(screen.getByText('Add places to your trip first')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add place/activity' }))
|
||||
|
||||
expect(planner.setEditingPlace).toHaveBeenCalledWith(null)
|
||||
expect(planner.setShowPlaceForm).toHaveBeenCalledWith(true)
|
||||
})
|
||||
|
||||
it('FE-MOB-ACCSH-033: without the right to add places the hint stays a hint', () => {
|
||||
setup(makePlanner({ places: [], can: vi.fn(() => false) }))
|
||||
expect(screen.getByText('Add places to your trip first')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Add place/activity' })).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-MOB-ACCSH-018: without categories there are no filter chips', () => {
|
||||
setup(makePlanner({ categories: [] }))
|
||||
expect(screen.queryByRole('button', { name: 'Hotels' })).not.toBeInTheDocument()
|
||||
|
||||
@@ -600,7 +600,7 @@ describe('MRoadtripTab', () => {
|
||||
const scroller = container.querySelector('[class*="overflow-y-auto"]') as HTMLElement
|
||||
// 96px band plus a 44px bar plus its gap. A padding left at the old 102 would
|
||||
// put the head card's first line behind the glass.
|
||||
expect(scroller.className).toContain('pt-[calc(var(--m-safe-top,12px)+150px)]')
|
||||
expect(scroller.className).toContain('pt-[max(calc(var(--m-safe-top,12px)+150px),var(--m-corner-clear,0px))]')
|
||||
})
|
||||
it('FE-MOB-RTTAB-031: no stage, no search bar, and the chain keeps its old top', () => {
|
||||
// Without a stage the corridor falls back to the trip's first routed day, which
|
||||
@@ -610,7 +610,7 @@ describe('MRoadtripTab', () => {
|
||||
|
||||
expect(screen.queryByText('roadtrip.poi.title')).toBeNull()
|
||||
const scroller = container.querySelector('[class*="overflow-y-auto"]') as HTMLElement
|
||||
expect(scroller.className).toContain('pt-[calc(var(--m-safe-top,12px)+102px)]')
|
||||
expect(scroller.className).toContain('pt-[max(calc(var(--m-safe-top,12px)+102px),var(--m-corner-clear,0px))]')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import { buildPlanner, buildShell } from '../../../helpers/mobileTrip'
|
||||
import { resetAllStores, seedStore } from '../../../helpers/store'
|
||||
import { fireEvent, render, screen } from '../../../helpers/render'
|
||||
|
||||
// FE-MOB-TRSH-001 to FE-MOB-TRSH-036
|
||||
// FE-MOB-TRSH-001 to FE-MOB-TRSH-044
|
||||
|
||||
vi.mock('../../../../src/utils/fileDownload', () => ({
|
||||
openFile: vi.fn(() => Promise.resolve()),
|
||||
@@ -504,4 +504,108 @@ describe('MTransportSheet', () => {
|
||||
expect(screen.getByText('10:20')).toBeInTheDocument()
|
||||
expect(screen.getByText('06:45')).toBeInTheDocument()
|
||||
})
|
||||
// #3122: opened from the compact Transports list, the sheet showed the times
|
||||
// but not the day they fall on.
|
||||
describe('calendar dates beside the times (#3122)', () => {
|
||||
const DAYS = [
|
||||
{ id: 3, trip_id: 1, day_number: 1, date: '2026-05-01' },
|
||||
{ id: 4, trip_id: 1, day_number: 2, date: '2026-05-02' },
|
||||
]
|
||||
|
||||
it('FE-MOB-TRSH-037: a flight with a route shows the departure and the arrival date beside their times', () => {
|
||||
render(<MTransportSheet planner={makePlanner({ days: DAYS })} shell={makeShell()} />)
|
||||
const dep = screen.getByText('10:20').parentElement as HTMLElement
|
||||
const arr = screen.getByText('06:45').parentElement as HTMLElement
|
||||
expect(dep).toHaveTextContent('Fri, May 1')
|
||||
expect(arr).toHaveTextContent('Sat, May 2')
|
||||
})
|
||||
|
||||
it('FE-MOB-TRSH-038: a transport holding only times reads its date off the linked day, not "Day 1"', () => {
|
||||
const res = {
|
||||
...FLIGHT, type: 'ferry', title: 'Ferry to Naxos', day_id: 4, end_day_id: null,
|
||||
reservation_time: '08:15', reservation_end_time: '13:40', metadata: null,
|
||||
endpoints: [
|
||||
{ id: 1, reservation_id: 7, role: 'from', sequence: 0, name: 'Piraeus', lat: 37.94, lng: 23.64, local_date: null, local_time: null },
|
||||
{ id: 2, reservation_id: 7, role: 'to', sequence: 1, name: 'Naxos', lat: 37.1, lng: 25.37, local_date: null, local_time: null },
|
||||
],
|
||||
} as unknown as Reservation
|
||||
render(<MTransportSheet planner={makePlanner({ days: DAYS, reservations: [res] })} shell={makeShell()} />)
|
||||
expect(screen.getByText('08:15').parentElement).toHaveTextContent('Sat, May 2')
|
||||
expect(screen.queryByText(/Day 1/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("FE-MOB-TRSH-039: a leg opened from its row shows that leg's own dates", () => {
|
||||
const res = {
|
||||
...FLIGHT, type: 'train', title: 'Night train', endpoints: [], reservation_time: null, reservation_end_time: null,
|
||||
metadata: JSON.stringify({
|
||||
legs: [
|
||||
{ from: 'Vienna', to: 'Munich', dep_day_id: 3, dep_time: '22:10', arr_day_id: 3, arr_time: '23:50' },
|
||||
{ from: 'Munich', to: 'Paris', dep_day_id: 3, dep_time: '23:58', arr_day_id: 4, arr_time: '09:30' },
|
||||
],
|
||||
}),
|
||||
} as unknown as Reservation
|
||||
render(<MTransportSheet planner={makePlanner({ days: DAYS, reservations: [res] })} shell={makeShell({ sheet: { id: 'transport', payload: { reservationId: 7, legIndex: 1 } } })} />)
|
||||
expect(screen.getByText('23:58').parentElement).toHaveTextContent('Fri, May 1')
|
||||
expect(screen.getByText('09:30').parentElement).toHaveTextContent('Sat, May 2')
|
||||
})
|
||||
|
||||
it('FE-MOB-TRSH-040: names a date once, beside the time, and not again in the subline', () => {
|
||||
const res = { ...FLIGHT, endpoints: [], metadata: null } as unknown as Reservation
|
||||
render(<MTransportSheet planner={makePlanner({ days: DAYS, reservations: [res] })} shell={makeShell()} />)
|
||||
expect(screen.getAllByText('Fri, May 1')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-MOB-TRSH-041: a flight with an airline but no route and no time names its date in the subline', () => {
|
||||
const res = { ...FLIGHT, endpoints: [], reservation_time: '2026-05-01', reservation_end_time: null } as unknown as Reservation
|
||||
render(<MTransportSheet planner={makePlanner({ days: DAYS, reservations: [res] })} shell={makeShell()} />)
|
||||
expect(screen.getByText('Lufthansa · LH 716 · Fri, May 1')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-MOB-TRSH-042: a transport with a route but no times yet names the date of its linked day', () => {
|
||||
const res = {
|
||||
...FLIGHT, type: 'ferry', title: 'Ferry to Naxos', day_id: 4, end_day_id: null,
|
||||
reservation_time: null, reservation_end_time: null, metadata: null,
|
||||
endpoints: [
|
||||
{ id: 1, reservation_id: 7, role: 'from', sequence: 0, name: 'Piraeus', lat: 37.94, lng: 23.64, local_date: null, local_time: null },
|
||||
{ id: 2, reservation_id: 7, role: 'to', sequence: 1, name: 'Naxos', lat: 37.1, lng: 25.37, local_date: null, local_time: null },
|
||||
],
|
||||
} as unknown as Reservation
|
||||
render(<MTransportSheet planner={makePlanner({ days: DAYS, reservations: [res] })} shell={makeShell()} />)
|
||||
expect(screen.getByText('Piraeus → Naxos · Sat, May 2')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-MOB-TRSH-043: with the live card in place of the time boxes, the subline names the date', () => {
|
||||
const now = Date.now()
|
||||
const soon: FlightLiveLeg = {
|
||||
reservation_id: 7, leg_index: 0, callsign: 'DLH716', flight_number: 'LH 716', service_date: '2026-05-01',
|
||||
origin: { code: 'FRA', name: 'Frankfurt', lat: 50.03, lng: 8.57, timezone: 'Europe/Berlin' },
|
||||
destination: { code: 'HND', name: 'Tokyo Haneda', lat: 35.55, lng: 139.78, timezone: 'Asia/Tokyo' },
|
||||
phase: 'scheduled', scheduled_departure: new Date(now + 3_600_000).toISOString(), scheduled_arrival: new Date(now + 7_200_000).toISOString(),
|
||||
departed_at: null, landed_at: null, estimated_arrival: null, departure_delay_min: null, arrival_delay_min: null,
|
||||
progress: null, distance_total_km: null, distance_remaining_km: null, position: null, aircraft: null,
|
||||
last_seen_at: null, fetched_at: new Date(now).toISOString(), stale: false, source: 'adsb.lol',
|
||||
}
|
||||
useFlightLiveStore.setState({ trips: { 1: { enabled: true, attribution: null, legs: { [legKey(7, 0)]: soon } } } })
|
||||
render(<MTransportSheet planner={makePlanner({ days: DAYS })} shell={makeShell()} />)
|
||||
expect(screen.queryByText('10:20')).not.toBeInTheDocument()
|
||||
expect(screen.getByText(/Frankfurt \(FRA\) → Tokyo \(HND\) · Fri, May 1/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
// Each box stands on its own in the row, so a same-day trip keeps the date on both
|
||||
// rather than leaving one box a line shorter than the other.
|
||||
it('FE-MOB-TRSH-044: a same-day trip shows its date on both time boxes', () => {
|
||||
const res = {
|
||||
...FLIGHT, type: 'train', title: 'ICE to Munich', metadata: null,
|
||||
reservation_time: '2026-05-01T10:20', reservation_end_time: '2026-05-01T12:05',
|
||||
endpoints: [
|
||||
{ id: 1, reservation_id: 7, role: 'from', sequence: 0, name: 'Frankfurt Hbf', lat: 50.1, lng: 8.66, local_date: '2026-05-01', local_time: '10:20' },
|
||||
{ id: 2, reservation_id: 7, role: 'to', sequence: 1, name: 'München Hbf', lat: 48.14, lng: 11.56, local_date: '2026-05-01', local_time: '12:05' },
|
||||
],
|
||||
} as unknown as Reservation
|
||||
render(<MTransportSheet planner={makePlanner({ days: DAYS, reservations: [res] })} shell={makeShell()} />)
|
||||
expect(screen.getByText('10:20').parentElement).toHaveTextContent('Fri, May 1')
|
||||
expect(screen.getByText('12:05').parentElement).toHaveTextContent('Fri, May 1')
|
||||
expect(screen.getAllByText('Fri, May 1')).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
# TREK on a Postgres database instead of the SQLite file. See the wiki page
|
||||
# Database-Postgres for what this changes, the requirements and the backups.
|
||||
#
|
||||
# Set two passwords in a .env file beside this file (or in the shell) before
|
||||
# the first start:
|
||||
# POSTGRES_ADMIN_PASSWORD=<a long random value> the database's superuser, postgres
|
||||
# POSTGRES_PASSWORD=<another long random value> TREK's own role, trek
|
||||
# TREK connects as the role trek, which owns its database but is not a
|
||||
# superuser: a backup TREK restores is a SQL script run by that role, and a
|
||||
# superuser would let a crafted one run commands in the database container.
|
||||
# The superuser only creates that role, on the database's first start
|
||||
# (configs.trek-db-role below). TREK's password goes into TREK_DB_URL, so keep
|
||||
# it to URL-safe characters or percent-encode it. Without either password the
|
||||
# first start fails instead of creating a database nobody can reach.
|
||||
#
|
||||
# An install that started from an older version of this file runs TREK as the
|
||||
# superuser trek; the wiki page Database-Postgres ("Moving a compose install
|
||||
# off the superuser") shows how to move it to this layout.
|
||||
#
|
||||
# The database runs PostgreSQL 18. TREK supports 14 to 18: to run 14 to 17,
|
||||
# change the image tag and mount the volume at /var/lib/postgresql/data
|
||||
# instead, where those images keep their data (the 18 image refuses that
|
||||
# path). An existing database stays on the major it was created with: when
|
||||
# you update this file, keep your image tag and volume path. Moving to
|
||||
# another major needs pg_upgrade, or a dump and restore (a TREK backup
|
||||
# restored into a new, empty database works across majors), never just a
|
||||
# new image tag.
|
||||
services:
|
||||
db:
|
||||
image: postgres:18
|
||||
container_name: trek-db
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- POSTGRES_DB=${POSTGRES_DB:-trek}
|
||||
- POSTGRES_USER=postgres
|
||||
- POSTGRES_PASSWORD=${POSTGRES_ADMIN_PASSWORD:-}
|
||||
- TREK_DB_PASSWORD=${POSTGRES_PASSWORD:-}
|
||||
configs:
|
||||
- source: trek-db-role
|
||||
target: /docker-entrypoint-initdb.d/10-trek-role.sh
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
# No ports are published: only the trek service on the compose network reaches the database.
|
||||
volumes:
|
||||
# The path the postgres:18 image expects. Images 14 to 17 need
|
||||
# /var/lib/postgresql/data here (see the top of this file).
|
||||
- trek-pgdata:/var/lib/postgresql
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres -d $${POSTGRES_DB}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 10s
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: 10m
|
||||
max-file: "3"
|
||||
|
||||
app:
|
||||
image: mauriceboe/trek:latest
|
||||
container_name: trek
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
read_only: true
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
cap_add:
|
||||
- CHOWN
|
||||
- SETUID
|
||||
- SETGID
|
||||
# dumb-init runs as root and forwards SIGTERM to node, which runs as the
|
||||
# node user; signalling another user's process needs KILL. See docker-compose.yml.
|
||||
- KILL
|
||||
tmpfs:
|
||||
- /tmp:noexec,nosuid,size=128m
|
||||
ports:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
- NODE_ENV=production
|
||||
- PORT=3000
|
||||
- ENCRYPTION_KEY=${ENCRYPTION_KEY:-} # Recommended. Generate with: openssl rand -hex 32.
|
||||
- TZ=${TZ:-UTC}
|
||||
- LOG_LEVEL=${LOG_LEVEL:-info}
|
||||
- ALLOWED_ORIGINS=${ALLOWED_ORIGINS:-}
|
||||
# The database URL, as the role trek. Its host is the service name above;
|
||||
# sslmode=disable is right on the compose network. Use sslmode=verify-full
|
||||
# with sslrootcert= for a database reached over a network you do not control.
|
||||
- TREK_DB_URL=postgres://trek:${POSTGRES_PASSWORD:-}@db:5432/${POSTGRES_DB:-trek}?sslmode=disable
|
||||
# Scale-out is not supported: keep one trek container (see Database-Postgres).
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
- ./uploads:/app/uploads
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: 10m
|
||||
max-file: "3"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -qO- http://localhost:$${PORT:-3000}/api/health || exit 1"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 15s
|
||||
|
||||
# Run once by the postgres image, on the database's first start, as the
|
||||
# superuser: creates the role trek, which owns TREK's database and its public
|
||||
# schema, so it can create TREK's tables and its collation there, and nothing
|
||||
# more. The password reaches psql as a variable, never spliced into the SQL.
|
||||
#
|
||||
# Outside Swarm, compose cannot set a config's file mode, so the file is not
|
||||
# executable and the image sources it into its own shell instead of running
|
||||
# it. All the work runs in a subshell, so set -eu and exit stay inside it,
|
||||
# and a failure there fails the database's first start either way.
|
||||
configs:
|
||||
trek-db-role:
|
||||
content: |
|
||||
#!/bin/sh
|
||||
(
|
||||
set -eu
|
||||
if [ -z "$${TREK_DB_PASSWORD:-}" ]; then
|
||||
echo 'POSTGRES_PASSWORD (the password of the role trek) is not set.' >&2
|
||||
exit 1
|
||||
fi
|
||||
psql -v ON_ERROR_STOP=1 --no-psqlrc --username "$$POSTGRES_USER" --dbname "$$POSTGRES_DB" \
|
||||
--set=password="$$TREK_DB_PASSWORD" --set=database="$$POSTGRES_DB" <<'SQL'
|
||||
CREATE ROLE trek LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD :'password';
|
||||
ALTER DATABASE :"database" OWNER TO trek;
|
||||
ALTER SCHEMA public OWNER TO trek;
|
||||
SQL
|
||||
)
|
||||
|
||||
volumes:
|
||||
trek-pgdata:
|
||||
@@ -48,6 +48,8 @@
|
||||
"entry": [
|
||||
"src/index.ts",
|
||||
"src/bootstrap.ts",
|
||||
// The move of a SQLite install into Postgres, run by hand (npm run db:move-to-postgres, dist/ in the image).
|
||||
"src/move-to-postgres.ts",
|
||||
// Read by the MikroORM CLI and at boot, by path.
|
||||
"src/mikro-orm.config.ts",
|
||||
// Started with child_process.fork() by the plugin supervisor (nest/plugins/paths.ts).
|
||||
|
||||
Generated
+2
-19
@@ -5684,7 +5684,6 @@
|
||||
"version": "7.2.8",
|
||||
"resolved": "https://registry.npmjs.org/@mikro-orm/postgresql/-/postgresql-7.2.8.tgz",
|
||||
"integrity": "sha512-spAGvR8xfXGK0+mwsAsN3Kt5cg2Ge3DgXT3rNOeA7IxaBXpl+NMwXu5cSWes4jHlhWKJ4jzXyTo6xH+we9fbNA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@mikro-orm/sql": "7.2.8",
|
||||
@@ -19855,7 +19854,6 @@
|
||||
"version": "8.23.1",
|
||||
"resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz",
|
||||
"integrity": "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pg-connection-string": "^2.14.1",
|
||||
@@ -19883,7 +19881,6 @@
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz",
|
||||
"integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
},
|
||||
@@ -19891,14 +19888,12 @@
|
||||
"version": "2.14.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz",
|
||||
"integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pg-cursor": {
|
||||
"version": "2.22.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-cursor/-/pg-cursor-2.22.1.tgz",
|
||||
"integrity": "sha512-X10ldv3wwBONQkOSwgWEbaEITMGLd92V2Zd+xsFPhDt3nhhU3hpAT08SERBChnIFmomczLax6lKXLJrHPPXfxA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"pg": "^8"
|
||||
@@ -19908,7 +19903,6 @@
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
|
||||
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=4.0.0"
|
||||
@@ -19918,7 +19912,6 @@
|
||||
"version": "3.14.0",
|
||||
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
|
||||
"integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"pg": ">=8.0"
|
||||
@@ -19928,14 +19921,12 @@
|
||||
"version": "1.16.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz",
|
||||
"integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pg-types": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
|
||||
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pg-int8": "1.0.1",
|
||||
@@ -19952,7 +19943,6 @@
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
|
||||
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
@@ -19962,7 +19952,6 @@
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
|
||||
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
@@ -19972,7 +19961,6 @@
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
|
||||
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"xtend": "^4.0.0"
|
||||
@@ -19985,7 +19973,6 @@
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
|
||||
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"split2": "^4.1.0"
|
||||
@@ -20355,7 +20342,6 @@
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-3.0.4.tgz",
|
||||
"integrity": "sha512-nAUSGfSDGOaOAEGwqsRY27GPOea7CNipJPOA7lPbdEpx5Kg3qzdP0AaWC5MlhTWV9s4hFX39nomVZ+C4tnGOJQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
@@ -20365,7 +20351,6 @@
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
|
||||
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
@@ -20375,7 +20360,6 @@
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-2.1.0.tgz",
|
||||
"integrity": "sha512-K7Juri8gtgXVcDfZttFKVmhglp7epKb1K4pgrkLxehjqkrgPhfG6OO8LHLkfaqkbpjNRnra018XwAr1yQFWGcA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
@@ -20385,7 +20369,6 @@
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-4.1.0.tgz",
|
||||
"integrity": "sha512-nJLACcOHi2iyRuMJeW6CuIA0Dc0i1YEpRr26XDyHAfxPjYUJOFxwZjmOc5oFFctTTh/OlRAMlnlXEJvr170fJg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
@@ -25724,7 +25707,6 @@
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
||||
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.4"
|
||||
@@ -25933,6 +25915,7 @@
|
||||
"@mikro-orm/core": "^7.2.7",
|
||||
"@mikro-orm/migrations": "^7.2.7",
|
||||
"@mikro-orm/nestjs": "^7.1.0",
|
||||
"@mikro-orm/postgresql": "^7.2.7",
|
||||
"@mikro-orm/seeder": "^7.2.7",
|
||||
"@mikro-orm/sql": "^7.2.1",
|
||||
"@mikro-orm/sqlite": "^7.2.7",
|
||||
@@ -25969,6 +25952,7 @@
|
||||
"nodemailer": "^10.5.0",
|
||||
"otplib": "^12.0.1",
|
||||
"pdf-parse": "^2.4.5",
|
||||
"pg-cursor": "^2.22.1",
|
||||
"qrcode": "^1.5.4",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.2",
|
||||
@@ -25987,7 +25971,6 @@
|
||||
"@aws-lite/s3-types": "^0.2.8",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@mikro-orm/entity-generator": "^7.2.7",
|
||||
"@mikro-orm/postgresql": "^7.2.7",
|
||||
"@nestjs/testing": "^11.2.5",
|
||||
"@swc/core": "^1.16.22",
|
||||
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
|
||||
|
||||
@@ -32,6 +32,7 @@ Because the package ships standalone it cannot import server code, so several fi
|
||||
|---|---|---|
|
||||
| `src/generated/host-facts.ts` (permissions, RPC methods, hooks, event catalog, `KNOWN_ADDONS`, the output contract `PLUGIN_ENTITY_FIELDS` / `PLUGIN_ENTITY_NESTED` / `PLUGIN_METHOD_RESULT`) | `server/src/nest/plugins/protocol/envelope.ts`, `protocol/output-contract.ts` and `server/src/addons.ts` via `server/scripts/gen-plugin-facts.ts` (**machine-written, never hand-edit**) | server `check:plugin-facts` CI gate; the entity interfaces in `src/index.ts` are type-checked against `PLUGIN_ENTITY_FIELDS` |
|
||||
| `src/egress-policy.ts` (pure helpers, kept **byte-identical**) | `server/src/nest/plugins/runtime/egress-policy.ts` | `test/permissions-parity.test.ts` |
|
||||
| `src/plugin-data-contract.ts` (the `ctx.db` contract `dev` and the mock host apply: the caps, the refusal texts, the NUL refusal and the transaction-control refusal, the whole file **byte-identical**) | `server/src/db/engine/plugin-data-contract.ts` | `test/permissions-parity.test.ts` |
|
||||
| `src/manifest.ts` (validation rules incl. the `trek` version range; its patterns, sets, caps and `PLUGIN_API_VERSION` come from `generated/host-facts.ts`, written from `server/src/nest/plugins/protocol/manifest-rules.ts`) | `server/src/nest/plugins/install/manifest.ts` | the verdicts: `test/fixtures/manifest-corpus.ts`, run here by `test/manifest-corpus.test.ts` and through both validators by `server/tests/unit/plugins/manifest-parity.test.ts` (the SDK may only be stricter, case by case) |
|
||||
| `src/index.ts` (the plugin API types) | `server/src/nest/plugins/runtime/plugin-sdk.ts` (the child's copy) | `test/host-types.test-d.ts` (vitest typecheck mode, on inside the monorepo): plain shapes equal, ctx-carrying shapes and every ctx namespace with the same members; `test/host-types-names.test.ts` makes it list every shared name |
|
||||
| `src/cli/checks/*` (registry gates) | TREK-Plugins registry repo (`scripts/validate-entry.mjs`, `check-readme.mjs`) | `test/checks-parity.test.ts` (runs the registry's real script; `TREK_PLUGINS_REPO` points at a checkout) |
|
||||
|
||||
+142
-1
@@ -169,6 +169,147 @@ Every ctx method falls into one of three kinds, listed per method in the exporte
|
||||
answer, an access token) or data you own (`ctx.db`, `ctx.meta`, another plugin's
|
||||
answer), returned as it is.
|
||||
|
||||
### Your own database on Postgres
|
||||
|
||||
`ctx.db` is a SQLite file of your own on a default TREK. When the instance runs on
|
||||
PostgreSQL (`TREK_DB_URL`), it is a schema of your own in TREK's database instead,
|
||||
named `trek_plugin_<your id>` with each dash an underscore, and no SQLite file is
|
||||
written. TREK hands your SQL to the engine as you wrote it and translates nothing, so
|
||||
ask which one you are on and write that dialect:
|
||||
|
||||
```js
|
||||
const pg = (await ctx.db.engine()) === 'postgres'
|
||||
await ctx.db.migrate('001', pg
|
||||
? 'CREATE TABLE notes (id bigserial PRIMARY KEY, body text NOT NULL)'
|
||||
: 'CREATE TABLE notes (id INTEGER PRIMARY KEY AUTOINCREMENT, body TEXT NOT NULL)')
|
||||
await ctx.db.exec(pg ? 'INSERT INTO notes (body) VALUES ($1)' : 'INSERT INTO notes (body) VALUES (?)', body)
|
||||
```
|
||||
|
||||
What changes on Postgres:
|
||||
|
||||
- **Placeholders** are `$1`, `$2`, ..., not `?`. A `?` with bound args is refused with a
|
||||
message that says so.
|
||||
- **Types and functions** are Postgres's: `bigserial`/`GENERATED ... AS IDENTITY` instead
|
||||
of `AUTOINCREMENT`, `now()` instead of `datetime('now')`, `ON CONFLICT` works on both.
|
||||
A `bigint` comes back as a number, and one past 2^53 is refused. A boolean comes back as
|
||||
`true`/`false`, not `1`/`0`.
|
||||
- **Not on a privileged role.** While TREK connects to Postgres as a superuser, a member of
|
||||
one, or another role that could reach the database server (the same roles TREK refuses
|
||||
restores for), every `ctx.db` call fails with an error that starts `Plugin databases
|
||||
(db:own) are refused on Postgres`, and TREK's boot log says so. Your SQL would run as
|
||||
that role. The admin fixes it by connecting TREK as a role that owns its database and is
|
||||
not a superuser; your plugin needs no change.
|
||||
- **Your SQL stays in your schema.** Only your schema is on the `search_path`, and a
|
||||
statement is refused before it runs when it names another schema (`public.users`,
|
||||
another plugin's), anything starting with `pg_` or `information_schema`, or a function
|
||||
that runs SQL from a string, reads settings or reaches an object by a name in a string
|
||||
(`query_to_xml`, `ts_stat`, `set_config`, `current_setting`, `nextval`, `setval`,
|
||||
`has_table_privilege` and the other `has_*_privilege` functions, `currtid2`, `to_reg*`,
|
||||
`lo_*`, `dblink`). The types that look an object up by name are refused in every
|
||||
spelling: `regclass`, `regtype`, `regproc`, `regprocedure`, `regoper`, `regoperator`,
|
||||
`regconfig`, `regdictionary`, `regnamespace`, `regrole`, `regcollation` and their arrays
|
||||
(`'x'::regtype`, `CAST('x' AS regtype)`, `regtype 'x'`). An alias that shares a schema's
|
||||
name is refused too, so pick another.
|
||||
- **Postgres's own functions: an allowlist.** You may call the functions that work only on
|
||||
their arguments: strings and bytes (`lower`, `substring`, `regexp_replace`, `format`,
|
||||
`md5`, `sha256`, ...), numbers (`round`, `abs`, `random`, ...), dates and times (`now`,
|
||||
`date_trunc`, `extract`, `to_char`, `make_date`, ...), the conversions (`numeric(10, 2)`,
|
||||
`varchar(20)`, `int8`, ...), JSON and JSONB (`jsonb_build_object`, `jsonb_set`,
|
||||
`jsonb_path_query`, ...), arrays (`unnest`, `array_agg`, `generate_series`, ...),
|
||||
aggregates and window functions (`count`, `sum`, `string_agg`, `row_number`, `lag`, ...),
|
||||
UUIDs (`gen_random_uuid`), ranges, geometry, network addresses, and full text search over
|
||||
vectors you build yourself (`array_to_tsvector`, `'a & b'::tsquery`, `ts_rank`, `@@`). The
|
||||
text search functions that take a configuration (`to_tsvector`, `to_tsquery`,
|
||||
`plainto_tsquery`, `websearch_to_tsquery`, `ts_headline`, ...) are refused: Postgres looks
|
||||
the configuration up by its name, which would tell you what else the database holds. Any
|
||||
other function of Postgres's catalog is refused
|
||||
however you spell the call (`f(...)`, `"f"(...)`, the column notation `(x).f`, `t.f`,
|
||||
`$1.f`): the ones that read the catalogs or the server rather than their arguments
|
||||
(`obj_description`, `col_description`, `format_type`, `version`, `current_database`,
|
||||
`inet_server_addr`, `txid_current`, ...), and so is every new function a later Postgres adds until TREK has
|
||||
decided about it. The keywords `current_user`, `session_user`, `current_role`, `user`,
|
||||
`system_user`, `current_catalog` and `current_schema` are refused too. `coalesce`,
|
||||
`nullif`, `greatest`, `least`, `CASE` and `CAST` are syntax and always work. The complete
|
||||
list is TREK's
|
||||
[`plugin-functions.txt`](https://github.com/liketrek/TREK/blob/main/server/assets/postgres/plugin-functions.txt).
|
||||
A table or type of yours may still share a refused function's name where it cannot be a
|
||||
call (`INSERT INTO version (...)`, `CREATE TABLE version (...)`, `REFERENCES version (id)`);
|
||||
as the table of `CREATE INDEX ... ON` it cannot, so name it differently. Postgres reads
|
||||
`t.f` as the call `f(t)` when `t` has no column `f`, so a column named like a refused
|
||||
function cannot follow a table's name and a dot either (`name`, `version`, `money`, `oid`
|
||||
and `xml` can); write it without the table's name, or name it differently.
|
||||
- **No system columns.** Reading `xmin`, `xmax`, `cmin`, `cmax`, `ctid` or `tableoid` is
|
||||
refused, quoted or not, after a table's name or alone: they show the server's transaction
|
||||
ids or where a row is stored, and SQLite has none of them. For optimistic locking keep a
|
||||
version or `updated_at` column of your own. A value of yours may still carry such a name
|
||||
where you give it, after `AS` or in a `WITH` query's or an alias's column list
|
||||
(`SELECT min(lng) AS xmin, max(lng) AS xmax FROM places`), and you read it from the
|
||||
result; the SQL itself cannot refer to it by that name (`ORDER BY xmin` is refused).
|
||||
- **No transaction ids.** The types `xid` and `xid8` (and their arrays) are refused where the
|
||||
word stands for the type: `'3'::xid`, `CAST(x AS xid)`, `xid '3'`, `xid(x)`, a column
|
||||
declared `xid`, and `x.xid`, which Postgres reads as the cast `xid(x)` when `x` has no
|
||||
column `xid`. `age()` of one is how many transactions the server ran. A column of yours
|
||||
may be called `xid` (`CREATE TABLE payments (id bigserial PRIMARY KEY, xid text)`, `SELECT
|
||||
xid FROM payments WHERE xid = $1`); name it without its table, and rename it where you
|
||||
need `t.xid` or `excluded.xid` in an upsert.
|
||||
- **Collations and access methods every server has.** After `COLLATE` only `"C"`,
|
||||
`"POSIX"`, `"default"` and `ucs_basic` are accepted, and after `USING` (or `SET ACCESS
|
||||
METHOD`) only `btree`, `hash`, `gist`, `gin`, `spgist`, `brin` and, for a table, `heap`:
|
||||
which others exist depends on the server's locales, ICU and extensions. Text sorts by the
|
||||
database's collation; `ORDER BY name COLLATE "C"` sorts by code point, as SQLite does.
|
||||
- **Values print the same on every server.** Each call runs with the time zone UTC and with
|
||||
Postgres's built-in defaults for the date style, the interval style, the money, number and
|
||||
month name formats (`lc_monetary`, `lc_numeric`, `lc_time` are `C`), float, bytea and xml
|
||||
output and the text search configuration (`simple`), whatever the server is set to:
|
||||
`now()::text` ends in `+00`, `date_trunc('day', now())` cuts at UTC midnight, and
|
||||
`12.5::money` prints `$12.50`.
|
||||
- **You change your own objects only.** Right before an `ALTER`, `DROP`, `REFRESH`,
|
||||
`TRUNCATE` or `CREATE INDEX ... ON` runs, Postgres resolves the object it names (and the
|
||||
tables a `CREATE`/`ALTER TABLE` ties to with `REFERENCES`, `INHERITS`, `PARTITION OF`,
|
||||
`ATTACH`/`DETACH PARTITION` or `INHERIT`), and the statement is refused unless each one
|
||||
that exists is in your schema. Postgres searches its catalog before your schema, so
|
||||
`ALTER TYPE int4 ...` or `DROP TYPE text` names the built-in type and is refused; name
|
||||
your own types so they do not clash with built-in ones.
|
||||
- **Statements**: `SELECT`, `INSERT`, `UPDATE`, `DELETE`, `MERGE`, `WITH`, `VALUES`,
|
||||
`TABLE`, `TRUNCATE`, `REFRESH`, and `CREATE`/`ALTER`/`DROP` of a table, index, view,
|
||||
materialized view, sequence or type (a composite, enum or range type, `CREATE TYPE x AS
|
||||
...`). No functions, triggers, procedures, `DO` blocks, base types, temporary tables,
|
||||
`SELECT ... INTO`, `COPY`, `SET`, transaction control (`tx()` makes a batch atomic),
|
||||
`WITH RECURSIVE`, and no `ALTER` of a schema, owner or tablespace. Dollar-quoted strings,
|
||||
`E'...'` and `U&'...'` are refused; write plain single-quoted strings. `CREATE TEMP` and
|
||||
`CREATE TEMPORARY` (also after `OR REPLACE`, `LOCAL` or `GLOBAL`) are refused, and so is
|
||||
`INTO` anywhere but right after the `INSERT` or `MERGE` that is the statement's verb (or
|
||||
the verb of a `WITH` query's body): `SELECT 1 insert INTO t` is refused, because `insert`
|
||||
there is a column alias. A column named `temp` needs no quoting.
|
||||
Numbers are decimal: `0x1F`, `0o17`, `0b1` and `1_000` are refused, because Postgres
|
||||
before 16 reads them differently. Outside strings, quoted names and comments, whitespace is
|
||||
space, tab, newline, carriage return or form feed; any other control character or non-ASCII
|
||||
whitespace (a no-break space, a byte order mark) is refused. A `--` comment ends at a
|
||||
newline or a carriage return.
|
||||
- **One statement at a time.** Each statement goes to Postgres on its own, over the protocol
|
||||
that runs exactly one: `query` and each `tx` entry take one statement, and an `exec`
|
||||
script is split at its semicolons and sent statement by statement.
|
||||
- **No NUL in text, on either engine.** Postgres text cannot hold the character U+0000, so
|
||||
TREK refuses it on SQLite as well, and `trek-plugin dev` and the mock host refuse it the
|
||||
same way. A bound argument holding one (a string, or a string in an array or an object)
|
||||
and a `migrate` id holding one are refused with an error that names it, and so is SQL text
|
||||
with one anywhere, a string literal included; TREK never drops or changes the character,
|
||||
since `'a\0b'` and `'ab'` are different keys. Bind binary data as a `Buffer` (a `BLOB` on
|
||||
SQLite, `bytea` on Postgres), and use another separator for composite keys. TREK does not
|
||||
see a NUL your SQL builds itself: on SQLite `char(0)` or a BLOB cast to text still stores
|
||||
one, while Postgres refuses `chr(0)`, and moving such an install to Postgres refuses the
|
||||
row. Keep binary data in a `BLOB`. Rows an older TREK stored in your SQLite file with a
|
||||
NUL are still read as they are.
|
||||
- **Limits**: the same row cap and quota as on SQLite. The 2 s budget is a
|
||||
`statement_timeout` here, so it also stops a single long statement, and an `exec` with
|
||||
bound args is held to it too; `migrate` stays untimed. The quota counts every relation of
|
||||
your schema (tables, indexes, sequences, materialized views and each table's TOAST
|
||||
storage), and a schema may hold at most 5,000 catalog objects (relations, types, each
|
||||
table brings its row type and that type's array, constraints and enum labels). A write
|
||||
that takes your schema past 256 MB or past 5,000 objects and grows it there is rolled
|
||||
back; a delete or a drop still runs. Rows deleted or rolled back keep their space until
|
||||
Postgres vacuums them.
|
||||
|
||||
## Settings
|
||||
|
||||
Declare settings in `trek-plugin.json`; TREK renders the form, you write no settings UI.
|
||||
@@ -252,7 +393,7 @@ for a legitimate plugin and only bite a runaway or abusive one — build against
|
||||
| `ctx.ai` | 200 calls/day per plugin (UTC midnight rollover); past it throws `"daily AI budget exhausted (resets at UTC midnight)"` |
|
||||
| `ctx.notify` | 100 calls/day per plugin (UTC midnight rollover); past it throws `"daily notification budget exhausted (resets at UTC midnight)"` |
|
||||
| RPC (every `ctx.*` call) | burst 60, sustained 20/s, 16 in-flight per plugin; a throttled call is refused with `HOST_ERROR: rate limit exceeded — slow down ctx.* calls` |
|
||||
| `ctx.db` (your own sqlite) | 256 MB per plugin; a `query` or `tx` returns at most 100,000 rows (a whole `tx` batch shares one count). A `query`, a whole `tx` batch and an `exec` script without bound args each have 2 s of wall-clock time, checked between the rows a statement reads and between the statements of a batch or script; past either limit the call throws (`query exceeded its 2000 ms time budget`), a `tx` rolls back, and an `exec` script stops before its next statement once the time is up (the statements that ran stay applied, as they always did, and a transaction the script opened itself is rolled back; a script whose last statement has run counts as done, however long it took). Split a longer script over several calls, or batch it with `tx`. `migrate` has no time budget, since a migration stopped part of the way would fail again on every start. `ATTACH`, `DETACH`, `VACUUM`, `PRAGMA`, `WITH RECURSIVE` and `load_extension` are refused. The budget cannot stop a single statement, because SQLite runs it on TREK's main thread in one step: a write runs to its end (an `INSERT ... SELECT` over a cross join of large tables), and a read runs until its first row (an aggregate over one). Keep your statements indexed and bounded |
|
||||
| `ctx.db` (your own database) | 256 MB per plugin; a `query` or `tx` returns at most 100,000 rows (a whole `tx` batch shares one count). A `query`, a whole `tx` batch and an `exec` script without bound args each have 2 s of wall-clock time, checked between the rows a statement reads and between the statements of a batch or script; past either limit the call throws (`query exceeded its 2000 ms time budget`), a `tx` rolls back, and an `exec` script stops before its next statement once the time is up (the statements that ran stay applied, as they always did; a script whose last statement has run counts as done, however long it took). Split a longer script over several calls, or batch it with `tx`. `migrate` has no time budget, since a migration stopped part of the way would fail again on every start. `ATTACH`, `DETACH`, `VACUUM`, `PRAGMA`, `WITH RECURSIVE` and `load_extension` are refused. Transaction control (`BEGIN`, `START`, `COMMIT`, `END`, `ROLLBACK`, `ABORT`, `SAVEPOINT`, `RELEASE`) is refused in every statement of every call, on both engines and in `dev`, with the error `PLUGIN_DATA_ERRORS.txControl`: each call runs in a transaction of its own, and `tx` makes a batch atomic. A named parameter written directly before a parenthesis (`$a(1)`) is refused too (`PLUGIN_DATA_ERRORS.parameterBeforeParenthesis`): the SQLite under `dev` reads it as one token up to the closing parenthesis, and TREK's engines refuse it anyway. The budget cannot stop a single statement, because SQLite runs it on TREK's main thread in one step: a write runs to its end (an `INSERT ... SELECT` over a cross join of large tables), and a read runs until its first row (an aggregate over one). Keep your statements indexed and bounded. On a TREK running on Postgres the same caps hold, and the budget also stops a single statement (see [Your own database on Postgres](#your-own-database-on-postgres)) |
|
||||
| `ctx.meta` | 64 KB per value, 256 chars per key, 100 keys per (plugin, entity) |
|
||||
| Plugin process | 300 MB RSS ceiling; auto-disabled after 5 crashes in 5 minutes |
|
||||
| Event redelivery buffer | 200 events held per plugin, dropped unreplayed after 15 minutes |
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "trek-plugin-sdk",
|
||||
"version": "1.9.1",
|
||||
"version": "1.10.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "trek-plugin-sdk",
|
||||
"version": "1.9.1",
|
||||
"version": "1.10.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.8.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "trek-plugin-sdk",
|
||||
"version": "1.9.1",
|
||||
"version": "1.10.0",
|
||||
"description": "SDK for building TREK plugins: types, definePlugin, a mock host, manifest validation, and the create-trek-plugin / trek-plugin CLIs.",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
|
||||
+60
-48
@@ -23,6 +23,7 @@ import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import { createRequire } from 'node:module';
|
||||
import * as sdk from '../index.js';
|
||||
import { PLUGIN_DATA_CAPS, PLUGIN_DATA_ERRORS, refuseNulSql, refuseNulValues, refuseTransactionControl } from '../plugin-data-contract.js';
|
||||
import { injectTrekUi } from '../ui/kit.js';
|
||||
import { readJsonFile } from './json.js';
|
||||
import {
|
||||
@@ -79,26 +80,21 @@ function printGaps(gaps: GrantGap[]): void {
|
||||
}
|
||||
}
|
||||
|
||||
// The same SQL guards the real host's PluginDataDb applies (plugin-data.service.ts):
|
||||
// forbidden statement types, an sql-length cap, a result-row cap, and — inside tx() —
|
||||
// no transaction control plus a batch-size cap. Without them a statement production
|
||||
// refuses would silently work in dev, and the author would debug a phantom.
|
||||
const MAX_SQL_LENGTH = 100_000;
|
||||
// The same SQL guards the real host's SQLite store applies (SqlitePluginDataStore):
|
||||
// forbidden statement types, an sql-length cap, a result-row cap, NUL in the SQL, an
|
||||
// argument or a migration id, transaction control in any statement of any call, and a
|
||||
// tx batch-size cap. The caps and the refusal texts come from plugin-data-contract.ts, a byte-identical
|
||||
// copy of the host's. Without them a statement production refuses would silently work
|
||||
// in dev, and the author would debug a phantom.
|
||||
const FORBIDDEN_SQL = /\b(ATTACH|DETACH|VACUUM|PRAGMA|RECURSIVE|LOAD_EXTENSION)\b/i;
|
||||
const TX_CONTROL = /^\s*(BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE|END)\b/i;
|
||||
const MAX_TX_OPS = 100;
|
||||
const MAX_ROWS = 100_000;
|
||||
|
||||
function guardSql(sql: string): void {
|
||||
if (typeof sql !== 'string') throw new Error('sql must be a string');
|
||||
if (sql.length > MAX_SQL_LENGTH) throw new Error('sql too long');
|
||||
if (FORBIDDEN_SQL.test(sql)) throw new Error('statement type not allowed for plugin databases');
|
||||
}
|
||||
|
||||
/** Strip LEADING comments/whitespace so a COMMIT hidden behind a comment can't slip
|
||||
* past the start-anchored TX_CONTROL check (mirrors the host's tx() guard). */
|
||||
function stripLeadingComments(sql: string): string {
|
||||
return String(sql ?? '').replace(/^(?:\s|--[^\n]*\n?|\/\*[\s\S]*?\*\/)*/, '');
|
||||
/** The host's checks on one SQL text, in the order the host runs them. */
|
||||
function guardSql(sql: unknown): void {
|
||||
if (typeof sql !== 'string') throw new Error(PLUGIN_DATA_ERRORS.sqlNotString);
|
||||
if (sql.length > PLUGIN_DATA_CAPS.maxSqlLength) throw new Error(PLUGIN_DATA_ERRORS.sqlTooLong);
|
||||
refuseNulSql(sql);
|
||||
if (FORBIDDEN_SQL.test(sql)) throw new Error(PLUGIN_DATA_ERRORS.statementNotAllowed);
|
||||
refuseTransactionControl(sql);
|
||||
}
|
||||
|
||||
// The credential-free inbound-header allowlist TREK's proxy forwards to auth:false
|
||||
@@ -149,11 +145,11 @@ export function createDevDb(dbFile: string): { db: PluginContextDb; note: string
|
||||
return {
|
||||
note: `db:own → in-memory STUB (writes are discarded — upgrade to Node 22.5+; you are on ${process.version})`,
|
||||
close: () => {},
|
||||
db: {
|
||||
async query(sql: string) { guardSql(sql); return []; },
|
||||
async exec(sql: string) { guardSql(sql); return { changes: 0 }; },
|
||||
async migrate(_id: string, sql: string) { guardSql(sql); return { applied: true }; },
|
||||
},
|
||||
db: withTx({
|
||||
async query(sql: string, ...args: unknown[]) { guardSql(sql); refuseNulValues(flatBind(args)); return []; },
|
||||
async exec(sql: string, ...args: unknown[]) { guardSql(sql); refuseNulValues(flatBind(args)); return { changes: 0 }; },
|
||||
async migrate(id: string, sql: string) { guardSql(sql); refuseNulValues([id]); return { applied: true }; },
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -164,26 +160,59 @@ export function createDevDb(dbFile: string): { db: PluginContextDb; note: string
|
||||
return {
|
||||
note: `db:own → real SQLite at ${dbFile}`,
|
||||
close: () => { try { sq.close(); } catch { /* ignore */ } },
|
||||
db: {
|
||||
db: withTx({
|
||||
async query(sql: string, ...args: unknown[]) {
|
||||
guardSql(sql);
|
||||
refuseNulValues(flatBind(args));
|
||||
const rows = sq.prepare(sql).all(...flatBind(args)) as unknown[];
|
||||
if (rows.length > MAX_ROWS) throw new Error(`query returned more than ${MAX_ROWS} rows`);
|
||||
if (rows.length > PLUGIN_DATA_CAPS.maxRows) throw new Error(PLUGIN_DATA_ERRORS.queryTooManyRows(PLUGIN_DATA_CAPS.maxRows));
|
||||
return rows;
|
||||
},
|
||||
async exec(sql: string, ...args: unknown[]) {
|
||||
guardSql(sql);
|
||||
refuseNulValues(flatBind(args));
|
||||
if (args.length) { const r = sq.prepare(sql).run(...flatBind(args)); return { changes: Number(r.changes ?? 0) }; }
|
||||
sq.exec(sql); return { changes: 0 };
|
||||
},
|
||||
async migrate(id: string, sql: string) { guardSql(sql); if (applied.has(id)) return { applied: false }; sq.exec(sql); applied.add(id); return { applied: true }; },
|
||||
},
|
||||
async migrate(id: string, sql: string) { guardSql(sql); refuseNulValues([id]); if (applied.has(id)) return { applied: false }; sq.exec(sql); applied.add(id); return { applied: true }; },
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
type DevTxOp = { sql: string; args?: unknown[] };
|
||||
type DevTxResult = { results: Array<{ changes?: number; rows?: unknown[] }> };
|
||||
|
||||
const isRead = (sql: string) => /^\s*(SELECT|WITH|VALUES)\b/i.test(sql) || /\bRETURNING\b/i.test(sql);
|
||||
|
||||
/**
|
||||
* Adds a functional (not strictly atomic) tx over `db`, so read-modify-write batches
|
||||
* work in dev; production runs it in one transaction. The whole batch is checked up
|
||||
* front, like the host's SqlitePluginDataStore.tx, so a bad op fails before anything ran
|
||||
* instead of leaving earlier writes behind.
|
||||
*/
|
||||
function withTx(db: Omit<PluginContextDb, 'tx'>): PluginContextDb {
|
||||
return {
|
||||
...db,
|
||||
async tx(ops: DevTxOp[]): Promise<DevTxResult> {
|
||||
if (!Array.isArray(ops)) throw new Error(PLUGIN_DATA_ERRORS.txNotArray);
|
||||
if (ops.length > PLUGIN_DATA_CAPS.maxTxOps) throw new Error(PLUGIN_DATA_ERRORS.txTooManyOps(PLUGIN_DATA_CAPS.maxTxOps));
|
||||
for (const op of ops) {
|
||||
guardSql(op?.sql);
|
||||
refuseNulValues(op.args ?? []);
|
||||
}
|
||||
const results: DevTxResult['results'] = [];
|
||||
for (const op of ops) {
|
||||
if (isRead(op.sql)) results.push({ rows: await db.query(op.sql, ...(op.args ?? [])) });
|
||||
else { const r = await db.exec(op.sql, ...(op.args ?? [])); results.push({ changes: r.changes }); }
|
||||
}
|
||||
return { results };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface SqliteDb { prepare(sql: string): { all(...a: unknown[]): unknown[]; run(...a: unknown[]): { changes?: number | bigint } }; exec(sql: string): void; close(): void; }
|
||||
interface PluginContextDb { query(sql: string, ...a: unknown[]): Promise<unknown[]>; exec(sql: string, ...a: unknown[]): Promise<{ changes: number }>; migrate(id: string, sql: string): Promise<{ applied: boolean }>; }
|
||||
interface PluginContextDb { query(sql: string, ...a: unknown[]): Promise<unknown[]>; exec(sql: string, ...a: unknown[]): Promise<{ changes: number }>; migrate(id: string, sql: string): Promise<{ applied: boolean }>; tx(ops: DevTxOp[]): Promise<DevTxResult>; }
|
||||
|
||||
function createDevContext(id: string, grants: Set<string>, fx: Fixtures, db: PluginContextDb, broadcasts: unknown[]) {
|
||||
const need = (perm: string, method: string) => { if (!grants.has(perm)) throw new PermissionDenied(`PERMISSION_DENIED: ${method} requires ${perm}`); };
|
||||
@@ -198,30 +227,13 @@ function createDevContext(id: string, grants: Set<string>, fx: Fixtures, db: Plu
|
||||
// one-arg calls work on a fresh scaffold — without this, a fixtures file that omits
|
||||
// actingUserId leaves the mock userless and every user-bound capability throws.
|
||||
const mock = sdk.createMockHost({ ...fx, actingUserId: fx.actingUserId ?? 1, grants: [...grants] });
|
||||
const isRead = (sql: string) => /^\s*(SELECT|WITH|VALUES)\b/i.test(sql) || /\bRETURNING\b/i.test(sql);
|
||||
const devDb = {
|
||||
query: (sql: string, ...a: unknown[]) => { need('db:own', 'db.query'); return db.query(sql, ...a); },
|
||||
exec: (sql: string, ...a: unknown[]) => { need('db:own', 'db.exec'); return db.exec(sql, ...a); },
|
||||
migrate: (mid: string, sql: string) => { need('db:own', 'db.migrate'); return db.migrate(mid, sql); },
|
||||
// A functional (not strictly atomic) tx over the real dev db so read-modify-write
|
||||
// batches work in dev; production runs it in one better-sqlite3 transaction.
|
||||
tx: async (ops: Array<{ sql: string; args?: unknown[] }>) => {
|
||||
need('db:own', 'db.tx');
|
||||
// Validate the WHOLE batch up front, like the host's PluginDataDb.tx — a bad
|
||||
// op must fail before anything ran, not leave earlier writes behind.
|
||||
if (!Array.isArray(ops)) throw new Error('tx requires an array of { sql, args }');
|
||||
if (ops.length > MAX_TX_OPS) throw new Error(`tx allows at most ${MAX_TX_OPS} statements`);
|
||||
for (const op of ops) {
|
||||
guardSql(op?.sql as string);
|
||||
if (TX_CONTROL.test(stripLeadingComments(op?.sql as string))) throw new Error('transaction-control statements are not allowed inside tx()');
|
||||
}
|
||||
const results: Array<{ changes?: number; rows?: unknown[] }> = [];
|
||||
for (const op of ops) {
|
||||
if (isRead(op.sql)) results.push({ rows: await db.query(op.sql, ...(op.args ?? [])) as unknown[] });
|
||||
else { const r = await db.exec(op.sql, ...(op.args ?? [])) as { changes?: number }; results.push({ changes: r?.changes ?? 0 }); }
|
||||
}
|
||||
return { results };
|
||||
},
|
||||
// `dev` always runs your plugin on SQLite; test the Postgres dialect against a TREK on Postgres.
|
||||
engine: async () => { need('db:own', 'db.engine'); return 'sqlite' as const; },
|
||||
tx: (ops: DevTxOp[]) => { need('db:own', 'db.tx'); return db.tx(ops); },
|
||||
};
|
||||
const wrap = (base: typeof mock.ctx, actingUserId: number | undefined) => ({
|
||||
...base,
|
||||
|
||||
@@ -100,6 +100,7 @@ export const METHOD_PERMISSION: Readonly<Record<string, string>> = {
|
||||
'db.query': 'db:own',
|
||||
'db.migrate': 'db:own',
|
||||
'db.tx': 'db:own',
|
||||
'db.engine': 'db:own',
|
||||
'trips.getById': 'db:read:trips',
|
||||
'trips.getPlaces': 'db:read:trips',
|
||||
'trips.getReservations': 'db:read:trips',
|
||||
@@ -214,6 +215,7 @@ export const KNOWN_METHODS: string[] = [
|
||||
'db.query',
|
||||
'db.migrate',
|
||||
'db.tx',
|
||||
'db.engine',
|
||||
'trips.getById',
|
||||
'trips.getPlaces',
|
||||
'trips.getReservations',
|
||||
@@ -927,6 +929,7 @@ export const PLUGIN_METHOD_RESULT: Readonly<Record<string, string>> = {
|
||||
'db.query': 'host',
|
||||
'db.migrate': 'host',
|
||||
'db.tx': 'host',
|
||||
'db.engine': 'host',
|
||||
'trips.getById': 'trip',
|
||||
'trips.getPlaces': 'place[]',
|
||||
'trips.getReservations': 'reservation[]',
|
||||
|
||||
@@ -74,8 +74,10 @@ export interface PluginContext {
|
||||
settings: {
|
||||
get(key: string): Promise<unknown>;
|
||||
};
|
||||
/** Your OWN sqlite database (`db:own`): a separate file the plugin never gets a
|
||||
* path or connection to directly. Quota: 256 MB per plugin (writes past it fail);
|
||||
/** Your OWN database (`db:own`): a SQLite file of its own, or, when TREK runs on
|
||||
* Postgres, a schema of its own in TREK's database, which your SQL is confined to
|
||||
* (`engine()` says which, and README § Your own database on Postgres has the rules).
|
||||
* The plugin never gets a path or connection to it directly. Quota: 256 MB per plugin (writes past it fail);
|
||||
* result sets are capped at 100,000 rows, and a `query`, a `tx` or an `exec` script
|
||||
* without args gets 2 s of wall-clock time, checked between the rows it reads and
|
||||
* the statements it runs (past it, it throws, a `tx` rolls back and a script stops
|
||||
@@ -87,6 +89,9 @@ export interface PluginContext {
|
||||
query<T = unknown>(sql: string, ...args: unknown[]): Promise<T[]>;
|
||||
exec(sql: string, ...args: unknown[]): Promise<{ changes: number }>;
|
||||
migrate(id: string, sql: string): Promise<{ applied: boolean }>;
|
||||
/** The engine your SQL runs on: 'sqlite' (the default), or 'postgres' when TREK runs on
|
||||
* Postgres. Your SQL is passed through as written, so write it in that engine's dialect. */
|
||||
engine(): Promise<'sqlite' | 'postgres'>;
|
||||
/** Run several statements atomically on your OWN db — all commit or all roll
|
||||
* back. Each op is one statement; reads see the batch's own earlier writes.
|
||||
* A read returns `{ rows }`, a write `{ changes }`. Max 100 statements. */
|
||||
|
||||
+49
-29
@@ -2,6 +2,14 @@ import { PLUGIN_SESSION_MAX_KEYS, PLUGIN_SESSION_MAX_KEY_LENGTH, PLUGIN_SESSION_
|
||||
import type { PluginContext, PluginDefinition, PluginRequest, PluginResponse, Trip, Place, Day, Reservation, PackingItem, TripFile, BudgetItem, User, NotificationMessage, PluginActionResult, PluginSessionStorage } from './index.js';
|
||||
import { CHANNEL_EVENTS } from './manifest.js';
|
||||
import { PermissionDenied, HOOK_PERMISSION, USER_DATA_PERMISSION, EVENTS_PERMISSION, JOBS_PERMISSION } from './permissions.js';
|
||||
import {
|
||||
PLUGIN_DATA_CAPS,
|
||||
PLUGIN_DATA_ERRORS,
|
||||
refuseNulSql,
|
||||
refuseNulValues,
|
||||
refuseTransactionControl,
|
||||
type PluginSqlDialect,
|
||||
} from './plugin-data-contract.js';
|
||||
|
||||
/**
|
||||
* A mock PluginContext for unit-testing a plugin without a running TREK
|
||||
@@ -48,6 +56,8 @@ export interface MockHostOptions {
|
||||
users?: Record<number, unknown>;
|
||||
/** Optional canned db.query results, keyed by the exact sql string. */
|
||||
queryResults?: Record<string, unknown[]>;
|
||||
/** What `db.engine()` answers; 'sqlite' when unset. Set 'postgres' to test a plugin's Postgres SQL path. */
|
||||
dbEngine?: 'sqlite' | 'postgres';
|
||||
/** The host-bound acting user for costs.* (a job/onLoad has none → refused). */
|
||||
actingUserId?: number;
|
||||
/** Trip bound to the mock plugin UI's `session` helper. Required for scope: 'trip'. */
|
||||
@@ -192,25 +202,24 @@ export interface MockHost {
|
||||
}
|
||||
|
||||
|
||||
// --- Statement guards copied from the host's PluginDataDb (plugin-data.service.ts),
|
||||
// so SQL production refuses fails in a unit test too instead of silently passing. ---
|
||||
const MAX_SQL_LENGTH = 100_000;
|
||||
// --- Statement guards copied from the host's SQLite store (SqlitePluginDataStore),
|
||||
// so SQL production refuses fails in a unit test too instead of silently passing.
|
||||
// The caps, the refusal texts and the NUL refusal come from plugin-data-contract.ts,
|
||||
// a byte-identical copy of the host's. ---
|
||||
const FORBIDDEN_SQL = /\b(ATTACH|DETACH|VACUUM|PRAGMA|RECURSIVE|LOAD_EXTENSION)\b/i;
|
||||
// Transaction-control keywords, matched only at statement start (CASE…END and
|
||||
// identifiers are unaffected). A raw COMMIT inside tx() would break atomicity.
|
||||
const TX_CONTROL = /^\s*(BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE|END)\b/i;
|
||||
const MAX_TX_OPS = 100;
|
||||
|
||||
function guardSql(sql: string): void {
|
||||
if (typeof sql !== 'string') throw new Error('sql must be a string');
|
||||
if (sql.length > MAX_SQL_LENGTH) throw new Error('sql too long');
|
||||
if (FORBIDDEN_SQL.test(sql)) throw new Error('statement type not allowed for plugin databases');
|
||||
}
|
||||
|
||||
/** Strip LEADING comments/whitespace so a COMMIT hidden behind a line or block
|
||||
* comment can't slip past the start-anchored TX_CONTROL check. */
|
||||
function stripLeadingComments(sql: string): string {
|
||||
return String(sql ?? '').replace(/^(?:\s|--[^\n]*\n?|\/\*[\s\S]*?\*\/)*/, '');
|
||||
/**
|
||||
* The host's checks on one SQL text, in the order the host runs them. The
|
||||
* transaction-control scan reads `sql` in the dialect of the engine the mock
|
||||
* host emulates, so Postgres spellings (`$1::numeric(10, 2)`, `$$...$$`) pass
|
||||
* where TREK on Postgres runs them.
|
||||
*/
|
||||
function guardSql(sql: unknown, dialect: PluginSqlDialect): void {
|
||||
if (typeof sql !== 'string') throw new Error(PLUGIN_DATA_ERRORS.sqlNotString);
|
||||
if (sql.length > PLUGIN_DATA_CAPS.maxSqlLength) throw new Error(PLUGIN_DATA_ERRORS.sqlTooLong);
|
||||
refuseNulSql(sql);
|
||||
if (FORBIDDEN_SQL.test(sql)) throw new Error(PLUGIN_DATA_ERRORS.statementNotAllowed);
|
||||
refuseTransactionControl(sql, dialect);
|
||||
}
|
||||
|
||||
// The host's stripEmoji (text-sanitize.ts), copied so notify.send cleans/rejects the
|
||||
@@ -259,6 +268,7 @@ const META_KEY_MAX = 256;
|
||||
const META_KEYS_MAX = 100;
|
||||
|
||||
export function createMockHost(opts: MockHostOptions = {}): MockHost {
|
||||
const dialect: PluginSqlDialect = opts.dbEngine ?? 'sqlite';
|
||||
const grants = new Set(opts.grants ?? []);
|
||||
const calls: MockHost['calls'] = [];
|
||||
const logs: MockHost['logs'] = [];
|
||||
@@ -436,29 +446,39 @@ export function createMockHost(opts: MockHostOptions = {}): MockHost {
|
||||
},
|
||||
},
|
||||
db: {
|
||||
async query(sql) {
|
||||
async query(sql, ...args) {
|
||||
need('db:own', 'db.query');
|
||||
guardSql(sql);
|
||||
return (opts.queryResults?.[sql] ?? []) as never[];
|
||||
guardSql(sql, dialect);
|
||||
refuseNulValues(args);
|
||||
const rows = opts.queryResults?.[sql] ?? [];
|
||||
if (rows.length > PLUGIN_DATA_CAPS.maxRows) throw new Error(PLUGIN_DATA_ERRORS.queryTooManyRows(PLUGIN_DATA_CAPS.maxRows));
|
||||
return rows as never[];
|
||||
},
|
||||
async exec(sql) {
|
||||
async exec(sql, ...args) {
|
||||
need('db:own', 'db.exec');
|
||||
guardSql(sql);
|
||||
guardSql(sql, dialect);
|
||||
refuseNulValues(args);
|
||||
return { changes: 0 };
|
||||
},
|
||||
async migrate(_id, sql) {
|
||||
async migrate(id, sql) {
|
||||
need('db:own', 'db.migrate');
|
||||
guardSql(sql);
|
||||
guardSql(sql, dialect);
|
||||
refuseNulValues([id]);
|
||||
return { applied: true };
|
||||
},
|
||||
async engine() {
|
||||
need('db:own', 'db.engine');
|
||||
return dialect;
|
||||
},
|
||||
async tx(ops) {
|
||||
need('db:own', 'db.tx');
|
||||
// Same batch guards as the host's PluginDataDb: an op cap, the forbidden
|
||||
// statement types, and no transaction control inside the batch.
|
||||
if (ops.length > MAX_TX_OPS) throw new Error(`tx allows at most ${MAX_TX_OPS} statements`);
|
||||
// Same batch guards as the host's SQLite store: an op cap, then each op's
|
||||
// SQL through the guard every call takes (transaction control included).
|
||||
if (!Array.isArray(ops)) throw new Error(PLUGIN_DATA_ERRORS.txNotArray);
|
||||
if (ops.length > PLUGIN_DATA_CAPS.maxTxOps) throw new Error(PLUGIN_DATA_ERRORS.txTooManyOps(PLUGIN_DATA_CAPS.maxTxOps));
|
||||
for (const op of ops) {
|
||||
guardSql(op.sql);
|
||||
if (TX_CONTROL.test(stripLeadingComments(op.sql))) throw new Error('transaction-control statements are not allowed inside tx()');
|
||||
guardSql(op?.sql, dialect);
|
||||
refuseNulValues(op.args ?? []);
|
||||
}
|
||||
// Mirror the host: reads resolve from queryResults, writes report 0 changes.
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
/**
|
||||
* The contract of a plugin's own database (`db:own`) that holds on every
|
||||
* engine: the caps, the words a call that breaks it is refused with, and the
|
||||
* refusals of U+0000 (NUL) and of transaction control, so a plugin answers the
|
||||
* same whichever engine TREK runs on.
|
||||
*
|
||||
* TREK's two stores (`server/src/db/engine/sqlite/plugin-data-store.ts` and
|
||||
* `server/src/db/engine/postgres/plugin-data-store.ts`) throw these texts;
|
||||
* `server/tests/unit/db/engine/plugin-data-contract.test.ts` runs every case
|
||||
* on both and fails on a store that answers one differently.
|
||||
*
|
||||
* The plugin SDK keeps a byte-identical copy (`plugin-sdk/src/plugin-data-contract.ts`)
|
||||
* so `trek-plugin dev` and the mock host refuse what TREK refuses, with the
|
||||
* same words; its `test/permissions-parity.test.ts` compares the two files.
|
||||
* Change both together. No imports: the SDK ships standalone.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The limits every plugin database is held to, whatever the engine. The
|
||||
* plugin-sdk README's "Runtime limits" table documents them.
|
||||
*/
|
||||
export const PLUGIN_DATA_CAPS = {
|
||||
/** The longest SQL text one call may carry. */
|
||||
maxSqlLength: 100_000,
|
||||
/** The most rows a query, or a whole tx batch, returns. */
|
||||
maxRows: 100_000,
|
||||
/** The most statements one tx batch holds. */
|
||||
maxTxOps: 100,
|
||||
/** Wall-clock time for one query, one tx batch or one exec script. */
|
||||
timeBudgetMs: 2_000,
|
||||
/** The most a plugin's data may take on disk. */
|
||||
quotaBytes: 256 * 1024 * 1024,
|
||||
} as const;
|
||||
|
||||
/** The calls a time budget holds. */
|
||||
export type PluginDataBudgetedCall = 'query' | 'exec' | 'tx';
|
||||
|
||||
/** The start of every refusal of a statement a plugin may not run. */
|
||||
const STATEMENT_NOT_ALLOWED = 'statement type not allowed for plugin databases';
|
||||
|
||||
/**
|
||||
* What a plugin is told when a call breaks the contract. Both stores throw
|
||||
* these and nothing else for these cases.
|
||||
*
|
||||
* `noStatement`, `moreThanOneStatement` and `closed` are better-sqlite3's own
|
||||
* messages: the SQLite store passes them on as the driver throws them, and
|
||||
* the Postgres store says the same. `statementNotAllowed` starts every
|
||||
* refusal of a statement the store does not run for a plugin; the Postgres
|
||||
* guard adds the reason after a colon. `txControl` is such a refusal with its
|
||||
* reason, in the same words on both engines ({@link refuseTransactionControl}).
|
||||
* `parameterBeforeParenthesis` is the refusal of a spelling no engine TREK
|
||||
* runs accepts, which the scanner behind `refuseTransactionControl` cannot
|
||||
* read the way every SQLite build does.
|
||||
*/
|
||||
export const PLUGIN_DATA_ERRORS = {
|
||||
sqlNotString: 'sql must be a string',
|
||||
sqlTooLong: 'sql too long',
|
||||
statementNotAllowed: STATEMENT_NOT_ALLOWED,
|
||||
txControl:
|
||||
`${STATEMENT_NOT_ALLOWED}: transaction-control statements are not allowed: ` +
|
||||
'each call runs in its own transaction, and tx() makes a batch atomic',
|
||||
parameterBeforeParenthesis:
|
||||
`${STATEMENT_NOT_ALLOWED}: a parameter name ($name, :name, @name) directly followed by "(" is not allowed: ` +
|
||||
'no engine TREK runs accepts it, and the SQLite of trek-plugin dev would read the parentheses as part of the name',
|
||||
noStatement: 'The supplied SQL string contains no statements',
|
||||
moreThanOneStatement: 'The supplied SQL string contains more than one statement',
|
||||
closed: 'The database connection is not open',
|
||||
txNotArray: 'tx requires an array of { sql, args }',
|
||||
txTooManyOps: (max: number): string => `tx allows at most ${max} statements`,
|
||||
queryTooManyRows: (max: number): string => `query returned more than ${max} rows`,
|
||||
txTooManyRows: (max: number): string => `tx returned more than ${max} rows in total`,
|
||||
overBudget: (call: PluginDataBudgetedCall, ms: number): string => `${call} exceeded its ${ms} ms time budget`,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Why a plugin's SQL holding NUL is refused: Postgres ends a statement's text
|
||||
* at a NUL and its text cannot hold one. On SQLite a NUL in a string literal
|
||||
* would store a value the same plugin could never store on Postgres.
|
||||
*/
|
||||
export const PLUGIN_SQL_NUL_REFUSAL =
|
||||
'the SQL holds the character U+0000 (NUL), which plugin databases refuse on every engine: ' +
|
||||
'Postgres cannot read it in a statement or store it in text. Remove it from the SQL';
|
||||
|
||||
/**
|
||||
* Why a plugin's bound value or migration id holding NUL is refused: TREK
|
||||
* will not change what a plugin asked to store or compare (`'a\0b'` and
|
||||
* `'ab'` are different keys). SQLite could store it, but then the plugin
|
||||
* would answer differently on Postgres and its data could not move there.
|
||||
*/
|
||||
export const PLUGIN_VALUE_NUL_REFUSAL =
|
||||
'a plugin argument holds the character U+0000 (NUL), which plugin databases refuse on every engine: ' +
|
||||
'Postgres text cannot store it, and TREK refuses it instead of changing the value. ' +
|
||||
'Remove it, or bind binary data as a Buffer (a BLOB on SQLite, bytea on Postgres)';
|
||||
|
||||
/** Refuses plugin SQL holding NUL ({@link PLUGIN_SQL_NUL_REFUSAL}). */
|
||||
export function refuseNulSql(sql: string): void {
|
||||
if (sql.includes('\u0000')) throw new Error(PLUGIN_SQL_NUL_REFUSAL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses plugin values holding NUL ({@link PLUGIN_VALUE_NUL_REFUSAL}): a
|
||||
* string, or a string anywhere in an array or a plain object (SQLite binds an
|
||||
* object's fields as named parameters, `pg` sends one as JSON). A Buffer is
|
||||
* binary data and holds any byte.
|
||||
*/
|
||||
export function refuseNulValues(values: readonly unknown[]): void {
|
||||
if (holdsNul(values, new Set())) throw new Error(PLUGIN_VALUE_NUL_REFUSAL);
|
||||
}
|
||||
|
||||
function holdsNul(value: unknown, seen: Set<object>): boolean {
|
||||
if (typeof value === 'string') return value.includes('\u0000');
|
||||
if (typeof value !== 'object' || value === null || seen.has(value)) return false;
|
||||
seen.add(value);
|
||||
if (Array.isArray(value)) return value.some((item) => holdsNul(item, seen));
|
||||
const proto: unknown = Object.getPrototypeOf(value);
|
||||
if (proto !== Object.prototype && proto !== null) return false;
|
||||
return Object.values(value).some((item) => holdsNul(item, seen));
|
||||
}
|
||||
|
||||
/**
|
||||
* The verbs of transaction control, in lower case. TREK runs every call in a
|
||||
* transaction of its own and `tx()` makes a batch atomic, so a plugin never
|
||||
* opens, ends or nests one: a COMMIT in the middle would keep writes the call
|
||||
* then reports as failed. SQLite knows no START or ABORT, but they are refused
|
||||
* there too, so a plugin is told the same on both engines.
|
||||
*/
|
||||
export const PLUGIN_TRANSACTION_CONTROL: ReadonlySet<string> = new Set([
|
||||
'begin',
|
||||
'start',
|
||||
'commit',
|
||||
'end',
|
||||
'rollback',
|
||||
'abort',
|
||||
'savepoint',
|
||||
'release',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Refuses SQL in which any statement starts with transaction control
|
||||
* ({@link PLUGIN_DATA_ERRORS.txControl}), in a query, a tx op, a migration or
|
||||
* any statement of an exec script, before anything runs. The SQLite store and
|
||||
* the SDK harnesses call it; the Postgres guard finds the same verbs with its
|
||||
* own lexer.
|
||||
*
|
||||
* A named parameter directly followed by `(` is refused as well
|
||||
* ({@link PLUGIN_DATA_ERRORS.parameterBeforeParenthesis}). A SQLite built with
|
||||
* Tcl variables, as node:sqlite is under `trek-plugin dev`, reads `$a(...)`
|
||||
* up to the closing parenthesis as one token, quotes and semicolons
|
||||
* included, so `$a(')); COMMIT; --')` would hide a COMMIT from this scan.
|
||||
* better-sqlite3 and Postgres refuse the spelling anyway.
|
||||
*
|
||||
* `dialect` says whose spelling `sql` is. The stores and `trek-plugin dev`
|
||||
* run SQLite and pass nothing. The SDK's mock host emulating Postgres passes
|
||||
* `'postgres'`, so `$1`, dollar quotes (`$$...$$`, `$tag$...$tag$`) and
|
||||
* escape strings (`E'...'`) are read as Postgres reads them, `:`, `@` and `#`
|
||||
* are operators there, and a trigger has no body of statements.
|
||||
*/
|
||||
export function refuseTransactionControl(sql: string, dialect: PluginSqlDialect = 'sqlite'): void {
|
||||
if (statementVerbs(sql, dialect).some((verb) => PLUGIN_TRANSACTION_CONTROL.has(verb))) {
|
||||
throw new Error(PLUGIN_DATA_ERRORS.txControl);
|
||||
}
|
||||
}
|
||||
|
||||
/** Whose spelling a plugin's SQL is in. */
|
||||
export type PluginSqlDialect = 'sqlite' | 'postgres';
|
||||
|
||||
/** A name or keyword as SQLite reads one, unquoted. */
|
||||
const WORD = /[A-Za-z_\u0080-][A-Za-z0-9_$\u0080-]*/y;
|
||||
|
||||
/** A character SQLite reads as part of a name. */
|
||||
const NAME_CHAR = /[A-Za-z0-9_$\u0080-]/;
|
||||
|
||||
/** The characters a named parameter starts with in SQLite. */
|
||||
const PARAMETER_PREFIXES = new Set(['$', ':', '@', '#']);
|
||||
|
||||
/**
|
||||
* How many leading words of a statement are kept: enough for
|
||||
* EXPLAIN QUERY PLAN CREATE TEMP TRIGGER.
|
||||
*/
|
||||
const LEADING_WORDS = 6;
|
||||
|
||||
/**
|
||||
* The first word of every statement in `sql`, in lower case, read the way
|
||||
* SQLite splits a script: quoted text ('...', "...", `...`, [...]) and
|
||||
* comments are skipped, and a semicolon ends a statement, except inside
|
||||
* the body of a CREATE TRIGGER, which only `; END ;` ends (as in SQLite's
|
||||
* sqlite3_complete). The statements of a trigger body are not counted, so
|
||||
* its closing END is not taken for transaction control. A statement that
|
||||
* starts with a quoted name or a parenthesis has no verb here. A named
|
||||
* parameter is read as SQLite reads it ({@link afterParameter}).
|
||||
*/
|
||||
function statementVerbs(sql: string, dialect: PluginSqlDialect): string[] {
|
||||
const verbs: string[] = [];
|
||||
let words: string[] = [];
|
||||
let tokens = 0;
|
||||
let inTrigger = false;
|
||||
// In a trigger body: whether the last tokens were `;`, or `;` and END.
|
||||
let afterSemicolon = false;
|
||||
let afterEnd = false;
|
||||
let i = 0;
|
||||
while (i < sql.length) {
|
||||
const c = sql[i];
|
||||
const next = sql[i + 1];
|
||||
if (/\s/.test(c)) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (c === '-' && next === '-') {
|
||||
i = indexAfter(sql, '\n', i + 2);
|
||||
continue;
|
||||
}
|
||||
if (c === '/' && next === '*') {
|
||||
i = indexAfter(sql, '*/', i + 2);
|
||||
continue;
|
||||
}
|
||||
if (c === ';') {
|
||||
if (!inTrigger || afterEnd) {
|
||||
words = [];
|
||||
tokens = 0;
|
||||
inTrigger = false;
|
||||
}
|
||||
afterSemicolon = inTrigger;
|
||||
afterEnd = false;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
WORD.lastIndex = i;
|
||||
const word = WORD.exec(sql)?.[0];
|
||||
tokens++;
|
||||
if (word === undefined) {
|
||||
i = afterOtherToken(sql, i, dialect);
|
||||
afterSemicolon = false;
|
||||
afterEnd = false;
|
||||
continue;
|
||||
}
|
||||
i += word.length;
|
||||
const lower = word.toLowerCase();
|
||||
if (tokens === 1) verbs.push(lower);
|
||||
if (tokens === words.length + 1 && words.length < LEADING_WORDS) words.push(lower);
|
||||
if (!inTrigger && dialect === 'sqlite') inTrigger = opensTrigger(words);
|
||||
afterEnd = afterSemicolon && lower === 'end';
|
||||
afterSemicolon = false;
|
||||
}
|
||||
return verbs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a statement starting with `words` is
|
||||
* [EXPLAIN [QUERY PLAN]] CREATE [TEMP | TEMPORARY] TRIGGER.
|
||||
*/
|
||||
function opensTrigger(words: readonly string[]): boolean {
|
||||
let at = 0;
|
||||
if (words[0] === 'explain') at = words[1] === 'query' && words[2] === 'plan' ? 3 : 1;
|
||||
if (words[at] !== 'create') return false;
|
||||
at += words[at + 1] === 'temp' || words[at + 1] === 'temporary' ? 2 : 1;
|
||||
return words[at] === 'trigger';
|
||||
}
|
||||
|
||||
/** The index after the token at `start` that is no word: quoted text, a parameter, or one character. */
|
||||
function afterOtherToken(sql: string, start: number, dialect: PluginSqlDialect): number {
|
||||
if (dialect === 'postgres') return afterPostgresToken(sql, start);
|
||||
const c = sql[start];
|
||||
if (c === '[') return indexAfter(sql, ']', start + 1);
|
||||
if (c === "'" || c === '"' || c === '`') return afterQuoted(sql, start);
|
||||
if (PARAMETER_PREFIXES.has(c)) return afterParameter(sql, start);
|
||||
return start + 1;
|
||||
}
|
||||
|
||||
/** A dollar quote's opening tag, `$$` or `$tag$`, as Postgres reads one. */
|
||||
const DOLLAR_TAG = /\$(?:[A-Za-z_\u0080-][A-Za-z0-9_\u0080-]*)?\$/y;
|
||||
|
||||
/**
|
||||
* The index after the token at `start` that is no word, read as Postgres reads
|
||||
* it: quoted text and quoted names, a dollar-quoted string up to its closing
|
||||
* tag, an escape string (`E'...'`, where a backslash escapes the next
|
||||
* character), or one character (`$1` is `$` and a number, `::` two colons).
|
||||
*/
|
||||
function afterPostgresToken(sql: string, start: number): number {
|
||||
const c = sql[start];
|
||||
if (c === '$') {
|
||||
DOLLAR_TAG.lastIndex = start;
|
||||
const tag = DOLLAR_TAG.exec(sql)?.[0];
|
||||
if (tag !== undefined) return indexAfter(sql, tag, start + tag.length);
|
||||
return start + 1;
|
||||
}
|
||||
if (c === "'" && isEscapeStringPrefix(sql, start - 1)) return afterEscapeString(sql, start);
|
||||
if (c === "'" || c === '"') return afterQuoted(sql, start);
|
||||
return start + 1;
|
||||
}
|
||||
|
||||
/** Whether the character at `at` is a lone `E`/`e` that makes the string after it an escape string. */
|
||||
function isEscapeStringPrefix(sql: string, at: number): boolean {
|
||||
return (sql[at] === 'E' || sql[at] === 'e') && (at === 0 || !NAME_CHAR.test(sql[at - 1]));
|
||||
}
|
||||
|
||||
/** The index after the escape string whose quote is at `start`. */
|
||||
function afterEscapeString(sql: string, start: number): number {
|
||||
let i = start + 1;
|
||||
while (i < sql.length) {
|
||||
if (sql[i] === '\\') i += 2;
|
||||
else if (sql[i] !== "'") i++;
|
||||
else if (sql[i + 1] === "'") i += 2;
|
||||
else return i + 1;
|
||||
}
|
||||
return sql.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* The index after the named parameter starting at `start`, read as SQLite's
|
||||
* tokenizer reads one: name characters, with `::` allowed inside. Refuses a
|
||||
* name directly followed by `(` ({@link PLUGIN_DATA_ERRORS.parameterBeforeParenthesis}).
|
||||
*
|
||||
* A prefix without a name is no parameter, and SQLite refuses the statement
|
||||
* holding it. Its colons are skipped together, so the scan does not read a
|
||||
* Postgres cast (`x::numeric(10)`, which the mock host may be handed) as a
|
||||
* parameter.
|
||||
*/
|
||||
function afterParameter(sql: string, start: number): number {
|
||||
let i = start + 1;
|
||||
let named = false;
|
||||
while (i < sql.length) {
|
||||
if (NAME_CHAR.test(sql[i])) {
|
||||
named = true;
|
||||
i++;
|
||||
} else if (sql[i] === ':' && sql[i + 1] === ':') {
|
||||
i += 2;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!named) {
|
||||
while (sql[i] === ':') i++;
|
||||
return i;
|
||||
}
|
||||
if (sql[i] === '(') throw new Error(PLUGIN_DATA_ERRORS.parameterBeforeParenthesis);
|
||||
return i;
|
||||
}
|
||||
|
||||
/** The index after the first `token` from `from`, or the end of `sql`. */
|
||||
function indexAfter(sql: string, token: string, from: number): number {
|
||||
const at = sql.indexOf(token, from);
|
||||
return at < 0 ? sql.length : at + token.length;
|
||||
}
|
||||
|
||||
/** The index after the quoted text starting at `start`; a doubled quote stands for itself. */
|
||||
function afterQuoted(sql: string, start: number): number {
|
||||
const quote = sql[start];
|
||||
let i = start + 1;
|
||||
while (i < sql.length) {
|
||||
if (sql[i] !== quote) i++;
|
||||
else if (sql[i + 1] === quote) i += 2;
|
||||
else return i + 1;
|
||||
}
|
||||
return sql.length;
|
||||
}
|
||||
@@ -63,6 +63,17 @@ describe.skipIf(!inMonorepo)('parity with the host', () => {
|
||||
});
|
||||
});
|
||||
|
||||
const serverDataContract = path.resolve(here, '../../server/src/db/engine/plugin-data-contract.ts');
|
||||
|
||||
describe.skipIf(!fs.existsSync(serverDataContract))('parity with the host plugin database', () => {
|
||||
it("the vendored ctx.db contract is byte-identical to the server's", () => {
|
||||
// dev and the mock host hold ctx.db to the host's caps and refuse a call with the host's
|
||||
// own words, NUL included; a drift would let a plugin pass here and fail in TREK.
|
||||
const ours = fs.readFileSync(path.resolve(here, '../src/plugin-data-contract.ts'), 'utf8');
|
||||
expect(ours.replace(/\r\n/g, '\n')).toBe(fs.readFileSync(serverDataContract, 'utf8').replace(/\r\n/g, '\n'));
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(!fs.existsSync(hostFrame))('parity with the host frame', () => {
|
||||
it('the session storage contract is one contract in all three copies', () => {
|
||||
// Nothing generates these: the limits are written out by hand in the SDK export
|
||||
|
||||
+165
-2
@@ -5,6 +5,7 @@ import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
import { createRequire } from 'node:module';
|
||||
import { definePlugin, PLUGIN_API_VERSION, validateManifest, createMockHost, PermissionDenied } from '../src/index.js';
|
||||
import { PLUGIN_DATA_CAPS, PLUGIN_DATA_ERRORS, PLUGIN_SQL_NUL_REFUSAL, PLUGIN_VALUE_NUL_REFUSAL } from '../src/plugin-data-contract.js';
|
||||
import { isUnboundedRange } from '../src/manifest.js';
|
||||
import { scaffold } from '../src/cli/create.js';
|
||||
import { validatePluginDir } from '../src/cli/validate.js';
|
||||
@@ -506,11 +507,75 @@ describe('createMockHost', () => {
|
||||
it('db guards match the host: forbidden statements, tx control, op cap', async () => {
|
||||
const { ctx } = createMockHost({ grants: ['db:own'] });
|
||||
await expect(ctx.db.query('PRAGMA user_version')).rejects.toThrow(/not allowed/);
|
||||
await expect(ctx.db.tx([{ sql: ' COMMIT' }])).rejects.toThrow(/transaction-control/);
|
||||
await expect(ctx.db.tx([{ sql: '/* x */ROLLBACK' }])).rejects.toThrow(/transaction-control/);
|
||||
await expect(ctx.db.tx([{ sql: ' COMMIT' }])).rejects.toThrow(new Error(PLUGIN_DATA_ERRORS.txControl));
|
||||
await expect(ctx.db.tx([{ sql: '/* x */ROLLBACK' }])).rejects.toThrow(new Error(PLUGIN_DATA_ERRORS.txControl));
|
||||
await expect(ctx.db.tx(Array.from({ length: 101 }, () => ({ sql: 'SELECT 1' })))).rejects.toThrow(/at most 100/);
|
||||
});
|
||||
|
||||
it('db refuses transaction control in every call and statement position, as TREK does on both engines', async () => {
|
||||
const { ctx } = createMockHost({ grants: ['db:own'] });
|
||||
const txControl = new Error(PLUGIN_DATA_ERRORS.txControl);
|
||||
for (const sql of ['BEGIN', 'start transaction', 'End', 'ABORT', 'SAVEPOINT a', 'RELEASE a', '-- c\nCOMMIT']) {
|
||||
await expect(ctx.db.query(sql)).rejects.toThrow(txControl);
|
||||
}
|
||||
await expect(ctx.db.exec('BEGIN; INSERT INTO kv VALUES (1); COMMIT;')).rejects.toThrow(txControl);
|
||||
await expect(ctx.db.exec('INSERT INTO kv VALUES (1); /* x */ commit')).rejects.toThrow(txControl);
|
||||
await expect(ctx.db.migrate('001', 'CREATE TABLE kv (k TEXT); COMMIT;')).rejects.toThrow(txControl);
|
||||
await expect(ctx.db.tx([{ sql: 'SELECT 1' }, { sql: 'ROLLBACK' }])).rejects.toThrow(txControl);
|
||||
// The words where they are no statement's verb run.
|
||||
await expect(ctx.db.exec("SELECT CASE WHEN 1 THEN 'BEGIN; COMMIT' END; -- END")).resolves.toEqual({ changes: 0 });
|
||||
});
|
||||
|
||||
it('db reads SQL in the dialect of the engine it emulates', async () => {
|
||||
const txControl = new Error(PLUGIN_DATA_ERRORS.txControl);
|
||||
const pg = createMockHost({ grants: ['db:own'], dbEngine: 'postgres' }).ctx;
|
||||
// Postgres spellings TREK on Postgres runs: a cast with a precision, dollar quotes, escape strings.
|
||||
await expect(pg.db.query('SELECT $1::numeric(10, 2) AS v', 1)).resolves.toEqual([]);
|
||||
await expect(pg.db.exec("SELECT $$it's; COMMIT$$; SELECT $f$ROLLBACK$f$")).resolves.toEqual({ changes: 0 });
|
||||
await expect(pg.db.exec("SELECT E'it\\'s; COMMIT'")).resolves.toEqual({ changes: 0 });
|
||||
await expect(pg.db.exec('CREATE TRIGGER t AFTER INSERT ON kv FOR EACH ROW EXECUTE FUNCTION f(); END')).rejects.toThrow(txControl);
|
||||
await expect(pg.db.exec("SELECT $$x$$; COMMIT")).rejects.toThrow(txControl);
|
||||
await expect(pg.db.exec("SELECT E'a\\''; ROLLBACK")).rejects.toThrow(txControl);
|
||||
// The SQLite mock keeps SQLite's reading: a named parameter before a parenthesis is refused.
|
||||
const sqlite = createMockHost({ grants: ['db:own'] }).ctx;
|
||||
await expect(sqlite.db.query('SELECT $a(1)')).rejects.toThrow(new Error(PLUGIN_DATA_ERRORS.parameterBeforeParenthesis));
|
||||
});
|
||||
|
||||
it("db refuses NUL in the SQL, an argument or a migration id with the host's errors", async () => {
|
||||
const { ctx } = createMockHost({ grants: ['db:own'] });
|
||||
await expect(ctx.db.query("SELECT 'a\u0000'")).rejects.toThrow(PLUGIN_SQL_NUL_REFUSAL);
|
||||
await expect(ctx.db.exec('INSERT INTO kv VALUES (?)', 'a\u0000b')).rejects.toThrow(PLUGIN_VALUE_NUL_REFUSAL);
|
||||
await expect(ctx.db.query('SELECT 1 WHERE ? = 1', [{ k: '\u0000' }])).rejects.toThrow(PLUGIN_VALUE_NUL_REFUSAL);
|
||||
await expect(ctx.db.tx([{ sql: 'INSERT INTO kv VALUES (?)', args: ['\u0000'] }])).rejects.toThrow(PLUGIN_VALUE_NUL_REFUSAL);
|
||||
await expect(ctx.db.migrate('001\u0000', 'CREATE TABLE t (x)')).rejects.toThrow(PLUGIN_VALUE_NUL_REFUSAL);
|
||||
// Binary data with a zero byte is a Buffer, which holds any byte.
|
||||
await expect(ctx.db.exec('INSERT INTO raw VALUES (?)', Buffer.from([1, 0, 2]))).resolves.toEqual({ changes: 0 });
|
||||
});
|
||||
|
||||
it("db refuses a call that breaks the contract with the host's exact words", async () => {
|
||||
const tooLong = 'x'.repeat(PLUGIN_DATA_CAPS.maxSqlLength + 1);
|
||||
const { ctx } = createMockHost({
|
||||
grants: ['db:own'],
|
||||
queryResults: { 'SELECT n FROM big': Array.from({ length: PLUGIN_DATA_CAPS.maxRows + 1 }, (_, n) => ({ n })) },
|
||||
});
|
||||
await expect(ctx.db.query(42 as never)).rejects.toThrow(new Error(PLUGIN_DATA_ERRORS.sqlNotString));
|
||||
await expect(ctx.db.exec(tooLong)).rejects.toThrow(new Error(PLUGIN_DATA_ERRORS.sqlTooLong));
|
||||
await expect(ctx.db.migrate('m', 'PRAGMA user_version')).rejects.toThrow(new Error(PLUGIN_DATA_ERRORS.statementNotAllowed));
|
||||
await expect(ctx.db.query('SELECT n FROM big')).rejects.toThrow(new Error(PLUGIN_DATA_ERRORS.queryTooManyRows(PLUGIN_DATA_CAPS.maxRows)));
|
||||
await expect(ctx.db.tx('nope' as never)).rejects.toThrow(new Error(PLUGIN_DATA_ERRORS.txNotArray));
|
||||
await expect(ctx.db.tx([null as never])).rejects.toThrow(new Error(PLUGIN_DATA_ERRORS.sqlNotString));
|
||||
const ops = Array.from({ length: PLUGIN_DATA_CAPS.maxTxOps + 1 }, () => ({ sql: 'SELECT 1' }));
|
||||
await expect(ctx.db.tx(ops)).rejects.toThrow(new Error(PLUGIN_DATA_ERRORS.txTooManyOps(PLUGIN_DATA_CAPS.maxTxOps)));
|
||||
// The host checks NUL before the statement type, so SQL breaking both is told about the NUL.
|
||||
await expect(ctx.db.query("PRAGMA x = 'a\u0000'")).rejects.toThrow(new Error(PLUGIN_SQL_NUL_REFUSAL));
|
||||
});
|
||||
|
||||
it('db.engine says SQLite unless the mock is told the host runs Postgres, and needs db:own', async () => {
|
||||
await expect(createMockHost({ grants: ['db:own'] }).ctx.db.engine()).resolves.toBe('sqlite');
|
||||
await expect(createMockHost({ grants: ['db:own'], dbEngine: 'postgres' }).ctx.db.engine()).resolves.toBe('postgres');
|
||||
await expect(createMockHost({ grants: [] }).ctx.db.engine()).rejects.toThrow(/PERMISSION_DENIED/);
|
||||
});
|
||||
|
||||
it('member writes need member_manage + protect the owner; users.getById serves only public fields', async () => {
|
||||
const host = createMockHost({
|
||||
grants: ['db:write:members', 'db:read:users'],
|
||||
@@ -784,6 +849,104 @@ describe('dev db bind shapes', () => {
|
||||
close();
|
||||
}
|
||||
});
|
||||
|
||||
it.runIf(hasNodeSqlite)('refuses transaction control in every call before anything runs, as TREK does on both engines', async () => {
|
||||
const { createDevDb } = await import('../src/cli/dev.js');
|
||||
const { db, close } = createDevDb(path.join(tmp, 'db.sqlite'));
|
||||
const txControl = new Error(PLUGIN_DATA_ERRORS.txControl);
|
||||
try {
|
||||
await db.migrate('001', 'CREATE TABLE kv (k TEXT)');
|
||||
await expect(db.query('/* x */ BEGIN')).rejects.toThrow(txControl);
|
||||
await expect(db.query('START TRANSACTION')).rejects.toThrow(txControl);
|
||||
await expect(db.exec("INSERT INTO kv VALUES ('a'); BEGIN; INSERT INTO kv VALUES ('b'); COMMIT;")).rejects.toThrow(txControl);
|
||||
await expect(db.exec('COMMIT', 'x')).rejects.toThrow(txControl);
|
||||
await expect(db.migrate('002', "INSERT INTO kv VALUES ('c');\n-- done\nEND")).rejects.toThrow(txControl);
|
||||
await expect(db.tx([{ sql: "INSERT INTO kv VALUES ('d')" }, { sql: 'SAVEPOINT s' }])).rejects.toThrow(txControl);
|
||||
expect(await db.query('SELECT count(*) AS n FROM kv')).toEqual([{ n: 0 }]);
|
||||
// A trigger body's closing END and a CASE ... END run.
|
||||
await db.exec("CREATE TRIGGER t AFTER INSERT ON kv BEGIN SELECT CASE WHEN 1 THEN 'x' END; END; INSERT INTO kv VALUES ('e');");
|
||||
expect(await db.query('SELECT k FROM kv')).toEqual([{ k: 'e' }]);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
});
|
||||
|
||||
it.runIf(hasNodeSqlite)('refuses a parameter name followed by "(", which node:sqlite reads past quotes and semicolons', async () => {
|
||||
const { createDevDb } = await import('../src/cli/dev.js');
|
||||
const { db, close } = createDevDb(path.join(tmp, 'db.sqlite'));
|
||||
const refusal = new Error(PLUGIN_DATA_ERRORS.parameterBeforeParenthesis);
|
||||
try {
|
||||
await db.migrate('001', 'CREATE TABLE kv (k TEXT)');
|
||||
// node:sqlite reads $a(')) as one parameter, so the COMMIT after it would run.
|
||||
await expect(db.exec("INSERT INTO kv VALUES ($a(')); COMMIT; --')")).rejects.toThrow(refusal);
|
||||
await expect(db.query("SELECT :a(')")).rejects.toThrow(refusal);
|
||||
await expect(db.tx([{ sql: "SELECT @a::b(';')" }])).rejects.toThrow(refusal);
|
||||
expect(await db.query('SELECT count(*) AS n FROM kv')).toEqual([{ n: 0 }]);
|
||||
// A parameter with a space before the parenthesis, or none at all, is read as before.
|
||||
await db.exec('INSERT INTO kv VALUES ($a)', { a: 'x' });
|
||||
expect(await db.query('SELECT k FROM kv')).toEqual([{ k: 'x' }]);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
});
|
||||
|
||||
it.runIf(hasNodeSqlite)('reads the body of an EXPLAIN CREATE TRIGGER as a trigger body', async () => {
|
||||
const { createDevDb } = await import('../src/cli/dev.js');
|
||||
const { db, close } = createDevDb(path.join(tmp, 'db.sqlite'));
|
||||
try {
|
||||
await db.migrate('001', 'CREATE TABLE kv (k TEXT)');
|
||||
expect((await db.query('EXPLAIN CREATE TRIGGER t AFTER INSERT ON kv BEGIN SELECT 1; END')).length).toBeGreaterThan(0);
|
||||
await db.query('EXPLAIN QUERY PLAN CREATE TEMP TRIGGER t AFTER INSERT ON kv BEGIN SELECT 1; END');
|
||||
await expect(db.exec('EXPLAIN CREATE TRIGGER t AFTER INSERT ON kv BEGIN SELECT 1; END; COMMIT')).rejects.toThrow(
|
||||
new Error(PLUGIN_DATA_ERRORS.txControl),
|
||||
);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
});
|
||||
|
||||
it.runIf(hasNodeSqlite)('refuses NUL in the SQL, an argument or a migration id, as TREK does on every engine', async () => {
|
||||
const { createDevDb } = await import('../src/cli/dev.js');
|
||||
const { db, close } = createDevDb(path.join(tmp, 'db.sqlite'));
|
||||
try {
|
||||
await db.migrate('001', 'CREATE TABLE kv (k TEXT PRIMARY KEY, v BLOB)');
|
||||
await expect(db.exec("INSERT INTO kv VALUES ('a\u0000b', 'x')")).rejects.toThrow(PLUGIN_SQL_NUL_REFUSAL);
|
||||
await expect(db.exec('INSERT INTO kv VALUES (?, ?)', ['a\u0000b', 'x'])).rejects.toThrow(PLUGIN_VALUE_NUL_REFUSAL);
|
||||
await expect(db.exec('INSERT INTO kv VALUES (?, ?)', 'c', ['\u0000'])).rejects.toThrow(PLUGIN_VALUE_NUL_REFUSAL);
|
||||
await expect(db.query('SELECT v FROM kv WHERE k = :k', { k: 'x\u0000' })).rejects.toThrow(PLUGIN_VALUE_NUL_REFUSAL);
|
||||
await expect(db.migrate('002\u0000', 'CREATE TABLE more (x INTEGER)')).rejects.toThrow(PLUGIN_VALUE_NUL_REFUSAL);
|
||||
expect(await db.query('SELECT count(*) AS n FROM kv')).toEqual([{ n: 0 }]);
|
||||
// Binary data with a zero byte goes in as a Buffer.
|
||||
await db.exec('INSERT INTO kv VALUES (?, ?)', 'b', Buffer.from([1, 0, 2]));
|
||||
expect(await db.query('SELECT length(v) AS n FROM kv')).toEqual([{ n: 3 }]);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
});
|
||||
|
||||
it.runIf(hasNodeSqlite)("refuses a call that breaks the contract with the host's exact words", async () => {
|
||||
const { createDevDb } = await import('../src/cli/dev.js');
|
||||
const { db, close } = createDevDb(path.join(tmp, 'db.sqlite'));
|
||||
try {
|
||||
await expect(db.query(42 as never)).rejects.toThrow(new Error(PLUGIN_DATA_ERRORS.sqlNotString));
|
||||
await expect(db.exec('x'.repeat(PLUGIN_DATA_CAPS.maxSqlLength + 1))).rejects.toThrow(new Error(PLUGIN_DATA_ERRORS.sqlTooLong));
|
||||
await expect(db.migrate('m', "ATTACH DATABASE 'x' AS y")).rejects.toThrow(new Error(PLUGIN_DATA_ERRORS.statementNotAllowed));
|
||||
await expect(db.tx('nope' as never)).rejects.toThrow(new Error(PLUGIN_DATA_ERRORS.txNotArray));
|
||||
await expect(db.tx([{ sql: 7 as never }])).rejects.toThrow(new Error(PLUGIN_DATA_ERRORS.sqlNotString));
|
||||
const ops = Array.from({ length: PLUGIN_DATA_CAPS.maxTxOps + 1 }, () => ({ sql: 'SELECT 1' }));
|
||||
await expect(db.tx(ops)).rejects.toThrow(new Error(PLUGIN_DATA_ERRORS.txTooManyOps(PLUGIN_DATA_CAPS.maxTxOps)));
|
||||
// A batch is checked whole before anything runs: the insert ahead of the bad op never lands.
|
||||
await db.migrate('001', 'CREATE TABLE kv (k TEXT)');
|
||||
await expect(db.tx([{ sql: "INSERT INTO kv VALUES ('a')" }, { sql: 'PRAGMA user_version' }])).rejects.toThrow(
|
||||
new Error(PLUGIN_DATA_ERRORS.statementNotAllowed),
|
||||
);
|
||||
await expect(db.tx([{ sql: 'INSERT INTO kv VALUES (?)', args: ['b'] }, { sql: 'SELECT k FROM kv' }])).resolves.toEqual({
|
||||
results: [{ changes: 1 }, { rows: [{ k: 'b' }] }],
|
||||
});
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('reference plugin (examples/koffi)', () => {
|
||||
|
||||
@@ -8,12 +8,23 @@
|
||||
// through this script, and every other job asks the answer whether to run.
|
||||
// The aggregate `ci-ok` job then treats a skipped job as passed.
|
||||
//
|
||||
// It also decides whether the run mirrors the push run instead of testing.
|
||||
// The release pull request (dev into main, from this repository) always
|
||||
// carries the head of dev, and every push to dev already runs this workflow
|
||||
// on exactly that commit, listing its changes against the merge base with
|
||||
// main, so that run covers every area the pull request brings in. Running
|
||||
// it twice for one commit doubled the jobs past the organisation's slots, so
|
||||
// on that pull request every area is off and ci-ok mirrors the push run's
|
||||
// verdict (scripts/ci/mirror-push-run.mjs).
|
||||
// The run's context comes from the environment: CI_EVENT, CI_BASE_REF,
|
||||
// CI_HEAD_REF, CI_HEAD_REPO and CI_REPO.
|
||||
//
|
||||
// Usage:
|
||||
// node scripts/ci/changed-areas.mjs --files <list> one changed path per line
|
||||
// node scripts/ci/changed-areas.mjs --all no usable list, run everything
|
||||
//
|
||||
// Prints `<area>=true|false` per area and appends the same lines to
|
||||
// $GITHUB_OUTPUT when it is set.
|
||||
// Prints `<area>=true|false` per area and `mirror=true|false`, and appends
|
||||
// the same lines to $GITHUB_OUTPUT when it is set.
|
||||
//
|
||||
// It fails closed. A list it cannot read is an error, and anything it cannot
|
||||
// classify with confidence (an empty list, a path git had to quote) turns every
|
||||
@@ -23,9 +34,9 @@
|
||||
import { appendFileSync, readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
// The workflow file and this script decide what runs, so a change to either
|
||||
// runs everything.
|
||||
const ALWAYS = ['.github/workflows/test.yml', 'scripts/ci/'];
|
||||
// The workflow file, the local actions its jobs set up with and this script
|
||||
// decide what runs and how, so a change to any of them runs everything.
|
||||
const ALWAYS = ['.github/workflows/test.yml', '.github/actions/', 'scripts/ci/'];
|
||||
|
||||
// Files the test suites read straight from disk, outside the packages:
|
||||
// config-templates.test.ts pins docker-compose.yml and the Helm chart to the
|
||||
@@ -49,7 +60,7 @@ export const AREAS = {
|
||||
'package-lock.json',
|
||||
'.nvmrc',
|
||||
'sonar-project.properties',
|
||||
// lint:knip in server-lint-checks reads it.
|
||||
// lint:knip in server-lint reads it.
|
||||
'knip.jsonc',
|
||||
'Dockerfile',
|
||||
...READ_BY_TESTS,
|
||||
@@ -108,6 +119,50 @@ export function classify(files) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// The release pull request: base main, head dev, and the head branch in this
|
||||
// repository. A fork's branch named dev is not it: its commits never ran here.
|
||||
export const RELEASE_PR = { base: 'main', head: 'dev' };
|
||||
|
||||
/**
|
||||
* @param {{ event?: string, baseRef?: string, headRef?: string, headRepo?: string, repo?: string }} context
|
||||
* @returns {boolean} true when the run mirrors the push run on dev instead of testing
|
||||
*/
|
||||
export function mirrorsPushRun({ event, baseRef, headRef, headRepo, repo }) {
|
||||
return (
|
||||
event === 'pull_request' &&
|
||||
baseRef === RELEASE_PR.base &&
|
||||
headRef === RELEASE_PR.head &&
|
||||
Boolean(repo) &&
|
||||
headRepo === repo
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the run does: the areas to test, and whether ci-ok mirrors the push
|
||||
* run. In mirror mode every area is off, so every job skips by its area
|
||||
* condition and only changes and ci-ok run.
|
||||
*
|
||||
* @param {string[] | null} files changed paths, or null when there is no usable list
|
||||
* @param {Parameters<typeof mirrorsPushRun>[0]} context
|
||||
* @returns {Record<string, boolean>}
|
||||
*/
|
||||
export function decide(files, context) {
|
||||
if (mirrorsPushRun(context)) {
|
||||
return { ...Object.fromEntries(Object.keys(AREAS).map((area) => [area, false])), mirror: true };
|
||||
}
|
||||
return { ...classify(files), mirror: false };
|
||||
}
|
||||
|
||||
function contextFromEnv(env) {
|
||||
return {
|
||||
event: env.CI_EVENT,
|
||||
baseRef: env.CI_BASE_REF,
|
||||
headRef: env.CI_HEAD_REF,
|
||||
headRepo: env.CI_HEAD_REPO,
|
||||
repo: env.CI_REPO,
|
||||
};
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
if (argv.length === 1 && argv[0] === '--all') return { all: true };
|
||||
if (argv.length === 2 && argv[0] === '--files' && argv[1]) return { all: false, list: argv[1] };
|
||||
@@ -118,7 +173,7 @@ function main() {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
// An unreadable list throws and fails the job instead of running on a guess.
|
||||
const files = args.all ? null : readFileSync(args.list, 'utf8').split('\n');
|
||||
const result = classify(files);
|
||||
const result = decide(files, contextFromEnv(process.env));
|
||||
const lines = Object.entries(result).map(([area, on]) => `${area}=${on}`);
|
||||
console.log(lines.join('\n'));
|
||||
if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `${lines.join('\n')}\n`);
|
||||
|
||||
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os';
|
||||
import { basename, dirname, join } from 'node:path';
|
||||
import { after, describe, it } from 'node:test';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { AREAS, classify } from './changed-areas.mjs';
|
||||
import { AREAS, classify, decide, mirrorsPushRun } from './changed-areas.mjs';
|
||||
|
||||
const script = fileURLToPath(new URL('./changed-areas.mjs', import.meta.url));
|
||||
const workflow = fileURLToPath(new URL('../../.github/workflows/test.yml', import.meta.url));
|
||||
@@ -15,10 +15,21 @@ after(() => rmSync(scratch, { recursive: true, force: true }));
|
||||
const none = Object.fromEntries(Object.keys(AREAS).map((area) => [area, false]));
|
||||
const every = Object.fromEntries(Object.keys(AREAS).map((area) => [area, true]));
|
||||
|
||||
// The run's context, cleared so a variable set around the test run cannot
|
||||
// switch the script into mirror mode.
|
||||
const NO_CONTEXT = { CI_EVENT: '', CI_BASE_REF: '', CI_HEAD_REF: '', CI_HEAD_REPO: '', CI_REPO: '' };
|
||||
const RELEASE_PR_ENV = {
|
||||
CI_EVENT: 'pull_request',
|
||||
CI_BASE_REF: 'main',
|
||||
CI_HEAD_REF: 'dev',
|
||||
CI_HEAD_REPO: 'liketrek/TREK',
|
||||
CI_REPO: 'liketrek/TREK',
|
||||
};
|
||||
|
||||
function run(args, env = {}) {
|
||||
return spawnSync(process.execPath, [script, ...args], {
|
||||
encoding: 'utf8',
|
||||
env: { ...process.env, GITHUB_OUTPUT: '', ...env },
|
||||
env: { ...process.env, GITHUB_OUTPUT: '', ...NO_CONTEXT, ...env },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -44,6 +55,24 @@ describe('classify', () => {
|
||||
assert.deepEqual(classify(['server/src/nest/weather/weather.service.ts']), { code: true, image: true, deploy: false });
|
||||
});
|
||||
|
||||
it('runs the Postgres probe and lane for every file they read', () => {
|
||||
// server-postgres is gated on `code`; a migration, a repository, the
|
||||
// engine, the baseline or the lane's own config must never skip it.
|
||||
for (const file of [
|
||||
'server/src/db/migrations/Migration20200101046440_x.ts',
|
||||
'server/src/db/repositories/Trips.repository.ts',
|
||||
'server/src/db/dialect/sql-functions.ts',
|
||||
'server/src/db/engine/postgres/schema-bootstrap.ts',
|
||||
'server/assets/postgres/baseline.sql',
|
||||
'server/scripts/pg-probe-baseline.json',
|
||||
'server/vitest.pg.config.ts',
|
||||
'server/tests/postgres/lane.ts',
|
||||
'server/tests/postgres/snapshot-suites-baseline.json',
|
||||
]) {
|
||||
assert.equal(classify([file]).code, true, file);
|
||||
}
|
||||
});
|
||||
|
||||
it('runs the tests but not the image for a plugin-sdk change', () => {
|
||||
assert.deepEqual(classify(['plugin-sdk/src/index.ts']), { code: true, image: false, deploy: false });
|
||||
});
|
||||
@@ -77,6 +106,13 @@ describe('classify', () => {
|
||||
assert.deepEqual(classify(['scripts/ci/changed-areas.mjs']), every);
|
||||
});
|
||||
|
||||
it('runs everything when a local action the jobs set up with changes', () => {
|
||||
assert.deepEqual(classify(['.github/actions/setup/action.yml']), every);
|
||||
assert.deepEqual(classify(['.github/actions/other/action.yaml']), every);
|
||||
// Another workflow is not one of them.
|
||||
assert.deepEqual(classify(['.github/workflows/security.yml']), none);
|
||||
});
|
||||
|
||||
it('matches whole file names, not prefixes of them', () => {
|
||||
assert.deepEqual(classify(['package.json.bak', 'Dockerfile.old', 'serverless/x.ts', 'wikis/x.png']), none);
|
||||
});
|
||||
@@ -93,6 +129,55 @@ describe('classify', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('the mirror decision', () => {
|
||||
const releasePr = {
|
||||
event: 'pull_request',
|
||||
baseRef: 'main',
|
||||
headRef: 'dev',
|
||||
headRepo: 'liketrek/TREK',
|
||||
repo: 'liketrek/TREK',
|
||||
};
|
||||
|
||||
it('mirrors the push run on the release pull request from dev into main', () => {
|
||||
assert.equal(mirrorsPushRun(releasePr), true);
|
||||
});
|
||||
|
||||
it('tests every other run itself', () => {
|
||||
for (const [what, context] of [
|
||||
['a push to dev', { ...releasePr, event: 'push', baseRef: '', headRef: '' }],
|
||||
['a push to main', { event: 'push', repo: 'liketrek/TREK' }],
|
||||
['a manual dispatch', { ...releasePr, event: 'workflow_dispatch' }],
|
||||
['a feature PR into dev', { ...releasePr, baseRef: 'dev', headRef: 'feat/x' }],
|
||||
['a hotfix PR into main', { ...releasePr, headRef: 'hotfix/x' }],
|
||||
['a PR from main into dev', { ...releasePr, baseRef: 'dev', headRef: 'main' }],
|
||||
['a fork whose branch is named dev', { ...releasePr, headRepo: 'someone/TREK' }],
|
||||
['a PR without a head repository', { ...releasePr, headRepo: '' }],
|
||||
['a run without a repository', { ...releasePr, headRepo: '', repo: '' }],
|
||||
['no context at all', {}],
|
||||
]) {
|
||||
assert.equal(mirrorsPushRun(context), false, what);
|
||||
}
|
||||
});
|
||||
|
||||
it('turns every area off in mirror mode, whatever changed', () => {
|
||||
for (const files of [null, [], ['server/src/index.ts'], ['.github/workflows/test.yml']]) {
|
||||
assert.deepEqual(decide(files, releasePr), { ...none, mirror: true }, JSON.stringify(files));
|
||||
}
|
||||
});
|
||||
|
||||
it('classifies the files as before outside mirror mode', () => {
|
||||
const feature = { ...releasePr, baseRef: 'dev', headRef: 'feat/x' };
|
||||
assert.deepEqual(decide(['README.md'], feature), { ...none, mirror: false });
|
||||
assert.deepEqual(decide(null, { event: 'push' }), { ...every, mirror: false });
|
||||
assert.deepEqual(decide(['charts/trek/values.yaml'], feature), {
|
||||
code: true,
|
||||
image: false,
|
||||
deploy: true,
|
||||
mirror: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('the command line', () => {
|
||||
it('writes the areas to stdout and to GITHUB_OUTPUT', () => {
|
||||
const list = join(scratch, 'list.txt');
|
||||
@@ -101,14 +186,30 @@ describe('the command line', () => {
|
||||
writeFileSync(output, '');
|
||||
const result = run(['--files', list], { GITHUB_OUTPUT: output });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(result.stdout, 'code=true\nimage=false\ndeploy=true\n');
|
||||
assert.equal(readFileSync(output, 'utf8'), 'code=true\nimage=false\ndeploy=true\n');
|
||||
assert.equal(result.stdout, 'code=true\nimage=false\ndeploy=true\nmirror=false\n');
|
||||
assert.equal(readFileSync(output, 'utf8'), 'code=true\nimage=false\ndeploy=true\nmirror=false\n');
|
||||
});
|
||||
|
||||
it('turns everything on with --all', () => {
|
||||
const result = run(['--all']);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(result.stdout, 'code=true\nimage=true\ndeploy=true\n');
|
||||
assert.equal(result.stdout, 'code=true\nimage=true\ndeploy=true\nmirror=false\n');
|
||||
});
|
||||
|
||||
it('turns every area off and mirror on for the release pull request', () => {
|
||||
const list = join(scratch, 'release-list.txt');
|
||||
writeFileSync(list, 'server/src/index.ts\n');
|
||||
for (const args of [['--files', list], ['--all']]) {
|
||||
const result = run(args, RELEASE_PR_ENV);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(result.stdout, 'code=false\nimage=false\ndeploy=false\nmirror=true\n', JSON.stringify(args));
|
||||
}
|
||||
});
|
||||
|
||||
it('still fails on an unreadable list in mirror mode', () => {
|
||||
const result = run(['--files', join(scratch, 'missing.txt')], RELEASE_PR_ENV);
|
||||
assert.equal(result.status, 1);
|
||||
assert.equal(result.stdout, '');
|
||||
});
|
||||
|
||||
it('fails on a list it cannot read', () => {
|
||||
|
||||
@@ -67,7 +67,7 @@ export function verdict(response, sha) {
|
||||
`${run.status === 'completed' ? run.conclusion : run.status} ${run.html_url ?? `check run ${run.id}`}`;
|
||||
|
||||
if (runs.length === 0) {
|
||||
return { ok: false, lines: [`::error::ci-ok never ran on ${sha}. Run Tests & SonarQube on it and dispatch again.`] };
|
||||
return { ok: false, lines: [`::error::ci-ok never ran on ${sha}. Run CI on it and dispatch again.`] };
|
||||
}
|
||||
|
||||
const lines = runs.map((run) => `ci-ok on ${sha}: ${describe(run)}`);
|
||||
@@ -82,7 +82,7 @@ export function verdict(response, sha) {
|
||||
return diff > 0 || (diff === 0 && b.id > a.id) ? b : a;
|
||||
});
|
||||
if (newest.conclusion !== 'success') {
|
||||
lines.push(`::error::The newest ci-ok on ${sha} is not green: ${describe(newest)}. Re-run that run, or run Tests & SonarQube on it again, then dispatch again.`);
|
||||
lines.push(`::error::The newest ci-ok on ${sha} is not green: ${describe(newest)}. Re-run that run, or run CI on it again, then dispatch again.`);
|
||||
return { ok: false, lines };
|
||||
}
|
||||
for (const run of runs) {
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
"plugin-sdk/CLAUDE.md :: protocol/output-contract.ts",
|
||||
"plugin-sdk/CLAUDE.md :: scripts/validate-entry.mjs",
|
||||
"server/CLAUDE.md :: db/migrations.ts",
|
||||
"server/CLAUDE.md :: host/plugin-data.service.ts",
|
||||
"server/CLAUDE.md :: host/rpc-host.ts",
|
||||
"server/CLAUDE.md :: pg-probe/arg-samples.ts",
|
||||
"server/CLAUDE.md :: pg-probe/recorder.ts",
|
||||
|
||||
@@ -78,7 +78,6 @@
|
||||
"server/src/nest/accommodations/night-seat.ts": 1,
|
||||
"server/src/nest/app-config/index.ts": 6,
|
||||
"server/src/nest/auth/auth.helpers.ts": 1,
|
||||
"server/src/nest/backup/backup-archive.ts": 1,
|
||||
"server/src/nest/backup/backup.impl.ts": 3,
|
||||
"server/src/nest/budget/budget.service.ts": 1,
|
||||
"server/src/nest/day-notes/day-notes.service.ts": 1,
|
||||
@@ -209,7 +208,6 @@
|
||||
"server/src/nest/plugins/protocol/envelope.ts": 2,
|
||||
"server/src/nest/storage/drivers/mirror.driver.ts": 1,
|
||||
"server/src/nest/tours/tours.helpers.ts": 1,
|
||||
"server/src/nest/trips/trips.service.ts": 3,
|
||||
"server/src/nest/unsplash/unsplash.service.ts": 1,
|
||||
"server/src/nest/vacay/vacay.service.ts": 4,
|
||||
"server/src/nest/weather/weather.impl.ts": 1,
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
#!/usr/bin/env node
|
||||
// Mirrors the push run's ci-ok onto the release pull request.
|
||||
//
|
||||
// The release pull request (dev into main) always carries the head of dev, and
|
||||
// every push to dev runs test.yml on exactly that commit. Running the whole
|
||||
// workflow a second time for the pull request doubled the jobs past the
|
||||
// organisation's slots, so on that pull request changes turns every area off
|
||||
// (scripts/ci/changed-areas.mjs) and ci-ok runs this script instead: it waits
|
||||
// for the ci-ok of the push run of test.yml on dev for the pull request's head
|
||||
// commit and passes or fails with it.
|
||||
//
|
||||
// A green push ci-ok means every area the pull request brings in was tested:
|
||||
// a push to dev lists its changes against the merge base with main (the
|
||||
// "List the changed files" step in test.yml), not against the previous push,
|
||||
// so a cancelled or red earlier push cannot hide under a later docs-only one.
|
||||
//
|
||||
// It never passes without a real test of that exact commit. No push run for
|
||||
// it, a push run that ended without a ci-ok verdict, a ci-ok that is not
|
||||
// success, an API that keeps failing, or a wait past the timeout all fail,
|
||||
// each with what to do next.
|
||||
//
|
||||
// Usage (in ci-ok, with GITHUB_TOKEN, GITHUB_REPOSITORY and GITHUB_API_URL set):
|
||||
// HEAD_SHA=<sha> node scripts/ci/mirror-push-run.mjs
|
||||
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
export const WORKFLOW_FILE = 'test.yml';
|
||||
export const BRANCH = 'dev';
|
||||
export const CHECK = 'ci-ok';
|
||||
|
||||
// The push run starts about 20 s before the pull request run, so it is there
|
||||
// on the first look. A short grace covers GitHub creating them the other way
|
||||
// round.
|
||||
export const GRACE_MS = 3 * 60_000;
|
||||
export const INTERVAL_MS = 20_000;
|
||||
// Below ci-ok's timeout-minutes in test.yml (workflow-jobs.test.mjs holds the
|
||||
// margin), so the script always ends with its own message, not a kill.
|
||||
export const TIMEOUT_MS = 17 * 60_000;
|
||||
export const MAX_API_ERRORS = 3;
|
||||
|
||||
const minutes = (ms) => `${Math.round(ms / 60_000)} min`;
|
||||
|
||||
class ApiError extends Error {}
|
||||
|
||||
function api({ fetch, apiUrl, token }) {
|
||||
return async (path) => {
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(`${apiUrl}${path}`, {
|
||||
headers: {
|
||||
Accept: 'application/vnd.github+json',
|
||||
Authorization: `Bearer ${token}`,
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
throw new ApiError(`GET ${path} failed: ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
if (!response.ok) throw new ApiError(`GET ${path} answered ${response.status}`);
|
||||
return response.json();
|
||||
};
|
||||
}
|
||||
|
||||
/** The newest push run of test.yml on dev for the commit, or null. */
|
||||
async function findPushRun(get, repo, sha) {
|
||||
const query = new URLSearchParams({ head_sha: sha, event: 'push', branch: BRANCH, per_page: '100' });
|
||||
const body = await get(`/repos/${repo}/actions/workflows/${WORKFLOW_FILE}/runs?${query}`);
|
||||
if (!Array.isArray(body?.workflow_runs)) throw new ApiError('the runs answer has no workflow_runs array');
|
||||
const runs = body.workflow_runs.filter(
|
||||
(run) => run.head_sha === sha && run.event === 'push' && run.head_branch === BRANCH,
|
||||
);
|
||||
return runs.reduce((newest, run) => (newest === null || run.id > newest.id ? run : newest), null);
|
||||
}
|
||||
|
||||
/** The ci-ok job of the run's latest attempt, or null while it has none. */
|
||||
async function findCheck(get, repo, runId) {
|
||||
const jobs = [];
|
||||
for (let page = 1; ; page += 1) {
|
||||
const body = await get(`/repos/${repo}/actions/runs/${runId}/jobs?filter=latest&per_page=100&page=${page}`);
|
||||
if (!Array.isArray(body?.jobs)) throw new ApiError('the jobs answer has no jobs array');
|
||||
jobs.push(...body.jobs);
|
||||
if (body.jobs.length === 0 || jobs.length >= (body.total_count ?? 0)) break;
|
||||
}
|
||||
const named = jobs.filter((job) => job.name === CHECK);
|
||||
return named.reduce((newest, job) => (newest === null || job.id > newest.id ? job : newest), null);
|
||||
}
|
||||
|
||||
/**
|
||||
* One look at the push run. Returns { done: false, note } to keep waiting, or
|
||||
* { done: true, ok, message } once the verdict is known.
|
||||
*/
|
||||
export function assess({ run, check, sha, elapsed, grace = GRACE_MS }) {
|
||||
if (!run) {
|
||||
if (elapsed < grace) return { done: false, note: `No push run of ${WORKFLOW_FILE} on ${BRANCH} for ${sha} yet.` };
|
||||
return {
|
||||
done: true,
|
||||
ok: false,
|
||||
message: `No push run of ${WORKFLOW_FILE} on ${BRANCH} exists for ${sha}, so nothing tested this commit. Push it to ${BRANCH} (or run CI on ${BRANCH} again), then re-run this job.`,
|
||||
};
|
||||
}
|
||||
const where = run.html_url ?? `run ${run.id}`;
|
||||
if (check?.status === 'completed') {
|
||||
if (check.conclusion === 'success') {
|
||||
return { done: true, ok: true, message: `${CHECK} of the push run passed on ${sha}: ${check.html_url ?? where}` };
|
||||
}
|
||||
return {
|
||||
done: true,
|
||||
ok: false,
|
||||
message: `${CHECK} of the push run is ${check.conclusion} on ${sha}: ${check.html_url ?? where}. Fix it on ${BRANCH}, or re-run that push run, then re-run this job.`,
|
||||
};
|
||||
}
|
||||
if (run.status === 'completed') {
|
||||
return {
|
||||
done: true,
|
||||
ok: false,
|
||||
message: `The push run ${where} ended ${run.conclusion} without a ${CHECK} verdict on ${sha}. Re-run it, then re-run this job.`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
done: false,
|
||||
note: `Waiting for the push run ${where}: run ${run.status}, ${CHECK} ${check ? check.status : 'not started'}.`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for the push run's ci-ok and returns { ok, message }.
|
||||
*
|
||||
* @param {object} options
|
||||
* @param {string} options.sha the pull request's head commit
|
||||
* @param {string} options.repo owner/name
|
||||
* @param {string} options.token a token with actions: read
|
||||
* @param {string} [options.apiUrl]
|
||||
* @param {typeof fetch} options.fetch
|
||||
* @param {{ now(): number, sleep(ms: number): Promise<void> }} options.clock
|
||||
* @param {(line: string) => void} [options.log]
|
||||
*/
|
||||
export async function mirror({
|
||||
sha,
|
||||
repo,
|
||||
token,
|
||||
apiUrl = 'https://api.github.com',
|
||||
fetch,
|
||||
clock,
|
||||
log = () => {},
|
||||
interval = INTERVAL_MS,
|
||||
timeout = TIMEOUT_MS,
|
||||
grace = GRACE_MS,
|
||||
maxApiErrors = MAX_API_ERRORS,
|
||||
}) {
|
||||
const get = api({ fetch, apiUrl, token });
|
||||
const start = clock.now();
|
||||
let errors = 0;
|
||||
let lastNote = '';
|
||||
let lastRun = null;
|
||||
for (;;) {
|
||||
try {
|
||||
const run = await findPushRun(get, repo, sha);
|
||||
const check = run ? await findCheck(get, repo, run.id) : null;
|
||||
errors = 0;
|
||||
lastRun = run;
|
||||
const result = assess({ run, check, sha, elapsed: clock.now() - start, grace });
|
||||
if (result.done) return { ok: result.ok, message: result.message };
|
||||
if (result.note !== lastNote) log(result.note);
|
||||
lastNote = result.note;
|
||||
} catch (err) {
|
||||
if (!(err instanceof ApiError)) throw err;
|
||||
errors += 1;
|
||||
log(`The API failed (${errors} of ${maxApiErrors}): ${err.message}`);
|
||||
if (errors >= maxApiErrors) {
|
||||
return {
|
||||
ok: false,
|
||||
message: `The GitHub API failed ${maxApiErrors} times in a row (${err.message}), so the push run's ${CHECK} is unknown. Re-run this job.`,
|
||||
};
|
||||
}
|
||||
}
|
||||
if (clock.now() - start + interval > timeout) break;
|
||||
await clock.sleep(interval);
|
||||
}
|
||||
const where = lastRun?.html_url ?? `the push run of ${WORKFLOW_FILE} on ${BRANCH}`;
|
||||
return {
|
||||
ok: false,
|
||||
message: `Gave up after ${minutes(timeout)}: ${CHECK} of ${where} has not finished on ${sha}. Once it has, re-run this job; it then reads the verdict at once.`,
|
||||
};
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const sha = process.env.HEAD_SHA ?? '';
|
||||
const repo = process.env.GITHUB_REPOSITORY ?? '';
|
||||
const token = process.env.GITHUB_TOKEN ?? '';
|
||||
if (!/^[0-9a-f]{40}$/.test(sha)) throw new Error(`HEAD_SHA is not a commit: "${sha}"`);
|
||||
if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) throw new Error(`GITHUB_REPOSITORY is not owner/name: "${repo}"`);
|
||||
if (!token) throw new Error('GITHUB_TOKEN is empty');
|
||||
const result = await mirror({
|
||||
sha,
|
||||
repo,
|
||||
token,
|
||||
apiUrl: process.env.GITHUB_API_URL || 'https://api.github.com',
|
||||
fetch: globalThis.fetch,
|
||||
clock: { now: () => Date.now(), sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)) },
|
||||
log: (line) => console.log(line),
|
||||
});
|
||||
if (!result.ok) {
|
||||
console.log(`::error::${result.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(result.message);
|
||||
}
|
||||
|
||||
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
|
||||
main().catch((err) => {
|
||||
console.log(`::error::${err instanceof Error ? err.message : err}`);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, it } from 'node:test';
|
||||
import { assess, GRACE_MS, INTERVAL_MS, mirror, TIMEOUT_MS } from './mirror-push-run.mjs';
|
||||
|
||||
const SHA = 'a'.repeat(40);
|
||||
const REPO = 'liketrek/TREK';
|
||||
const RUN_URL = 'https://github.com/liketrek/TREK/actions/runs/7';
|
||||
|
||||
const pushRun = (fields = {}) => ({
|
||||
id: 7,
|
||||
head_sha: SHA,
|
||||
event: 'push',
|
||||
head_branch: 'dev',
|
||||
status: 'in_progress',
|
||||
conclusion: null,
|
||||
html_url: RUN_URL,
|
||||
...fields,
|
||||
});
|
||||
const ciOk = (status, conclusion = null) => ({ id: 70, name: 'ci-ok', status, conclusion, html_url: `${RUN_URL}/job/70` });
|
||||
const otherJob = { id: 71, name: 'Server tests 1/10', status: 'completed', conclusion: 'success' };
|
||||
|
||||
/**
|
||||
* A fake GitHub API. `looks` holds one answer per look: { runs, jobs } or
|
||||
* { error } (a status code, or 'network'). The last look repeats.
|
||||
*/
|
||||
function fakeApi(looks) {
|
||||
const calls = [];
|
||||
let look = -1;
|
||||
const fetch = async (url, init) => {
|
||||
calls.push({ url, init });
|
||||
const path = url.replace('https://api.github.test', '');
|
||||
if (path.includes('/actions/workflows/')) look += 1;
|
||||
const answer = looks[Math.min(look, looks.length - 1)];
|
||||
if (answer.error === 'network') throw new Error('socket hang up');
|
||||
if (answer.error) return { ok: false, status: answer.error, json: async () => ({}) };
|
||||
if (path.includes('/actions/workflows/')) {
|
||||
return { ok: true, status: 200, json: async () => ({ workflow_runs: answer.runs ?? [] }) };
|
||||
}
|
||||
const jobs = answer.jobs ?? [];
|
||||
return { ok: true, status: 200, json: async () => ({ total_count: jobs.length, jobs }) };
|
||||
};
|
||||
return { fetch, calls };
|
||||
}
|
||||
|
||||
function fakeClock() {
|
||||
let now = 0;
|
||||
return { now: () => now, sleep: async (ms) => void (now += ms), elapsed: () => now };
|
||||
}
|
||||
|
||||
async function mirrorWith(looks, options = {}) {
|
||||
const { fetch, calls } = fakeApi(looks);
|
||||
const clock = fakeClock();
|
||||
const lines = [];
|
||||
const result = await mirror({
|
||||
sha: SHA,
|
||||
repo: REPO,
|
||||
token: 'secret',
|
||||
apiUrl: 'https://api.github.test',
|
||||
fetch,
|
||||
clock,
|
||||
log: (line) => lines.push(line),
|
||||
...options,
|
||||
});
|
||||
return { ...result, calls, lines, elapsed: clock.elapsed() };
|
||||
}
|
||||
|
||||
describe('mirror', () => {
|
||||
it('passes when the push run ci-ok passed', async () => {
|
||||
const result = await mirrorWith([{ runs: [pushRun()], jobs: [otherJob, ciOk('completed', 'success')] }]);
|
||||
assert.equal(result.ok, true, result.message);
|
||||
assert.match(result.message, /passed/);
|
||||
assert.equal(result.elapsed, 0);
|
||||
});
|
||||
|
||||
it('asks for exactly the push runs of test.yml on dev for the commit, with the token', async () => {
|
||||
const { calls } = await mirrorWith([{ runs: [pushRun()], jobs: [ciOk('completed', 'success')] }]);
|
||||
const runs = new URL(calls[0].url);
|
||||
assert.equal(runs.pathname, `/repos/${REPO}/actions/workflows/test.yml/runs`);
|
||||
assert.equal(runs.searchParams.get('head_sha'), SHA);
|
||||
assert.equal(runs.searchParams.get('event'), 'push');
|
||||
assert.equal(runs.searchParams.get('branch'), 'dev');
|
||||
assert.equal(calls[0].init.headers.Authorization, 'Bearer secret');
|
||||
const jobs = new URL(calls[1].url);
|
||||
assert.equal(jobs.pathname, `/repos/${REPO}/actions/runs/7/jobs`);
|
||||
assert.equal(jobs.searchParams.get('filter'), 'latest');
|
||||
});
|
||||
|
||||
it('fails when the push run ci-ok failed', async () => {
|
||||
const result = await mirrorWith([
|
||||
{ runs: [pushRun({ status: 'completed', conclusion: 'failure' })], jobs: [ciOk('completed', 'failure')] },
|
||||
]);
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.message, /ci-ok of the push run is failure/);
|
||||
});
|
||||
|
||||
it('fails when the push run ci-ok was cancelled', async () => {
|
||||
const result = await mirrorWith([
|
||||
{ runs: [pushRun({ status: 'completed', conclusion: 'cancelled' })], jobs: [ciOk('completed', 'cancelled')] },
|
||||
]);
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.message, /is cancelled/);
|
||||
});
|
||||
|
||||
it('fails when the push run ended before ci-ok ran', async () => {
|
||||
const result = await mirrorWith([{ runs: [pushRun({ status: 'completed', conclusion: 'cancelled' })], jobs: [] }]);
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.message, /ended cancelled without a ci-ok verdict/);
|
||||
});
|
||||
|
||||
it('fails closed after the grace when no push run exists', async () => {
|
||||
const result = await mirrorWith([{ runs: [] }]);
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.message, /No push run of test\.yml on dev exists/);
|
||||
assert.match(result.message, /re-run this job/);
|
||||
assert.ok(result.elapsed >= GRACE_MS && result.elapsed < GRACE_MS + 2 * INTERVAL_MS, String(result.elapsed));
|
||||
});
|
||||
|
||||
it('counts no run of another event, branch or commit', async () => {
|
||||
const result = await mirrorWith([
|
||||
{
|
||||
runs: [
|
||||
pushRun({ event: 'workflow_dispatch' }),
|
||||
pushRun({ event: 'pull_request' }),
|
||||
pushRun({ head_branch: 'main' }),
|
||||
pushRun({ head_sha: 'b'.repeat(40) }),
|
||||
],
|
||||
jobs: [ciOk('completed', 'success')],
|
||||
},
|
||||
]);
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.message, /No push run/);
|
||||
});
|
||||
|
||||
it('reads the newest push run when there are several', async () => {
|
||||
const { fetch, calls } = fakeApi([{ runs: [pushRun({ id: 7 }), pushRun({ id: 9 })], jobs: [ciOk('completed', 'success')] }]);
|
||||
const result = await mirror({ sha: SHA, repo: REPO, token: 't', apiUrl: 'https://api.github.test', fetch, clock: fakeClock() });
|
||||
assert.equal(result.ok, true);
|
||||
assert.match(calls[1].url, /\/actions\/runs\/9\/jobs/);
|
||||
});
|
||||
|
||||
it('waits while the push run is still going, then passes', async () => {
|
||||
const result = await mirrorWith([
|
||||
{ runs: [] },
|
||||
{ runs: [pushRun({ status: 'queued' })], jobs: [] },
|
||||
{ runs: [pushRun()], jobs: [ciOk('queued')] },
|
||||
{ runs: [pushRun()], jobs: [ciOk('in_progress')] },
|
||||
{ runs: [pushRun({ status: 'completed', conclusion: 'success' })], jobs: [ciOk('completed', 'success')] },
|
||||
]);
|
||||
assert.equal(result.ok, true, result.message);
|
||||
assert.equal(result.elapsed, 4 * INTERVAL_MS);
|
||||
assert.equal(result.lines.length, 4, result.lines.join('\n'));
|
||||
});
|
||||
|
||||
it('logs a waiting state once, not on every look', async () => {
|
||||
const looks = Array.from({ length: 5 }, () => ({ runs: [pushRun()], jobs: [ciOk('queued')] }));
|
||||
looks.push({ runs: [pushRun()], jobs: [ciOk('completed', 'success')] });
|
||||
const result = await mirrorWith(looks);
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.lines.length, 1);
|
||||
});
|
||||
|
||||
it('gives up with a re-run hint at the timeout, before ci-ok would be killed', async () => {
|
||||
const result = await mirrorWith([{ runs: [pushRun()], jobs: [ciOk('in_progress')] }]);
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.message, /Gave up after 17 min/);
|
||||
assert.match(result.message, /re-run this job/);
|
||||
assert.ok(result.message.includes(RUN_URL));
|
||||
assert.ok(result.elapsed <= TIMEOUT_MS, String(result.elapsed));
|
||||
assert.ok(result.elapsed > TIMEOUT_MS - 2 * INTERVAL_MS, String(result.elapsed));
|
||||
});
|
||||
|
||||
it('rides out a passing API error', async () => {
|
||||
const result = await mirrorWith([
|
||||
{ error: 502 },
|
||||
{ error: 'network' },
|
||||
{ runs: [pushRun()], jobs: [ciOk('completed', 'success')] },
|
||||
]);
|
||||
assert.equal(result.ok, true, result.message);
|
||||
});
|
||||
|
||||
it('fails after the API failed three times in a row', async () => {
|
||||
const result = await mirrorWith([{ error: 403 }]);
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.message, /failed 3 times in a row/);
|
||||
});
|
||||
|
||||
it('reads every page of jobs', async () => {
|
||||
const page1 = Array.from({ length: 100 }, (_, i) => ({ id: i + 1, name: `job ${i}`, status: 'completed', conclusion: 'success' }));
|
||||
let jobCalls = 0;
|
||||
const fetch = async (url) => {
|
||||
if (url.includes('/actions/workflows/')) return { ok: true, json: async () => ({ workflow_runs: [pushRun()] }) };
|
||||
jobCalls += 1;
|
||||
const jobs = new URL(url).searchParams.get('page') === '1' ? page1 : [ciOk('completed', 'success')];
|
||||
return { ok: true, json: async () => ({ total_count: 101, jobs }) };
|
||||
};
|
||||
const result = await mirror({ sha: SHA, repo: REPO, token: 't', fetch, clock: fakeClock() });
|
||||
assert.equal(result.ok, true, result.message);
|
||||
assert.equal(jobCalls, 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('assess', () => {
|
||||
it('waits for a missing run only within the grace', () => {
|
||||
assert.equal(assess({ run: null, check: null, sha: SHA, elapsed: 0 }).done, false);
|
||||
assert.equal(assess({ run: null, check: null, sha: SHA, elapsed: GRACE_MS }).done, true);
|
||||
});
|
||||
|
||||
it('passes only a completed ci-ok whose conclusion is success', () => {
|
||||
for (const conclusion of ['failure', 'cancelled', 'skipped', 'timed_out', 'neutral', 'action_required']) {
|
||||
const result = assess({ run: pushRun(), check: ciOk('completed', conclusion), sha: SHA, elapsed: 0 });
|
||||
assert.deepEqual([result.done, result.ok], [true, false], conclusion);
|
||||
}
|
||||
const green = assess({ run: pushRun(), check: ciOk('completed', 'success'), sha: SHA, elapsed: 0 });
|
||||
assert.deepEqual([green.done, green.ok], [true, true]);
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user