Compare commits

..

21 Commits

Author SHA1 Message Date
Josh Creek 669d0cdeaa Merge pull request #99 from jcreek/perf/pokedex-grid-transport
Perf/pokedex grid transport
2026-09-15 18:39:28 +01:00
Josh Creek 7373bf005d docs(performance): record the pokédex investigation and hosting evaluation
Keeps the measurements, the implementation notes and the hosting comparison next
to the code they justify.
2026-09-15 17:49:04 +01:00
Josh Creek 3ee69f0d04 refactor(api): drop the redundant setSession in export-integrations
requireAuth has already resolved the session on locals.supabase.
2026-09-15 17:49:04 +01:00
Josh Creek 0c1de9a93d fix(a11y): trap focus inside the pokédex modal
Tab moved to the page behind the open dialog and closing it left focus nowhere.
Keep Tab within the dialog, move focus to the close button on open, restore it
to the trigger on close, and give the dialog an accessible name.
2026-09-15 17:49:04 +01:00
Josh Creek 03b74089a0 feat(offline): open entry details from the saved snapshot
Opening an entry while offline needed a request that could not be made. Read it
from the snapshot claimed by the signed-in account instead, re-checking
ownership after the read so a sign-in mid-read cannot surface another account's
data, and let controls marked data-offline-action stay usable in read-only mode.
2026-09-15 17:48:57 +01:00
Josh Creek 56b676b04a perf(startup): defer offline sync and backup status until the grid is interactive
Both fired during hydration and competed with rendering the grid, and the layout
waited for the user store before it could show a signed-in shell even though the
server already knew who the user was.

Seed the user from the layout data, and queue the offline sync and backup
refresh behind the grid's interactive mark; an explicit refresh, a reconnect or
an edit still runs straight away. Backup refreshes now share one in-flight
request per generation, and a change of account cancels the pending startup
refresh and clears the stale status.
2026-09-15 17:48:49 +01:00
Josh Creek 19abb34693 fix(sync): keep queued catch-record writes from crossing an account change
The queue held whole records and flushed whatever was in it, so edits made
before a sign-out could be written against the account that signed in next.

Queue patches and merge them per key, so two edits to one entry combine instead
of one replacing the other; drop everything when the owning account is no longer
the current one; and stop scheduling flushes while offline, where they could only
fail and back off.
2026-09-15 17:48:34 +01:00
Josh Creek 54eaa6d776 fix(catch-records): stop bulk upserts clobbering fields a toggle never touched
Toggling one checkbox sent the whole record, so a stale copy of the other fields
could overwrite newer values. Send only the fields that changed, group rows by
the columns they carry, and upsert each group with defaultToNull: false so
omitted columns keep their stored value. Results are returned in the caller's
order rather than whatever order the groups came back in.
2026-09-15 17:48:34 +01:00
Josh Creek 2042e5a65a test(performance): add a local pokédex benchmark and run it in CI
Measures the pokédex load against a local Supabase with a generated fixture, and
compares runs so a regression shows up as a number rather than a hunch. Wired
into test:ci and given its own job so the artifacts survive a failure.
2026-09-15 17:47:21 +01:00
Josh Creek 2766e5ea67 build(cloudflare): add a Cloudflare preview build target
DEPLOY_TARGET now selects the adapter; Netlify stays the default and NODE_ADAPTER
keeps working. Cloudflare compresses in transit, so the Worker build aliases
$lib/server/compression to a pass-through that leaves the streaming body alone.

CI builds and dry-run deploys this target. That is compilation and packaging
coverage only, not a production compatibility gate: native sharp still blocks the
share-preview route in the Worker runtime.
2026-09-15 17:47:14 +01:00
Josh Creek b2b750115f perf(sprites): serve grid-sized thumbnails from an immutable URL space
Every grid cell downloaded the full detail sprite. Generate a smaller
/sprites-grid/v1/ set at build time and let the grid ask for those first,
falling back through the existing detail URLs when a thumbnail is missing so
detail resolution is unchanged. The new prefix is versioned, so it can be cached
forever, and the service worker recognises it alongside the other sprite roots.

The placeholder is now an empty box rather than a spinner: a thousand spinners
cost layout work and announced nothing useful.
2026-09-15 17:46:49 +01:00
Josh Creek 26b9e3b8c1 perf(pokedex): fetch dex scopes with the pokédex row
findById made a second round trip for scopes on every page load; embed
pokedex_dex_scopes in the select instead.
2026-09-15 17:46:23 +01:00
Josh Creek acaf760b36 perf(pokedex): send the box grid as packed rows with the page
The server load fetched a full combined-data page at a 9999 item page size,
carrying detail text and ownership fields the grid never renders, and the client
re-fetched the same payload after hydration.

Load a trimmed grid row instead and pack it as positional tuples so field names
are not repeated for every one of a thousand-plus entries. Entry detail is
fetched on demand from the new per-entry endpoint when a cell is opened, and the
grid marks itself interactive so other page-start work can queue behind it.
2026-09-15 17:46:19 +01:00
Josh Creek 4c268ba15c feat(pokedex): add opt-in Server-Timing for the pokédex load
POKEDEX_PERFORMANCE=true reports auth, ownership, scopes, entries and catches
with fixed labels only: no IDs, query strings, cookies or entry content ever
reach the header. Auth is measured in the hook, where the session is actually
resolved, and handed to the page load through locals.
2026-09-15 17:46:07 +01:00
Josh Creek 31fd959350 Merge pull request #98 from jcreek/perf/page-load-and-lighthouse
perf: fix slow page loads and gate performance in CI
2026-09-14 21:41:59 +01:00
Josh Creek 7603116369 ci(lighthouse): stop lhci reading the form factor as a CLI flag
lhci treats every LHCI_* environment variable as a command-line option, so
LHCI_PRESET=mobile reached `lhci assert` as an invalid --preset and failed
both jobs after the audits had run. Use LIGHTHOUSE_FORM_FACTOR instead.

Also upload the reports: upload-artifact v4+ skips dot-directories such as
.lighthouseci unless include-hidden-files is set.
2026-09-14 21:19:20 +01:00
Josh Creek 5d41462d35 test(bdd): find the account menu by its new accessible name
The avatar's alt text changed from "usericon" to "Account menu" as part of
the accessibility fixes, so the sign-out and offline-guide steps now look it
up by that name.
2026-09-14 20:59:38 +01:00
Josh Creek ff29095c47 perf: fix slow page loads and gate performance in CI
- Ship one hashed Tailwind stylesheet instead of two (one render-blocking)
- Compress responses in-app (brotli/gzip, streaming-safe) and precompress
  the node build so local and CI measurements match production
- Validate the Supabase session once per request
- Render the homepage immediately and stream public stats
- Stream a Pokedex's entries with the page instead of fetching after
  hydration, running the rows and count queries in parallel
- Shrink the avatar and offline placeholder images, fix layout shift,
  contrast, link names and missing meta descriptions
- Add Lighthouse CI (mobile + desktop) with score and metric budgets,
  bundle-size budgets in the build tests, and signed-in speed scenarios
2026-09-14 20:53:53 +01:00
Josh Creek 556f120f16 Merge pull request #97 from jcreek/fix/backup-reconnect-and-offline-guide
fix(backup): pause revoked backups and tell users to reconnect
2026-09-14 20:16:58 +01:00
Josh Creek 7786d46078 fix(backup): don't let a stale export pause a reconnected backup
- An export now pauses a revoked integration only if its row is
  unchanged since the export read it, using the trigger-maintained
  updatedAt column as the row version. If the user reconnected in the
  meantime, the stale failure no longer disables the fresh credentials
  or asks the user to reconnect again. updateExportStatus now reports
  whether a row was written.
- The backup status store ignores a response overtaken by a newer
  refresh, or by the status being flagged, cleared or set directly, so
  a slow response can't overwrite newer state.
- Unit tests cover the whole integration repository, the guarded pause
  and stale status responses. Coverage thresholds are raised to the
  new baseline.
2026-09-14 19:03:29 +01:00
Josh Creek fb95b43b30 fix(backup): pause revoked backups and tell users to reconnect
Google answers a revoked or expired refresh token with invalid_grant.
Every save then retried the dead token, and reconnecting never cleared
the old error, so it kept showing on Backup Settings afterwards.

- The Google Drive and Dropbox OAuth callbacks clear lastError when a
  provider is reconnected.
- An invalid_grant, or a missing refresh token, now pauses the
  integration with a readable "reconnect" message instead of retrying
  it on every catch update. Other failures still retry as before.
- A banner on every page and an alert on the Pokédex page point to
  Backup Settings, which shows a "Reconnect needed" badge. The Pokédex
  page re-checks backup status after each export, because saving a
  catch record also exports on the server and may pause a provider
  first.
- Offline sync status and the "Save all artwork" link move from every
  page to a new /offline-guide page, linked from the user menu and the
  home and welcome pages. Only the offline read-only banner stays
  sitewide.
- Unit tests cover every export path and the backup status store. BDD
  covers revocation and reconnecting for both providers, and the
  offline guide. The mock provider can now reject token refreshes, and
  mock control calls fail loudly if a stale mock is reused. Coverage
  thresholds are raised to the new baseline.
2026-09-14 18:46:09 +01:00
97 changed files with 14507 additions and 1043 deletions
+2
View File
@@ -11,3 +11,5 @@ node_modules
pnpm-lock.yaml
package-lock.json
yarn.lock
.wrangler/
+72
View File
@@ -80,6 +80,37 @@ jobs:
- run: npm ci
- run: npm run test:build
lighthouse:
runs-on: ubuntu-latest
timeout-minutes: 25
strategy:
fail-fast: false
matrix:
form-factor: [mobile, desktop]
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
node-version: 24
cache: npm
- run: npm ci
# The homepage streams public stats from the database, so audit against a real stack.
- run: npx supabase start
- run: npm run test:lighthouse
# Not LHCI_*: lhci reads any LHCI_ variable as a CLI flag (LHCI_PRESET became `--preset`).
env:
LIGHTHOUSE_FORM_FACTOR: ${{ matrix.form-factor }}
- uses: actions/upload-artifact@v6
if: always()
with:
name: lighthouse-${{ matrix.form-factor }}
path: .lighthouseci/
# upload-artifact v4+ skips dot-directories unless told otherwise.
include-hidden-files: true
if-no-files-found: ignore
- if: always()
run: npx supabase stop
bdd:
runs-on: ubuntu-latest
timeout-minutes: 30
@@ -113,3 +144,44 @@ jobs:
if-no-files-found: ignore
- if: always()
run: npx supabase stop
pokedex-performance:
runs-on: ubuntu-latest
timeout-minutes: 20
env:
PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER: 'true'
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
node-version: 24
cache: npm
- run: npm ci
- run: npx playwright install --with-deps chromium
- run: npx supabase start
- run: npm run test:performance
- uses: actions/upload-artifact@v6
if: always()
with:
name: pokedex-performance
path: test-results/performance/
if-no-files-found: ignore
- if: always()
run: npx supabase stop
cloudflare-preview-build:
runs-on: ubuntu-latest
timeout-minutes: 15
env:
WRANGLER_SEND_METRICS: 'false'
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
node-version: 24
cache: npm
- run: npm ci
- run: npm run build:cloudflare
- run: npm run check:cloudflare
# This is compilation/package coverage, not a production compatibility gate.
# Native sharp still blocks the share-preview route in the Worker runtime.
+4
View File
@@ -9,8 +9,12 @@ node_modules
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
/static/output.css
.lighthouseci
.netlify
.features-gen
coverage
playwright-report
test-results
/static/sprites-grid/
.wrangler/
+4
View File
@@ -13,3 +13,7 @@ static/sprites-small/manifest.json
# Machine-local editor and tool settings.
**/*.local.json
# Generated grid artwork and local Worker runtime output.
static/sprites-grid/
.wrangler/
+11 -1
View File
@@ -40,7 +40,17 @@ The test suite is split by responsibility so a failure points to the correct lay
- `tests/integration` checks the migrated Supabase schema, views, constraints, RLS, and repositories.
- `tests/bdd/features` is the executable Gherkin specification for user-visible behaviour. Step
definitions and browser fixtures live beside it under `tests/bdd`.
- `tests/build` verifies generated service-worker and manifest artifacts after each supported build.
- `tests/build` verifies generated service-worker and manifest artifacts after each supported build,
and fails if the gzipped JS or CSS every page loads grows past its budget.
- `lighthouserc.cjs` audits the public pages with Lighthouse CI (`npm run test:lighthouse`, which
builds and serves the Node output). PRs fail if Performance, Accessibility, Best Practices or SEO
drops below 90, or if LCP, TBT, CLS, script, stylesheet or total transfer size exceeds its budget.
CI runs it with both the mobile and desktop profiles (`LIGHTHOUSE_FORM_FACTOR=desktop`).
- `tests/bdd/features/performance.feature` holds time budgets for signed-in pages Lighthouse can't
reach: opening a Pokédex and switching between it and the Pokédex list.
The budgets sit just above current measurements so regressions fail the PR. If a change genuinely
needs more, raise the budget in the same PR so the cost is reviewed.
Run the offline suites while developing. `test:fast` includes the coverage run, so there is no need
to run both:
+3
View File
@@ -0,0 +1,3 @@
/sprites-grid/v1/*
Cache-Control: public, max-age=31536000, immutable
+7 -15
View File
@@ -2,19 +2,11 @@ import process from 'node:process';
import AdapterNode from '@sveltejs/adapter-node';
import AdapterNetlify from '@sveltejs/adapter-netlify';
export const nodeAdapter = process.env.NODE_ADAPTER === 'true';
// Netlify is the deployment target; the node adapter exists so the service worker
// build tests can check the `build/client` layout a Node server produces.
export const nodeAdapter =
process.env.NODE_ADAPTER === 'true' || process.env.DEPLOY_TARGET === 'node';
export const cloudflareAdapter = process.env.DEPLOY_TARGET === 'cloudflare';
export const adapter = nodeAdapter
? AdapterNode()
: AdapterNetlify({
// if true, will create a Netlify Edge Function rather
// than using standard Node-based functions
edge: false,
// if true, will split your app into multiple functions
// instead of creating a single one for the entire app.
// if `edge` is true, this option cannot be used
split: false
});
? AdapterNode({ precompress: true })
: cloudflareAdapter
? (await import('@sveltejs/adapter-cloudflare')).default()
: AdapterNetlify({ edge: false, split: false });
@@ -0,0 +1,57 @@
# Hosting evaluation: retain Netlify pending deployed evidence
Date: 15 September 2026. This is an interim decision report. **Do not cut over to Cloudflare yet.** The application improvements and selectable preview build are implemented, but the agreed real-host comparison cannot be completed with the current access and compatibility state.
## Evidence and decision
| Item | Observed result | Consequence |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| Production Netlify site | `livingdextracker`, `www.dextracker.uk`; published revision inspected: `31fd959350962c1f1b973a06ecd5cf4eeef86514` | This is the existing deployment, not this working tree |
| Function/database regions | Netlify `us-east-1`; linked Supabase `eu-north-1`; production public database URL matches that project | Cross-region round trips are a plausible contributor; their latency share is unmeasured |
| Node production checks | Compact SSR, details, status writes, offline behavior and rendering budgets exercised locally | Application evidence only |
| Cloudflare build | Adapter 7.2.9, Wrangler 4.131.2, compatibility date 2026-09-15, `nodejs_compat`; build and dry-run passed | Packaging is viable |
| Final Worker artifact | Approximately 1,876 KiB uncompressed / 336 KiB gzip; 9,621 static assets | Within published size/count limits; re-audit after renderer changes |
| Actual local workerd | Home, authenticated dex and public share page returned 200 | Basic runtime support demonstrated |
| Share image in workerd | `/shared/:token/preview.png` returned 500; `sharp` native module dynamic require is unsupported | **Compatibility gate failed**; see separate renderer proposal below |
| Remote preview access | Netlify CLI authenticated; Wrangler not authenticated; equivalent staging fixtures/accounts not supplied | No paired deployed samples collected |
No production deployment, DNS change, database migration or region change was performed. Retaining Netlify now is a decision under incomplete evidence and a failed compatibility gate, not evidence that Netlify is faster.
Netlify supports streaming; the investigation's buffering describes the installed adapter/runtime combination, not the entire platform. Cloudflare's supported SvelteKit adapter and partial Node compatibility do not imply support for native `sharp`. Sources: [Netlify streaming](https://docs.netlify.com/build/functions/lambda-compatibility/), [SvelteKit Cloudflare adapter](https://svelte.dev/docs/kit/adapter-cloudflare), [Cloudflare Node compatibility](https://developers.cloudflare.com/workers/runtime-apis/nodejs/).
## Build and environment requirements
- Default builds remain Netlify. `NODE_ADAPTER=true` or `DEPLOY_TARGET=node` selects Node. `npm run build:cloudflare` selects Workers with Static Assets; `npm run check:cloudflare` checks packaging; `npm run preview:cloudflare` runs workerd locally. Do not run builds concurrently.
- Cloudflare uses platform compression rather than the Node compression implementation. Verify actual deployed content encoding for HTML, SvelteKit data and JSON responses.
- Supply public Supabase URL/anon key at build time, and private Supabase/export/OAuth secrets through platform bindings. Preview secrets must belong to the same staging project on both hosts. Keep provider redirect allowlists and cookie/domain settings explicit.
- Authenticate Wrangler and select the intended account before creating a remote preview. Build/dry-run success does not authorize production routing.
- Current documented limits include 128 MB memory, one-second startup, 64 MiB uncompressed Worker size and 20,000/100,000 static files on Free/Paid. Each static file must be at most 25 MiB. Free CPU allowance is only 10 ms per invocation; do not assume the app or renderer fits it. Measure CPU/memory/startup under actual workerd and deployment. [Workers limits](https://developers.cloudflare.com/workers/platform/limits/)
## Separate proposal: Worker-compatible share-image renderer
This is the concrete implementation proposal required by the migration gate. It is **not implemented** in this change.
1. Extract the existing SVG construction, XML escaping and text truncation into a platform-neutral module. Preserve the endpoint, 1,200 × 630 dimensions, progress values, privacy behavior and cache headers.
2. Keep a Node renderer using `sharp`. Add a Cloudflare renderer using `@resvg/resvg-wasm`, selected through the same build-time platform alias pattern as compression. Pin a verified version in the renderer change; exclude native `sharp` from the Worker dependency graph.
3. Bundle the renderer's WASM as a module and initialize lazily once per isolate through a shared promise. Import a compiled WebAssembly module using the supported Workers approach, rather than assuming a browser-style URL fetch loader works. Release per-render allocations after producing a PNG byte array. [Workers WASM support](https://developers.cloudflare.com/workers/runtime-apis/webassembly/javascript/), [resvg WASM package](https://github.com/thx/resvg-js/tree/main/wasm)
4. Bundle licensed regular/bold fonts, for example Noto Sans with its license. Explicitly map SVG weights to those fonts; do not rely on operating-system fonts. Verify accented Pokémon names, punctuation, long descriptions and the intended non-Latin fallback policy. Font appearance will need review against existing PNGs.
5. Add golden-image/metadata tests for empty/long names, XML special characters, all badges and 0/100% progress. Exercise concurrent requests, first invocation, repeated renders and error recovery in built workerd. Require HTTP 200, PNG signature/dimensions, correct sharing access and no private notes.
6. Re-audit bundle/assets, CPU, memory and startup after adding WASM/fonts. Run the deployed share-image test and backup/export/auth matrix before setting compatibility to passed. If this renderer exceeds operating constraints, compare a separately hosted image service in a new proposal; do not silently redirect rendering to production Netlify.
## Remaining deployed benchmark
1. Supply equivalent staging credentials and disposable national/scoped-form fixtures, then publish this exact code to both preview hosts. Preserve actual deployed revision and environment metadata.
2. Establish improved Netlify document/data baselines. Consider a separate region-aligned Netlify preview as an additional experiment; do not change the primary paired comparison mid-run.
3. Exercise sign-in, token refresh, account switching, Google/Dropbox OAuth and refresh, export generation, public shares/images, compression, secrets/bindings, static cache headers, service-worker install/update/offline routing and custom preview domains on both real hosts.
4. Use the [comparison harness](pokedex-implementation.md#instrumentation-and-comparison-harness) for at least 30 warm samples per host × fixture × direct/client navigation. Keep code, Supabase project, fixtures, browser settings and client locations identical. Run additional deliberately idled samples and record the idle duration separately; first-observed is not a cold-start claim.
5. Recommend migration only when overall first-interactive p75 improves by **both 20% and 200 ms**, no fixture/navigation combination regresses by more than 10%, and functional checks pass. Include costs and operating requirements before making the final decision.
## Cost projection and operations
Actual monthly traffic, CPU usage and the account's current Netlify billing arrangement are not available, so no savings claim is justified.
Cloudflare Paid has a $5/month minimum, includes 10 million dynamic requests and 30 million CPU-ms, then charges $0.30/million requests and $0.02/million CPU-ms. Direct static asset requests are free; requests served through Workers Caching have different billing. Illustrative direct-static configuration: 1 million dynamic requests at 20 ms CPU each remains within $5; 10 million at 20 ms is approximately $8.40. These exclude other services and are assumptions, not measured app CPU. [Workers pricing](https://developers.cloudflare.com/workers/platform/pricing/)
For credit-based Netlify plans, estimate credits as `15 × production deploys + 10 × compute GB-hours + 20 × bandwidth GB + 2 × requests/10,000`. Confirm whether this account uses credit-based or legacy billing and apply its actual plan/allowance. Thumbnail byte savings affect bandwidth, while increased first-party sprite requests affect request metering. [Netlify pricing](https://www.netlify.com/pricing/)
Before a qualifying cutover: move database migrations out of host builds into one serialized CI release step; provision secrets and OAuth redirects; validate the custom domain and cookies; monitor error/latency/export metrics; retain the working Netlify deployment and a documented DNS rollback. These production changes remain conditional on completing the gates above.
+115
View File
@@ -0,0 +1,115 @@
# Pokédex performance implementation
Status: application changes implemented; hosting comparison remains gated. Measurements below are local production-build evidence, not deployed latency improvements. See [hosting evaluation](pokedex-hosting-evaluation.md) for the migration decision and remaining work.
## Application changes
- Ownership and saved scope links are read together. Scoped entry retrieval is shared by rows/count consumers; the full grid performs no count query. Catch joins use ID maps. Scope deduplication, named default forms, supplements and ordering remain covered by repository tests.
- The page awaits the entire compact grid and renders initial boxes on the server. Authentication state reaches SSR through the validated layout user. Successful navigation needs no grid API request; failed grid loads expose retry.
- `PokedexGridRow` contains identity, sprite resolution fields and catch flags. The page and authenticated `/api/pokedexes/[id]/grid` endpoint transport named tuples defined in `PokedexGridRow.ts`; `packGrid`/`unpackGrid` keep that wire format out of components. Instructions, notes, origin games and repeated owner/dex IDs are absent. Existing full combined-data consumers retain their contracts.
- The detail endpoint verifies ownership and membership before returning one full `CombinedData` row. The modal opens immediately with identity and full artwork, then loads editable details. Its account/dex/entry cache, abort/sequence checks and pending-patch merge protect rapid selection changes and optimistic edits.
- Status writes send changed fields. Bulk writes group records by supplied columns, preserving omitted notes and flags; explicit empty notes clear them. New records use database defaults. Full-record callers and exports remain supported. Bulk box actions still target all original 30 slots, including dimmed entries.
- Grid placeholders preserve geometry; visible boxes and one row of overscan mount populated cells. Focused boxes remain mounted, keyboard navigation crosses boundaries, modal close restores focus, and an accessible render-all option exposes the complete document. Each Pokémon uses one button with identity/status and a noninteractive tooltip.
- Density is persisted in a cookie for stable SSR geometry and in local storage. Resize/density changes preserve the current box anchor. Existing local-storage-only preferences are replaced by the cookie after choosing a density.
- Automatic snapshot/backup work starts at the interactive/idle boundary with a five-second fallback. Concurrent backup refreshes coalesce. Explicit sync and edit/account/reconnect invalidations retain freshness behavior. Backup-status GET no longer revalidates via `setSession`.
- Complete offline snapshot format 2 is retained. Offline modal details come only from the matching account snapshot; missing copies report unavailable details. Offline details are read-only, as before for offline mutations.
## Artwork and build behavior
`npm run sprites:grid` generates 3,170 first-party WebP thumbnails, at most 128 pixels per side, quality 80. Builds run this automatically. Generated assets live in ignored `static/sprites-grid/v1/`; the generator emits a manifest. Originals remain 512 pixels for details and explicit full-artwork downloads.
The generated catalog is 10,007,504 bytes versus 53,659,230 bytes for the source WebP catalog (81.4% smaller). Shiny, female and named-form resolution uses the existing key/fallback chain. The service worker recognizes versioned grid sprites in the existing artwork cache; neither thumbnail nor original catalogs are blanket precached. Root `_headers` supplies immutable caching on Netlify/Cloudflare. Bump the URL version whenever generation settings or source images change; generation skips existing files within a version.
## Local acceptance evidence
Fixtures: national (1,025 entries), Scarlet/Paldea forms (439 entries), mixed catch flags and nonempty notes. Integration tests additionally cover missing catches and overlapping scopes through repository tests. Browser viewport: 1,350 × 940, comfortable density, Chromium, local Node production build and local seeded Supabase.
The packed grid is approximately 81 KB national and 36 KB scoped, versus the investigation's approximately 593 KB and 255 KB full-data JSON. The same-fixture integration assertion separately verifies at least 60% reduction against full combined rows. These are serialized row sizes, not compressed HTML document sizes.
The local browser checks verify at most 180 populated mounted cells, fewer than 2,500 DOM elements and CLS at most 0.1; observed initial population is 120 cells. Density/mobile checks include all three densities at 1,350 and 390 pixels. Detail artwork is asserted to load at 512 pixels. No redundant grid request is allowed; intentional detail requests are allowed.
Warm results from the corrected harness (30 samples per row; [sanitized summary](pokedex-local-results.json)):
| Fixture | Navigation | First visible p75 | First interactive p75 | Decoded response bytes p75 | Maximum DOM |
| ------------ | ---------- | ----------------: | --------------------: | -------------------------: | ----------: |
| National | Direct | 123.5 ms | 145.4 ms | 248,668 | 2,088 |
| National | Client | 495.6 ms | 494.1 ms | 102,687 | 2,090 |
| Scoped forms | Direct | 114.5 ms | 133.1 ms | 203,601 | 2,073 |
| Scoped forms | Client | 491.7 ms | 490.6 ms | 45,645 | 2,075 |
Every warm sample had 120 populated cells, zero observed CLS, zero redundant grid requests and a measured response size. Direct response bytes include SSR markup and SvelteKit data; client bytes are SvelteKit data responses, not just the packed rows. Interactive marks can precede the next animation-frame visibility observation by a few milliseconds. Client timings include Playwright click overhead, as explained below. This benchmark preceded the final account-switch backup invalidation guard; the final production smoke suite also passed after that guard.
### Validation completed
| Check | Result |
| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| Svelte/TypeScript | 0 errors; one existing `Tooltip.svelte` CSS `@apply` warning |
| Unit tests | 193 passed |
| Data tests | 18 passed |
| Coverage | Existing thresholds passed: 66.81% lines/statements, 88.79% branches, 90.99% functions |
| Local Supabase integration | 16 passed, including same-fixture payload reduction and note preservation |
| Authenticated browser regressions | 53 passed, including mock Google/Dropbox OAuth, exports and service-worker/offline flows |
| Build matrix | Four checks in each of Netlify/Node × generateSW/injectManifest passed |
| Production performance/behavior | Both fixtures, all densities/mobile, resize anchor, focus/keyboard, modal race, full artwork and offline snapshot isolation passed |
| Cloudflare | Final build and Wrangler dry-run passed; local workerd share-image generation failed as documented in the hosting report |
| Formatting/lint | All changed/new implementation files pass Prettier; ESLint and `git diff --check` pass |
Repository-wide `npm run lint` also scans the pre-existing untracked `dex.har` and `POKEDEX_PERFORMANCE_PROMPT.md`; those two files have formatting warnings and were intentionally left untouched. No coverage threshold was lowered. Disposable performance accounts and local test servers were cleaned up.
### Reproduce
```sh
npm ci
npx supabase start
npx playwright install chromium
npm run check
npm run test:unit
npm run test:integration
npm run test:build
PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER=true npm run test:bdd
npm run test:performance
PERF_BENCHMARK=true npm run test:performance
```
Run builds sequentially: they share `.svelte-kit` and `build`. Performance tests create a disposable local-only account, use private temporary session files, clean up afterward, and copy sanitized reports/screenshots to ignored `test-results/performance/`. Cleanup failures retain recovery files. Never commit session/configuration files.
## Instrumentation and comparison harness
Set `POKEDEX_PERFORMANCE=true` on a preview to emit fixed-label `Server-Timing` stages: auth, ownership, scopes, entries, catches, preparation and total. Timings do not include IDs, cookies, notes or query text. Authentication includes the request hook's validation. Total measures the page/service span, not total platform request lifetime; stages may therefore not sum to total.
The browser harness measures first visible cells via animation frames and first interactive cells via `pokedex:first-interactive`, independently of response completion. It collects DOM/cells, layout shifts, intentional/redundant API counts and response sizes. For Chromium service-worker responses where Playwright cannot read the body, decoded Resource Timing bytes are used; absent measurements stay null. Decoded, encoded and transferred bytes are distinguished.
`benchmark.mjs` requires at least 30 warm samples per fixture/navigation combination. It records the first observed run separately; that is **not** evidence of a cold start or first-after-idle run. For real-host work, collect deliberately idled runs separately and record the idle interval. Client timing starts before Playwright's click, so includes its actionability overhead; preserve identical tooling/settings between hosts and report this limitation.
Private configuration example (replace all placeholders):
```json
{
"samples": 30,
"revision": "exact-deployed-commit",
"databaseLabel": "same-staging-project",
"clientLocation": "London-fixed-runner",
"environment": "deployed",
"compatibilityPassed": false,
"hosts": [
{
"label": "netlify",
"url": "https://NETLIFY-PREVIEW",
"storageState": "/PRIVATE/netlify-session.json",
"fixtures": [
{ "id": "NATIONAL-ID", "name": "Performance National", "label": "national" },
{ "id": "SCOPED-ID", "name": "Performance Scarlet Forms", "label": "scoped-forms" }
]
}
]
}
```
Add an equivalent `cloudflare` host using the same database and fixtures. Run:
```sh
node scripts/performance/benchmark.mjs /PRIVATE/config.json /PRIVATE/results.json
node scripts/performance/compare.mjs /PRIVATE/results.json
```
The comparison refuses insufficient samples and retains Netlify unless deployed evidence, compatibility and the agreed improvement thresholds all pass. Human review must still establish costs, environment equivalence and deployment prerequisites.
+227
View File
@@ -0,0 +1,227 @@
# Signed-in Pokédex performance investigation
Investigated 1415 September 2026 at commit `31fd959350962c1f1b973a06ecd5cf4eeef86514`.
## Findings
The production capture establishes a server-response bottleneck: **3,506 ms waiting versus 261 ms receiving** the Pokédex data response. The current loading design exposes all entry work to that wait on the installed Netlify adapter. It requests practically the entire dex, and the adapter buffers the response before returning it. Independently, mounting the entire grid causes avoidable browser work.
Local measurements confirm the request sequence, duplicate game-scoped queries, large payload and rendering cost. **They do not explain the exact allocation of production's 3.5 seconds.** Regions, function startup and production query timings remain unverified. At the user's direction, no further production/dashboard access was attempted; subsequent measurements used local Supabase.
No performance fixes, migrations, deployment settings, public APIs or types were changed. Temporary instrumentation and the diagnostic rendering cap were removed. Full-resolution artwork must remain available when a user opens a Pokémon's detail view.
The numerical evidence, including individual runs and sanitized server traces, is in [pokedex-results.json](pokedex-results.json).
## Production evidence and its limits
| Evidence | Result | Interpretation |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- |
| Supplied `dex.har`, data navigation | Wait 3,506.100 ms; receive 260.671 ms; 401,199 uncompressed bytes | Waiting dominates transfer. This includes server and network effects; it is not a database timer. |
| Response headers | Brotli; `private,no-store`; Netlify request ID present | Compression already exists. User-specific content is not served as a public CDN cache hit. |
| HAR content | Response text absent | Cannot measure production field sizes or infer the dex's form/scope configuration from this file. |
| HAR sprites | 36 requests, 531,086 bytes total, `max-age=300` | Visible artwork has a substantial transfer cost independent of entry data. |
| Supplied Lighthouse summary | Root response 3,373 ms; about 386 KB serialized inline data; 10,442 DOM elements; 1.9 s rendering; CLS 0.127 | Corroborates both server wait and browser cost. These are user-supplied findings, not a new run. |
The HAR contains only one application request plus the 36 sprite requests. It does **not** contain the offline-snapshot or backup-status requests; their production sizes/durations come from the supplied Lighthouse summary. Extension findings were excluded.
### Why streaming currently fails to hide the work
[The server load](../../src/routes/pokedex/[id]/+page.server.ts) returns an unresolved `initialCombinedData` promise, but `INITIAL_PAGE_SIZE` is **9,999**, matching the client. Its `.then()` discards the count/pagination metadata after the shared service has calculated it.
[adapter.mjs](../../adapter.mjs) selects standard Netlify functions (`edge: false`), except for Node test builds. Installed `@sveltejs/adapter-netlify` **4.4.2**, in `node_modules/@sveltejs/adapter-netlify/files/esm/serverless.js`, awaits `response.text()` for text responses and `response.arrayBuffer()` for binary responses. Both buffer the body before the handler returns. This proves the behavior of the installed adapter; the exact deployed package/build was not accessible. The HAR's long wait is consistent with it.
[Compression](../../src/lib/server/compression.ts) already skips application compression in Lambda because Netlify handles it. Enabling more compression would not fix this buffering boundary. The page also assigns its entries client-side, so even genuine transport streaming does not mean the grid is server-rendered and interactive immediately.
An isolated local identity-encoding stream probe received first bytes before completion:
| Dex | First-byte median | Complete-body median |
| ------------- | ----------------: | -------------------: |
| National | 48.3 ms | 104.7 ms |
| Scarlet forms | 36.8 ms | 72.5 ms |
These are Vite measurements, not evidence that Netlify streams.
## Server request map and timings
Sources: [session hook](../../src/hooks.server.ts), [ownership repository](../../src/lib/repositories/PokedexRepository.ts), [scope service](../../src/lib/services/PokedexDexScopeService.ts), [combined-data service](../../src/lib/services/CombinedDataService.ts), [combined-data repository](../../src/lib/repositories/CombinedDataRepository.ts).
For an unexpired authenticated session, both measured dexes make **eight Supabase HTTP requests per page/data request**:
| Stage | National: 1,025 entries | Scarlet Paldea forms: 439 entries |
| ---------------------------------------- | ------------------------------------------ | ------------------------------------------ |
| Authentication | 1 `getUser` | 1 `getUser` |
| Ownership, then scope links | 1 `pokedexes`, then 1 `pokedex_dex_scopes` | Same |
| Entry branch | 2 sequential entry pages: 1,000 + 25 | 1 game-dex query, then 1 forms query |
| Count branch, parallel with entry branch | 1 HEAD exact-count query | Repeats the game-dex query and forms query |
| Catches, after entry retrieval | 2 sequential chunks: 1,000 + 25 | 1 chunk: 439 |
| Total / longest chain of requests | **8 / 7** | **8 / 6** |
The game query returns 400 rows. The named-form query returns 45 rows; six are already represented, leaving 39 supplements and 439 unique entries. The count branch repeats both reads, transferring another **277,047 bytes** from Supabase just to count those entries. The two branches run concurrently: eliminating duplication reduces work and traffic, but does not necessarily remove their summed durations from the critical path.
General case:
- National path: `3 + entry-page requests + 1 count + catch chunks`. Pagination continues until a short/empty batch or the requested limit. An exact multiple of 1,000 may require an empty terminal request. Catch chunks use at most 1,000 IDs.
- Explicit game scopes: `3 + 2 × (dex-page requests + applicable form-page requests) + catch chunks`. Counting fetches the full scope even when the requested page is small. Deduplication and slicing happen in JavaScript.
- A game scope without saved dex scopes adds two sequential reads (`games`, then `game_dexes`). National dexes still pay the scope-link query even though scope resolution itself returns immediately.
- Token refresh can add an authentication request. A separate probe using an expired saved cookie produced nine requests; the reported baseline was rerun with a fresh session. Replaying that stale cookie every time was a probe artifact, not normal browser session behavior.
- `safeGetSession` is shared within a request, not across navigation and background requests.
### Isolated local server timings
Five warm requests per dex, one first run excluded. Queries were instrumented at the Supabase fetch boundary, including response-body completion; repository methods were timed separately. The cloned response used for instrumentation adds overhead. All values below are medians, so columns are not additive.
| Measure | National | Scarlet forms |
| --------------------------------------------------- | -------: | ------------: |
| Auth `getUser` HTTP duration | 35.5 ms | 25.3 ms |
| Ownership + scope-link HTTP durations | 8.0 ms | 7.2 ms |
| `findCombinedData`, including entries and catches | 50.7 ms | 33.3 ms |
| `countCombinedData`, concurrent with find | 6.6 ms | 25.6 ms |
| Catch retrieval, included within find | 16.4 ms | 6.5 ms |
| Sum of all query durations | 92.9 ms | 86.0 ms |
| Elapsed request time to final query-body completion | 87.6 ms | 64.1 ms |
| Complete HTTP response | 104.7 ms | 72.5 ms |
| Supabase response-body bytes, summed | 917,728 | 709,996 |
The difference between summed query durations and elapsed completion reflects concurrency. Repository work, serialization, streaming and measurement overhead sit outside or between query timings. Do not subtract these local medians from production TTFB to invent a region/startup estimate.
### Query plans and indexes
`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` ran under the local `authenticated` role with the fixture user's JWT subject. These are SQL execution times, excluding HTTP, PostgREST JSON serialization and function/network latency.
| Query shape | Median of five warm executions |
| ------------------------------------------------- | -----------------------------: |
| National ordered entries, first 1,000 | 5.557 ms |
| National ordered entries, offset 1,000 | 5.866 ms |
| National exact count through the view | 2.484 ms |
| Scarlet game-dex detail rows | 10.706 ms |
| Named forms available in Scarlet | 2.934 ms |
| Catch query with the actual first 1,000 entry IDs | 0.476 ms |
The entry view joins and aggregates origin-game data before returning rows. The game-dex plan aggregates 1,390 Pokémon before joining the 400 scoped entries. The offset query repeats aggregation/sorting for the last 25 rows. These are real work amplification, but small absolute local costs.
The game membership index and existing catch-record dex index are used. The exact catch query is already sub-millisecond locally. **No new index is justified by these measurements.** Prefer avoiding duplicate/full-view work before speculative indexing. The evidence JSON also retains an earlier catch-plan probe with an ID subquery; the literal-ID result above is the closer match to the application.
## Payload and browser measurements
### Method and fixtures
- Existing local Supabase seed: 1,390 catalog entries, 1,025 default forms. No reset or migration was run.
- Dedicated disposable account: national living dex with 1,025 catch records; Scarlet/Paldea form dex with 1,390 seeded catch records, of which 439 match this view. Mixed deterministic statuses and empty personal notes. Existing user data was preserved.
- Headless Playwright Chromium, 1,350 × 940 viewport, device scale 1, no extensions, no CPU/network throttling. Vite 5.4.21 development server, Node 24.18.0, same-origin sprites.
- One first run plus five warm runs for each navigation/dex combination. Client navigation clicks the real card's View button from My Pokédexes. Each client sample starts from a loaded list page with a 1.1-second settling period.
- “Visible cells” uses Playwright's first-cell visibility check and includes automation overhead. Response completion is network response completion, not full page idle. Layout/style time is CDP `LayoutDuration + RecalcStyleDuration` over the sample and 1.5-second follow-up; it is not Lighthouse's entire rendering category.
| Dex / navigation | First-run visible | Five warm visible times | Median TTFB | Median response complete | Median visible | DOM |
| ---------------------- | ----------------: | -------------------------- | ----------: | -----------------------: | -------------: | -----: |
| National / direct | 798 ms | 549, 986, 519, 474, 432 ms | 84 ms | 268 ms | **519 ms** | 10,236 |
| National / client | 407 ms | 322, 335, 369, 423, 381 ms | 63 ms | 133 ms | **369 ms** | 10,236 |
| Scarlet forms / direct | 462 ms | 309, 278, 299, 312, 317 ms | 68 ms | 148 ms | **309 ms** | 4,476 |
| Scarlet forms / client | 224 ms | 272, 227, 233, 363, 274 ms | 59 ms | 111 ms | **272 ms** | 4,476 |
These development results must not be equated with optimized production performance. Local full-dataset fixture content, development scripts/styles and serialized session metadata differ from the production capture. The initial Vite dependency-optimization failure was resolved before collecting this matrix. One first-run streamed response could not be read through Chromium's body-capture API; its bytes are recorded as null, not zero.
### What is needed at first paint
At this viewport the national dex mounts 35 boxes and 1,025 populated cells, with only **60 cells visible**. Scarlet mounts 15 boxes and 439 cells, also with 60 visible. The national grid is 10,532 px tall. IntersectionObserver already defers distant sprite downloads; it does not prevent mounting those cells, tooltip components and loading spinners. There were 73 image elements, not 1,025 downloaded sprites.
The box and tooltip need identity/name/form/number/sprite key and catch-status flags. Evolution/catch instructions, origin games, dex notes and personal notes belong to the detail workflow. Repeated catch `userId`/`pokedexId` values are also expensive in ordinary JSON. The page still needs global totals and stable placement, so simply lowering the limit would break existing behavior.
| JSON measurement | National | Scarlet forms |
| ------------------------------------------------- | --------: | ------------: |
| Full combined rows | 592,997 B | 255,319 B |
| Display-only rows for every entry | 170,636 B | 74,154 B |
| Display-only first 60 entries | 9,751 B | 10,757 B |
| Detail-only Pokémon fields, separately serialized | 214,064 B | 91,887 B |
“Display-only” is a sizing experiment, **not a proposed drop-in API**: it excludes identifiers/fields that writes and details currently need. JSON partitions are serialized separately and are not additive. Actual SvelteKit data responses use a different serialization format: warm client response medians were 518,649 B and 222,892 B. Direct development documents were about 686 KB and 375 KB; their largest inline scripts were 545,897 B and 235,175 B.
### Controlled rendering comparison
A temporary diagnostic changed only the rendered box loop to its first two boxes, leaving the fetched full dataset intact. Both comparisons blocked the two background endpoints, used the existing offline worker, and measured five warm direct loads plus 2.5 seconds after visibility. The full loop was restored afterward.
| Measure | All 35 boxes | First 2 boxes only |
| ----------------------------------------------- | -----------: | -----------------: |
| Mounted populated cells | 1,025 | 60 |
| DOM elements | 10,236 | 728 |
| Median time to visible cells | 464 ms | 318 ms |
| Median layout/style work | 63.9 ms | 13.4 ms |
| Median main-thread task time during observation | 1,124 ms | 82.8 ms |
| Median accumulated long-task duration | 147 ms | 0 ms |
This isolates a substantial browser cost from mounting the full view; it does not demonstrate a complete virtualization implementation or guarantee the same production savings. Off-screen spinner components remain mounted in the full view, but this experiment does not separately attribute their cost.
Direct-load layout-shift observations varied (roughly 0.0820.657), with footer/content shifts recorded. Client-click samples recorded zero, partly because recent-input shifts are excluded. These short development observations are not interchangeable with production's Lighthouse CLS of 0.127. Reserve appropriate loading geometry when redesigning rendering.
## Background requests and artwork
[Offline synchronization](../../src/lib/stores/offlineSync.ts) schedules startup after one second and reuses a matching format-2 snapshot younger than 15 minutes. Explicit edits, retry, account changes and reconnect trigger a fresh copy. [The snapshot endpoint](../../src/routes/api/offline-snapshot/+server.ts) loads every owned dex in parallel, including full entry/detail/catch data. For this account that is ten Supabase calls with a fresh token, independent of the page's eight.
A separate local comparison activated the existing offline worker and controlled metadata age in the disposable browser cache. Five warm direct loads per condition:
| Condition | Median visible cells | Snapshot requests per load | Backup requests per load |
| -------------------------------------- | -------------------: | -------------------------: | -----------------------: |
| Fresh snapshot, enabled | 449 ms | 0 | 1 |
| Stale snapshot, enabled | 431 ms | 1 | 1 |
| Stale snapshot, both endpoints blocked | 464 ms | 0 completed | 0 completed |
The stale snapshot was **849,107 B**, typically around 130160 ms locally. It started around 1.2 seconds after navigation, after cells were visible. Backup status began around 0.20.3 seconds, overlapping rendering. Blocking requests did **not** improve time to visible cells consistently in these runs. Thus background work is a secondary bandwidth/CPU/DB contention concern, not a demonstrated explanation of initial local TTFB. An already-running snapshot could overlap a later client navigation; the production HAR cannot establish that.
[Backup status GET](../../src/routes/api/export-integrations/+server.ts) calls `requireAuth`, reads the memoized session, then calls `supabase.auth.setSession(session)`. Instrumentation observed **two `GET /auth/v1/user` requests plus one integration query**. Memoizing `safeGetSession` does not eliminate validation triggered by this separate `setSession` call.
The worker stores snapshot data without automatically fetching all artwork; artwork fetches are cached as viewed, and full artwork download is explicit. The initial dev navigation matrix had no registered worker, so its snapshot requests did not establish cache-reuse behavior; that is why the separate worker-enabled comparison was necessary.
### Preserve detail-image resolution
[Sprite URL resolution](../../src/lib/utils/spriteUrl.ts) selects local assets only when `PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER` is `true`; otherwise it uses GitHub raw URLs. The HAR confirms the latter for production. Local `home/1.webp` and `home/shiny/1.webp` are both 512 × 512. In-memory 128 px WebP experiments at quality 80 reduced 13,530 → 2,726 B and 12,634 → 2,522 B (about 80%). Two samples are not a catalog-wide saving estimate.
**Retain the 512 px originals for the clicked Pokémon detail view.** If pursuing this optimization, introduce separate grid thumbnails and retain full-resolution detail URLs, with fallback coverage for shiny, female and named forms. Update manifest/cache versioning deliberately; replacing assets at existing URLs conflicts with the worker's cache-forever assumption. The sprite build script currently defaults `SPRITE_MAX_SIZE` to zero, so “sprites-small” does not imply smaller dimensions. No sprite files were changed.
## Ranked recommendations
| Priority | Recommended next change | Evidence / confidence | Effort and risk |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 1 | Stop computing an unused count in the page preload; share one ordered scoped-entry retrieval when rows and count are both needed. Combine ownership and scope retrieval where practical. | Confirmed redundant work: one national count or two full scoped queries, plus serial metadata reads. High confidence in work reduction; production milliseconds unknown. | Lowmedium. Preserve ownership/RLS, scope deduplication, named default forms and ordering. |
| 2 | Reduce initial data and the number of mounted boxes together. Evaluate viewport rendering with reserved space, lightweight global totals/order, and on-demand detail data. | Only 60/1,025 cells visible; capped rendering reduced visible time 31%, layout/style work 79%, DOM 93%. Display-only JSON is about 71% smaller. | Mediumhigh. Preserve box numbering, scroll/keyboard access, global filters/counts, bulk edits, navigation races and offline details. Do not just change `9999` to `60`. |
| 3 | Resolve the Netlify buffering constraint as part of the loading design. Validate a supported streaming-capable adapter/runtime in a future deployment, or make the initial response intentionally small without relying on deferred promises. | Installed adapter demonstrably buffers. High confidence in the constraint; no deployed streaming alternative verified. | Medium. Keep Netlify as target; test both document and data navigation. A shell alone is not an interactive grid. |
| 4 | Remove redundant backup-session validation if authentication remains guaranteed; schedule nonessential background work after critical page work while preserving snapshot freshness and explicit syncs. | Three backup calls confirmed; stale snapshot 849 KB. No consistent local first-visibility gain when blocked. | Lowmedium. Verify reconnect status and account isolation; do not disable offline support. |
| 5 | Serve separate grid thumbnails, retaining full-resolution detail artwork. Evaluate first-party hosting/cache headers for those assets. | Two samples about 80% smaller; production HAR sprite transfer 531 KB. | Medium. Preserve all variants and offline cache behavior. Requires separate thumbnail URLs, not destructive resizing. |
| 6 | Replace per-entry linear catch lookup with a map when touching repository joins. | `.find()` per row has quadratic scaling, but current local processing is small. | Low. Lower priority than network, payload and DOM work. |
Do not propose a database index or a region move as an established fix from the available evidence. Production-specific stage instrumentation and region verification remain future work requiring access.
### Regression coverage and secondary findings
[Lighthouse CI](../../lighthouserc.cjs) audits only five signed-out pages using the Node adapter. [Signed-in BDD scenarios](../../tests/bdd/features/performance.feature) allow five seconds for direct load and three seconds per switch, assert first-cell visibility and prohibit a separate entry request. Those checks do not exercise Netlify's response buffering, assert authenticated data/DOM sizes, or distinguish shell, first cells and completed loading.
Future checks should use a full national fixture and a scoped form fixture, measure document and client navigation separately, and track response bytes, mounted cells, first useful view and background request counts. Preserve ordering, overlapping dex deduplication, named default forms, missing catches, filters, bulk status updates, modal notes, shiny/female artwork, account changes and fresh/stale offline behavior. A deliberate loading redesign may require replacing the “no separate entry request” assertion with a user-visible timing/data budget. Deployment checks must exercise actual Netlify responses, not infer parity from Node CI.
The nested `<button>` in [Tooltip](../../src/lib/components/Tooltip.svelte) is confirmed by source inside each Pokémon button. Address its accessible name and invalid nesting in follow-up UI work. Contrast, target-size and missing-meta-description findings are secondary to the performance diagnosis; contrast/target size require rendered theme/mobile verification, while the missing page description is visible in source. Preserve detail-view artwork quality as requested.
## Reproduction and cleanup
Raw captures, disposable credentials and diagnostic scripts are local-only under `/tmp/pokedex-perf-investigation` (directory mode 700); they are not included in the repository evidence. The evidence JSON omits sessions, fixture IDs, personal data and full query filters. The original `dex.har` and prompt remain untouched and untracked.
The seeded stack was already running. Instead of resetting it or invoking Tailwind output generation, the investigation used the project's loopback-checked Supabase environment wrapper and the same Vite dev server used by `dev:supabase`:
```sh
# From the repository root; these diagnostic scripts are retained locally, not installed tooling.
node /tmp/pokedex-perf-investigation/setup.mjs
node scripts/run-with-local-supabase.mjs node /tmp/pokedex-perf-investigation/seed.mjs
node scripts/run-with-local-supabase.mjs node /tmp/pokedex-perf-investigation/auth.mjs
PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER=true node scripts/run-with-local-supabase.mjs npx vite dev --host 127.0.0.1 --port 4173 > /tmp/pokedex-perf-investigation/dev.log 2>&1
# In another terminal, after Vite dependency optimization has settled:
node /tmp/pokedex-perf-investigation/measure.mjs
node /tmp/pokedex-perf-investigation/background.mjs
node /tmp/pokedex-perf-investigation/server-probe.mjs
node /tmp/pokedex-perf-investigation/analyze-server.mjs
node /tmp/pokedex-perf-investigation/explain.mjs
node /tmp/pokedex-perf-investigation/catch-plan.mjs
# After stopping the dev server and restoring the instrumented files:
node scripts/run-with-local-supabase.mjs node /tmp/pokedex-perf-investigation/cleanup.mjs
```
The rendering-cap experiment temporarily changed `{#each boxNumbers as boxNumber}` to `{#each boxNumbers.slice(0, 2) as boxNumber}`, then ran `PERF_VARIANT=grid-cap node /tmp/pokedex-perf-investigation/grid-cap.mjs` and restored the file. Run comparisons sequentially, discard the first run and keep viewport/cache/fixture settings equal. The full methodology and sanitized per-run evidence above remain usable if the temporary scripts are later removed.
At completion, original application files were restored byte-for-byte, the investigation server was stopped, and only the dedicated fixture account and its cascading test records were deleted. Existing database data and production configuration were unchanged. No commit was created.
@@ -0,0 +1,60 @@
{
"capturedAt": "2026-09-15T16:28:41.386Z",
"environment": "local-node",
"revision": "local-working-tree",
"clientLocation": "local-loopback",
"groups": [
{
"fixture": "national",
"navigation": "direct",
"samples": 30,
"visibleP75": 123.5,
"interactiveP75": 145.40000009536743,
"responseBytesP75": 248668,
"missingBytes": 0,
"maxDOM": 2088,
"maxCells": 120,
"maxCLS": 0,
"gridRequests": 0
},
{
"fixture": "national",
"navigation": "client",
"samples": 30,
"visibleP75": 495.59999990463257,
"interactiveP75": 494.09999990463257,
"responseBytesP75": 102687,
"missingBytes": 0,
"maxDOM": 2090,
"maxCells": 120,
"maxCLS": 0,
"gridRequests": 0
},
{
"fixture": "scoped-forms",
"navigation": "direct",
"samples": 30,
"visibleP75": 114.5,
"interactiveP75": 133.10000014305115,
"responseBytesP75": 203601,
"missingBytes": 0,
"maxDOM": 2073,
"maxCells": 120,
"maxCLS": 0,
"gridRequests": 0
},
{
"fixture": "scoped-forms",
"navigation": "client",
"samples": 30,
"visibleP75": 491.7000000476837,
"interactiveP75": 490.60000014305115,
"responseBytesP75": 45645,
"missingBytes": 0,
"maxDOM": 2075,
"maxCells": 120,
"maxCLS": 0,
"gridRequests": 0
}
]
}
File diff suppressed because it is too large Load Diff
+55
View File
@@ -0,0 +1,55 @@
// Lighthouse CI: `npm run test:lighthouse` builds the Node adapter output, serves it and audits the
// public pages. Any category below 90 fails the run (and so the PR).
// Set LIGHTHOUSE_FORM_FACTOR=desktop to audit with the desktop profile; the default is Lighthouse's
// mobile profile (slow 4G + CPU throttling), which is the stricter of the two. The variable must not
// start with LHCI_: lhci treats those as CLI flags, so LHCI_PRESET was passed to `lhci assert` as
// an invalid `--preset`.
const preset = process.env.LIGHTHOUSE_FORM_FACTOR === 'desktop' ? 'desktop' : undefined;
module.exports = {
ci: {
collect: {
startServerCommand: 'npm run preview-node',
startServerReadyPattern: 'Listening on',
url: [
'http://localhost:4173/',
'http://localhost:4173/signin',
'http://localhost:4173/welcome',
'http://localhost:4173/offline-guide',
'http://localhost:4173/forgot-password'
],
// Median of three runs smooths out noise from shared CI runners.
numberOfRuns: 3,
settings: {
...(preset ? { preset } : {}),
chromeFlags: '--no-sandbox --headless=new'
}
},
assert: {
assertions: {
'categories:performance': ['error', { minScore: 0.9 }],
'categories:accessibility': ['error', { minScore: 0.9 }],
'categories:best-practices': ['error', { minScore: 0.9 }],
'categories:seo': ['error', { minScore: 0.9 }],
// The app compresses its own responses (see src/lib/server/compression.ts and the
// precompressed build), so nothing may be served uncompressed.
'uses-text-compression': ['error', { minScore: 1 }],
// Regression budgets, set a little above what every audited page measured in September
// 2026 (mobile profile: LCP 1.4-2.6 s, TBT 0 ms, CLS 0, ~100 KB script, ~14 KB CSS and
// ~175 KB in total over the wire). A PR that makes pages meaningfully slower or heavier
// fails here even while the category scores stay above 90. When a change legitimately
// needs more, raise the number in the same PR so the cost is reviewed.
'largest-contentful-paint': ['error', { maxNumericValue: 3000 }],
'total-blocking-time': ['error', { maxNumericValue: 200 }],
'cumulative-layout-shift': ['error', { maxNumericValue: 0.05 }],
'resource-summary:script:size': ['error', { maxNumericValue: 115 * 1024 }],
'resource-summary:stylesheet:size': ['error', { maxNumericValue: 20 * 1024 }],
'resource-summary:total:size': ['error', { maxNumericValue: 220 * 1024 }]
}
},
upload: {
target: 'filesystem',
outputDir: '.lighthouseci/reports'
}
}
};
+4650 -61
View File
File diff suppressed because it is too large Load Diff
+19 -10
View File
@@ -8,12 +8,12 @@
"dev-generate-suppress-w": "GENERATE_SW=true SUPPRESS_WARNING=true npx tailwindcss -i ./static/input.css -o ./static/output.css && vite dev",
"sprites:build": "node scripts/optimize-sprites.mjs",
"sprites:manifest": "node scripts/sprite-manifest.mjs",
"build-generate-sw": "npm run tailwind && GENERATE_SW=true vite build",
"build-generate-sw-node": "npm run tailwind && NODE_ADAPTER=true GENERATE_SW=true vite build",
"build": "npm run tailwind && vite build",
"build-inject-manifest": "npm run tailwind && vite build",
"build-inject-manifest-node": "npm run tailwind && NODE_ADAPTER=true vite build",
"build-self-destroying": "npm run tailwind && SELF_DESTROYING_SW=true vite build",
"build-generate-sw": "npm run sprites:grid && npm run tailwind && GENERATE_SW=true vite build",
"build-generate-sw-node": "npm run sprites:grid && npm run tailwind && NODE_ADAPTER=true GENERATE_SW=true vite build",
"build": "npm run sprites:grid && npm run tailwind && vite build",
"build-inject-manifest": "npm run sprites:grid && npm run tailwind && vite build",
"build-inject-manifest-node": "npm run sprites:grid && npm run tailwind && NODE_ADAPTER=true vite build",
"build-self-destroying": "npm run sprites:grid && npm run tailwind && SELF_DESTROYING_SW=true vite build",
"preview": "vite preview --port=4173",
"preview-node": "PORT=4173 node build",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
@@ -21,7 +21,8 @@
"lint": "prettier --check . && eslint .",
"lint-fix": "npm run lint --fix",
"format": "prettier --write .",
"tailwind": "npx tailwindcss -i ./static/input.css -o ./static/output.css",
"tailwind": "npx tailwindcss -i ./static/input.css -o ./static/output.css --minify",
"test:lighthouse": "npm run build-inject-manifest-node && lhci autorun",
"test:unit": "vitest run tests/unit",
"test:data": "vitest run tests/data",
"test:coverage": "vitest run tests/unit --coverage",
@@ -35,7 +36,7 @@
"test:build:inject-static": "npm run build-inject-manifest && vitest run --config vitest.build.config.mts",
"test:build:inject-node": "npm run build-inject-manifest-node && NODE_ADAPTER=true vitest run --config vitest.build.config.mts",
"test:build": "npm run test:build:generate-static && npm run test:build:generate-node && npm run test:build:inject-static && npm run test:build:inject-node",
"test:ci": "npm run test:fast && npm run test:integration && npm run test:build && npm run test:bdd",
"test:ci": "npm run test:fast && npm run test:integration && npm run test:build && npm run test:bdd && npm run test:performance",
"test": "npm run test:ci",
"supabase:start": "supabase start",
"supabase:stop": "supabase stop",
@@ -43,11 +44,18 @@
"supabase:studio": "supabase studio",
"migrate:convert-tsv": "node scripts/convert-tsv-to-sql.js",
"dev:local": "./scripts/dev-local.sh && npm run dev",
"dev:supabase": "supabase start && npm run dev"
"dev:supabase": "supabase start && npm run dev",
"sprites:grid": "node scripts/grid-thumbnails.mjs",
"build:cloudflare": "DEPLOY_TARGET=cloudflare npm run build",
"preview:cloudflare": "wrangler dev",
"check:cloudflare": "wrangler deploy --dry-run",
"test:performance": "node scripts/run-with-local-supabase.mjs node scripts/performance/run-local.mjs"
},
"devDependencies": {
"@lhci/cli": "^0.15.1",
"@playwright/test": "1.55.1",
"@sveltejs/adapter-auto": "^3.0.0",
"@sveltejs/adapter-cloudflare": "7.2.9",
"@sveltejs/adapter-netlify": "^4.1.0",
"@sveltejs/adapter-node": "^2.0.0",
"@sveltejs/adapter-static": "^3.0.0",
@@ -75,7 +83,8 @@
"tailwindcss": "^3.4.3",
"tslib": "^2.6.2",
"typescript": "^5.3.3",
"vitest": "^1.0.4"
"vitest": "^1.0.4",
"wrangler": "4.131.2"
},
"type": "module",
"dependencies": {
+35
View File
@@ -0,0 +1,35 @@
import { readdir, mkdir, stat, writeFile } from 'node:fs/promises';
import path from 'node:path';
import sharp from 'sharp';
// Bump the URL version whenever dimensions, quality or source artwork changes.
const source = 'static/sprites-small/home';
const destination = 'static/sprites-grid/v1/home';
const files = [];
async function walk(relative = '') {
for (const entry of await readdir(path.join(source, relative), { withFileTypes: true })) {
const name = path.join(relative, entry.name);
if (entry.isDirectory()) await walk(name);
else if (entry.name.endsWith('.webp')) files.push(name);
}
}
await walk();
const manifest = [];
for (const relative of files.sort()) {
const target = path.join(destination, relative);
await mkdir(path.dirname(target), { recursive: true });
try {
await stat(target);
} catch {
await sharp(path.join(source, relative))
.resize(128, 128, { fit: 'inside', withoutEnlargement: true })
.webp({ quality: 80 })
.toFile(target);
}
manifest.push({ path: relative.split(path.sep).join('/'), bytes: (await stat(target)).size });
}
await writeFile(
'static/sprites-grid/v1/manifest.json',
JSON.stringify({ version: 1, width: 128, quality: 80, files: manifest })
);
console.log(`Prepared ${files.length} versioned grid thumbnails; originals preserved.`);
+13 -2
View File
@@ -3,7 +3,7 @@
import { createServer } from 'node:http';
const port = Number(process.env.MOCK_PROVIDER_PORT ?? 4199);
const state = { requests: [], failUploads: false, refreshes: 0 };
const state = { requests: [], failUploads: false, revokeRefresh: false, refreshes: 0 };
function send(response, status, body, headers = {}) {
response.writeHead(status, { 'Content-Type': 'application/json', ...headers });
@@ -25,6 +25,7 @@ const server = createServer(async (request, response) => {
if (url.pathname === '/__mock/reset') {
state.requests = [];
state.failUploads = false;
state.revokeRefresh = false;
state.refreshes = 0;
return send(response, 200, { ok: true });
}
@@ -32,6 +33,10 @@ const server = createServer(async (request, response) => {
state.failUploads = true;
return send(response, 200, { ok: true });
}
if (url.pathname === '/__mock/revoke-refresh') {
state.revokeRefresh = true;
return send(response, 200, { ok: true });
}
if (url.pathname.endsWith('/authorize')) {
const redirectUri = url.searchParams.get('redirect_uri');
@@ -45,7 +50,13 @@ const server = createServer(async (request, response) => {
}
if (url.pathname.endsWith('/token')) {
if (body.includes('grant_type=refresh_token')) state.refreshes++;
if (body.includes('grant_type=refresh_token')) {
state.refreshes++;
// Mirrors Google and Dropbox answering a revoked or expired refresh token.
if (state.revokeRefresh) {
return send(response, 400, { error: 'invalid_grant', error_description: 'Bad Request' });
}
}
return send(response, 200, {
access_token: 'mock-access-token',
refresh_token: 'mock-refresh-token',
+181
View File
@@ -0,0 +1,181 @@
import { chromium } from '@playwright/test';
import { readFile, writeFile } from 'node:fs/promises';
// Configuration holds session-file paths, never passwords. Keep it outside the repository.
const [configPath, outputPath] = process.argv.slice(2);
if (!configPath || !outputPath)
throw new Error('Usage: node scripts/performance/benchmark.mjs CONFIG.json RESULTS.json');
const config = JSON.parse(await readFile(configPath, 'utf8'));
const samples = config.samples ?? 30;
if (samples < 30)
throw new Error('Host decisions require at least 30 warm samples per fixture/navigation');
if (!config.revision || !config.databaseLabel || !config.clientLocation)
throw new Error('Record revision, databaseLabel and clientLocation for comparable results');
const browser = await chromium.launch();
const results = [];
try {
for (const host of config.hosts) {
for (const fixture of host.fixtures) {
for (const navigation of ['direct', 'client']) {
const context = await browser.newContext({
baseURL: host.url,
storageState: host.storageState,
viewport: { width: 1350, height: 940 },
deviceScaleFactor: 1
});
await context.addInitScript(() => {
window.__perfShifts = [];
new PerformanceObserver((list) => {
for (const entry of list.getEntries())
if (!entry.hadRecentInput)
window.__perfShifts.push({ value: entry.value, time: entry.startTime });
}).observe({ type: 'layout-shift', buffered: true });
window.__watchGrid = () => {
window.__perfVisible = null;
function check() {
const cell = document.querySelector('[data-entry-index]');
if (
location.pathname.startsWith('/pokedex/') &&
cell &&
cell.getBoundingClientRect().top < innerHeight &&
cell.getBoundingClientRect().height > 0
) {
window.__perfVisible = performance.now();
performance.mark('pokedex:first-visible');
} else requestAnimationFrame(check);
}
requestAnimationFrame(check);
};
window.__watchGrid();
});
const page = await context.newPage();
for (let index = 0; index <= samples; index++) {
if (navigation === 'client') {
await page.goto('/my-pokedexes');
await page.getByText(fixture.name, { exact: true }).first().waitFor();
} else if (index > 0) await page.goto('about:blank');
const bodies = [];
const requests = { grid: 0, details: 0, snapshot: 0, backup: 0 };
const onRequest = (request) => {
const path = new URL(request.url()).pathname;
if (/\/pokedexes\/[^/]+\/(grid|combined-data)$/.test(path)) requests.grid++;
if (/\/pokedexes\/[^/]+\/entries\//.test(path)) requests.details++;
if (path === '/api/offline-snapshot') requests.snapshot++;
if (path === '/api/export-integrations') requests.backup++;
};
const onResponse = (response) => {
const path = new URL(response.url()).pathname;
if (!path.startsWith(`/pokedex/${fixture.id}`)) return;
bodies.push(
(async () => {
// Chromium may not expose bodies routed through a service worker.
const body = await response.body().catch(() => null);
return {
url: response.url(),
bytes: body?.length ?? null,
status: response.status(),
fromServiceWorker: response.fromServiceWorker(),
timings: response.request().timing(),
serverTiming: response.headers()['server-timing'] ?? null
};
})()
);
};
page.on('request', onRequest);
page.on('response', onResponse);
let started = 0;
if (navigation === 'direct')
await page.goto(`/pokedex/${fixture.id}`, { waitUntil: 'domcontentloaded' });
else {
started = await page.evaluate(() => {
performance.clearMarks('pokedex:first-interactive');
window.__watchGrid();
return performance.now();
});
await page
.locator('.card')
.filter({ hasText: fixture.name })
.first()
.getByRole('button', { name: 'View', exact: true })
.click();
}
await page.waitForSelector('[data-grid-interactive]');
await page.waitForFunction(
() =>
window.__perfVisible !== null &&
performance.getEntriesByName('pokedex:first-interactive').length > 0
);
await page.waitForTimeout(1500);
const browserData = await page.evaluate(
(start) => ({
visibleMs: window.__perfVisible - start,
interactiveMs:
performance.getEntriesByName('pokedex:first-interactive').at(-1).startTime - start,
cells: document.querySelectorAll('[data-entry-index]').length,
dom: document.querySelectorAll('*').length,
cls: window.__perfShifts
.filter((entry) => entry.time >= start)
.reduce((total, entry) => total + entry.value, 0)
}),
started
);
page.off('request', onRequest);
page.off('response', onResponse);
const resources = await page.evaluate(() =>
performance.getEntriesByType('resource').map((entry) => ({
url: entry.name,
decodedBytes: entry.decodedBodySize,
encodedBytes: entry.encodedBodySize,
transferBytes: entry.transferSize
}))
);
const responses = (await Promise.all(bodies)).map(({ url, ...response }) => {
const resource = resources.findLast((entry) => entry.url === url);
return {
...response,
bytes: response.bytes ?? (resource?.decodedBytes || null),
byteSource: response.bytes !== null ? 'response-body' : 'resource-timing',
encodedBytes: resource?.encodedBytes ?? null,
transferBytes: resource?.transferBytes ?? null
};
});
results.push({
host: host.label,
fixture: fixture.label,
navigation,
run: index === 0 ? 'first-observed' : 'warm',
...browserData,
requests,
responses
});
}
await context.close();
console.log(
`Completed ${host.label}/${fixture.label}/${navigation}: ${samples} warm samples.`
);
}
}
}
await writeFile(
outputPath,
JSON.stringify(
{
version: 1,
capturedAt: new Date().toISOString(),
revision: config.revision,
databaseLabel: config.databaseLabel,
clientLocation: config.clientLocation,
environment: config.environment ?? 'deployed',
compatibilityPassed: config.compatibilityPassed ?? false,
results
},
null,
2
)
);
console.log(
`Recorded ${results.length} samples; first-observed runs are excluded from warm statistics.`
);
} finally {
await browser.close();
}
+46
View File
@@ -0,0 +1,46 @@
import { readFile } from 'node:fs/promises';
const data = JSON.parse(await readFile(process.argv[2], 'utf8'));
const warm = data.results.filter((row) => row.run === 'warm');
const p75 = (values) => [...values].sort((a, b) => a - b)[Math.ceil(values.length * 0.75) - 1];
const groups = [...new Set(warm.map((row) => `${row.fixture}/${row.navigation}`))];
const paired = groups.map((group) => {
const rows = (host) =>
warm.filter((row) => `${row.fixture}/${row.navigation}` === group && row.host === host);
for (const host of ['netlify', 'cloudflare'])
if (rows(host).length < 30) throw new Error(`Insufficient ${host} warm samples for ${group}`);
return {
group,
netlify: p75(rows('netlify').map((row) => row.interactiveMs)),
cloudflare: p75(rows('cloudflare').map((row) => row.interactiveMs))
};
});
if (groups.length !== 4)
throw new Error(
'Expected national and scoped-form fixtures, each with direct and client navigation'
);
const netlify = p75(warm.filter((row) => row.host === 'netlify').map((row) => row.interactiveMs));
const cloudflare = p75(
warm.filter((row) => row.host === 'cloudflare').map((row) => row.interactiveMs)
);
const improvement = netlify - cloudflare;
const passes =
improvement >= 200 &&
improvement / netlify >= 0.2 &&
paired.every((row) => row.cloudflare <= row.netlify * 1.1);
console.log(
JSON.stringify(
{
overallP75: { netlify, cloudflare },
improvementMs: improvement,
improvementPercent: (100 * improvement) / netlify,
groups: paired,
performanceGatePassed: passes,
recommendation:
passes && data.compatibilityPassed && data.environment === 'deployed'
? 'Cloudflare qualifies for a migration proposal; review operating cost before cutover.'
: 'Retain Netlify: performance, deployed evidence or compatibility gate is unmet.'
},
null,
2
)
);
+113
View File
@@ -0,0 +1,113 @@
import { createClient } from '@supabase/supabase-js';
import { createServerClient } from '@supabase/ssr';
import { mkdir, readFile, writeFile, unlink } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
const directory = process.env.PERF_FIXTURE_DIR ?? '/tmp/livingdex-grid-performance';
const url = process.env.PUBLIC_SUPABASE_URL;
if (!url || !['localhost', '127.0.0.1', '[::1]'].includes(new URL(url).hostname))
throw new Error('Fixtures require the local Supabase wrapper');
const admin = createClient(url, process.env.SUPABASE_SERVICE_ROLE_KEY, {
auth: { persistSession: false }
});
const check = ({ data, error }) => {
if (error) throw error;
return data;
};
await mkdir(directory, { recursive: true, mode: 0o700 });
const fixturePath = `${directory}/fixture.json`;
if (process.argv.includes('--cleanup')) {
const fixture = JSON.parse(await readFile(fixturePath, 'utf8'));
const { user } = check(await admin.auth.admin.getUserById(fixture.userId));
if (user.email !== fixture.email || !user.email.startsWith('grid-performance-'))
throw new Error('Refusing to remove a non-fixture account');
check(await admin.auth.admin.deleteUser(fixture.userId));
await unlink(fixturePath);
await unlink(`${directory}/storage-state.json`).catch(() => {});
console.log('Removed disposable performance account and session.');
process.exit(0);
}
try {
await readFile(fixturePath);
throw new Error('An existing fixture needs cleanup first');
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
const email = `grid-performance-${randomUUID()}@example.test`;
const password = randomUUID() + 'aA1!';
const { user } = check(await admin.auth.admin.createUser({ email, password, email_confirm: true }));
const fixture = { userId: user.id, email, password, dexes: [] };
await writeFile(fixturePath, JSON.stringify(fixture), { mode: 0o600 });
fixture.dexes = check(
await admin
.from('pokedexes')
.insert([
{ userId: user.id, name: 'Performance National', isLivingDex: true, isFormDex: false },
{
userId: user.id,
name: 'Performance Scarlet Forms',
isLivingDex: true,
isFormDex: true,
gameScope: 'Scarlet'
}
])
.select()
);
const game = fixture.dexes.find((dex) => dex.gameScope);
check(
await admin.from('pokedex_dex_scopes').insert({ pokedexId: game.id, dexId: 'scarlet-paldea' })
);
const entries = [];
for (let from = 0; ; from += 1000) {
const page = check(
await admin
.from('pokemon')
.select('id,isDefaultForm')
.order('id')
.range(from, from + 999)
);
entries.push(...page);
if (page.length < 1000) break;
}
for (const dex of fixture.dexes) {
const selected = entries.filter((entry) => dex.isFormDex || entry.isDefaultForm);
for (let from = 0; from < selected.length; from += 500) {
check(
await admin.from('catch_records').insert(
selected.slice(from, from + 500).map((entry, index) => ({
userId: user.id,
pokedexId: dex.id,
pokemonId: entry.id,
caught: (from + index) % 3 === 0,
haveToEvolve: (from + index) % 3 === 1,
inHome: (from + index) % 7 === 0,
personalNotes: index === 0 ? 'Performance fixture note: preserve me' : ''
}))
)
);
}
}
await writeFile(fixturePath, JSON.stringify(fixture), { mode: 0o600 });
const cookies = [];
const client = createServerClient(url, process.env.PUBLIC_SUPABASE_ANON_KEY, {
cookies: { getAll: () => [], setAll: (values) => cookies.push(...values) }
});
check(await client.auth.signInWithPassword({ email, password }));
const base = new URL(process.env.PERF_BASE_URL ?? 'http://127.0.0.1:4173');
await writeFile(
`${directory}/storage-state.json`,
JSON.stringify({
cookies: cookies.map(({ name, value }) => ({
name,
value,
domain: base.hostname,
path: '/',
httpOnly: false,
secure: base.protocol === 'https:',
sameSite: 'Lax'
})),
origins: []
}),
{ mode: 0o600 }
);
console.log('Prepared national and scoped-form fixtures and a private browser session.');
+105
View File
@@ -0,0 +1,105 @@
import { spawn } from 'node:child_process';
import { mkdtemp, mkdir, cp, rm, readFile, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
const directory = await mkdtemp(path.join(os.tmpdir(), 'livingdex-grid-tests-'));
const port = process.env.PERF_PORT ?? '4185';
const env = {
...process.env,
NODE_ADAPTER: 'true',
PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER: 'true',
POKEDEX_PERFORMANCE: 'true',
PERF_FIXTURE_DIR: directory,
PERF_BASE_URL: `http://127.0.0.1:${port}`,
PORT: port,
HOST: '127.0.0.1'
};
function run(command, args) {
return new Promise((resolve, reject) => {
const process = spawn(command, args, { env, stdio: 'inherit' });
process.once('error', reject);
process.once('exit', (code) =>
code === 0 ? resolve() : reject(new Error(`${command} failed (${code})`))
);
});
}
let server;
let fixture = false;
try {
await run('npm', ['run', 'build-inject-manifest-node']);
fixture = true;
await run('node', ['scripts/performance/fixture.mjs']);
server = spawn('node', ['build'], { env, stdio: 'inherit' });
await new Promise((resolve, reject) => {
const timer = setInterval(async () => {
try {
if ((await fetch(env.PERF_BASE_URL)).ok) {
clearInterval(timer);
clearTimeout(timeout);
resolve();
}
} catch {}
}, 200);
const timeout = setTimeout(() => {
clearInterval(timer);
reject(new Error('Local production server did not start'));
}, 15000);
server.once('error', (error) => {
clearInterval(timer);
clearTimeout(timeout);
reject(error);
});
server.once('exit', (code) => {
clearInterval(timer);
clearTimeout(timeout);
reject(new Error(`Local server exited (${code})`));
});
});
if (process.env.PERF_BENCHMARK === 'true') {
const data = JSON.parse(await readFile(path.join(directory, 'fixture.json'), 'utf8'));
await writeFile(
path.join(directory, 'benchmark-config.json'),
JSON.stringify({
samples: 30,
revision: process.env.PERF_REVISION ?? 'local-working-tree',
databaseLabel: 'local-seeded-supabase',
clientLocation: 'local-loopback',
environment: 'local-node',
hosts: [
{
label: 'node',
url: env.PERF_BASE_URL,
storageState: path.join(directory, 'storage-state.json'),
fixtures: data.dexes.map((dex) => ({
id: dex.id,
name: dex.name,
label: dex.gameScope ? 'scoped-forms' : 'national'
}))
}
]
})
);
await run('node', [
'scripts/performance/benchmark.mjs',
path.join(directory, 'benchmark-config.json'),
path.join(directory, 'benchmark.json')
]);
await mkdir('test-results/performance', { recursive: true });
await cp(path.join(directory, 'benchmark.json'), 'test-results/performance/benchmark.json');
}
await run('node', ['scripts/performance/verify.mjs']);
await run('node', ['scripts/performance/verify-behavior.mjs']);
await mkdir('test-results/performance', { recursive: true });
for (const file of ['verification.json', 'behavior.json', 'national.png', 'scoped.png'])
await cp(path.join(directory, file), path.join('test-results/performance', file));
} finally {
server?.kill('SIGTERM');
if (fixture)
await run('node', ['scripts/performance/fixture.mjs', '--cleanup']).catch((error) => {
throw new Error(`Fixture cleanup failed; retained recovery files in ${directory}`, {
cause: error
});
});
await rm(directory, { recursive: true, force: true });
}
+165
View File
@@ -0,0 +1,165 @@
import { chromium } from '@playwright/test';
import { readFile, writeFile } from 'node:fs/promises';
import assert from 'node:assert/strict';
const dir = process.env.PERF_FIXTURE_DIR ?? '/tmp/livingdex-grid-performance';
const fixture = JSON.parse(await readFile(`${dir}/fixture.json`, 'utf8'));
const browser = await chromium.launch();
const context = await browser.newContext({
baseURL: process.env.PERF_BASE_URL ?? 'http://127.0.0.1:4173',
storageState: `${dir}/storage-state.json`,
viewport: { width: 1350, height: 940 }
});
await context.addInitScript(() => {
window.__cls = 0;
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) if (!entry.hadRecentInput) window.__cls += entry.value;
}).observe({ type: 'layout-shift', buffered: true });
});
const page = await context.newPage();
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
const national = fixture.dexes.find((dex) => !dex.gameScope);
const scoped = fixture.dexes.find((dex) => dex.gameScope);
const results = [];
try {
await page.goto(`/pokedex/${national.id}`);
await page.waitForSelector('[data-grid-interactive]');
for (const width of [1350, 390]) {
await page.setViewportSize({ width, height: 940 });
for (const density of ['comfortable', 'compact', 'ultra']) {
await page.getByLabel('Choose box view layout density').selectOption(density);
await page.reload();
await page.waitForSelector('[data-grid-interactive]');
await page.waitForTimeout(350);
assert.equal(await page.getByLabel('Choose box view layout density').inputValue(), density);
const geometry = await page.evaluate(() => {
const cell = document.querySelector('[data-entry-index="0"]').getBoundingClientRect();
const shell = document.querySelector('[data-box-number="1"]').getBoundingClientRect();
return {
cellWidth: cell.width,
cellHeight: cell.height,
cls: window.__cls,
horizontalOverflow: document.documentElement.scrollWidth > innerWidth,
shellHeight: shell.height
};
});
assert.ok(Math.abs(geometry.cellWidth - geometry.cellHeight) < 1, JSON.stringify(geometry));
assert.ok(!geometry.horizontalOverflow, `Horizontal overflow at ${width}/${density}`);
assert.ok(geometry.cls <= 0.1, `CLS ${geometry.cls} at ${width}/${density}`);
results.push({ width, density, ...geometry });
}
}
await page.setViewportSize({ width: 1350, height: 940 });
await page.getByLabel('Choose box view layout density').selectOption('comfortable');
await page.getByLabel('Not caught', { exact: true }).check();
assert.equal(await page.locator('[data-entry-index="0"]').getAttribute('aria-disabled'), 'true');
assert.equal(await page.locator('[data-entry-index="0"]').getAttribute('data-entry-id'), '1');
await page.getByLabel('Not caught', { exact: true }).uncheck();
// Resizing across the mobile breakpoint keeps the same box at the scroll anchor.
await page.locator('[data-box-number="15"]').evaluate((node) => node.scrollIntoView());
await page.waitForTimeout(100);
const anchorTop = await page
.locator('[data-box-number="15"]')
.evaluate((node) => node.getBoundingClientRect().top);
await page.setViewportSize({ width: 390, height: 940 });
await page.waitForTimeout(200);
const resizedTop = await page
.locator('[data-box-number="15"]')
.evaluate((node) => node.getBoundingClientRect().top);
assert.ok(
Math.abs(anchorTop - resizedTop) < 2,
`Scroll anchor moved: ${anchorTop} to ${resizedTop}`
);
await page.setViewportSize({ width: 1350, height: 940 });
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
await page.waitForSelector('[data-entry-index="1024"]');
assert.ok((await page.locator('[data-entry-index]').count()) < 300);
await page.locator('[data-entry-index="1024"]').focus();
await page.keyboard.press('ArrowRight');
assert.equal(
await page.evaluate(() => document.activeElement.getAttribute('data-entry-index')),
'1024'
);
await page.evaluate(() => window.scrollTo(0, 0));
await page.waitForSelector('[data-entry-index="0"]');
// Closing an in-flight modal must prevent its response from replacing the next selection.
let release;
const held = new Promise((resolve) => {
release = resolve;
});
await page.route(`**/api/pokedexes/${national.id}/entries/1`, async (route) => {
await held;
await route.continue().catch(() => {});
});
await page.locator('[data-entry-index="0"]').click();
await page.getByRole('dialog').getByRole('button', { name: 'Close', exact: true }).click();
await page.locator('[data-entry-index="1"]').click();
release();
await page.getByRole('dialog').getByLabel('Notes:', { exact: true }).waitFor();
assert.equal(
await page.getByRole('dialog').getByRole('heading', { name: 'Ivysaur', exact: true }).count(),
1
);
assert.equal(
await page.getByRole('dialog').getByRole('heading', { name: 'Bulbasaur', exact: true }).count(),
0
);
await page.getByRole('dialog').getByRole('button', { name: 'Close', exact: true }).click();
await page.unrouteAll({ behavior: 'wait' });
// Navigate through actual list cards, preserving fixture-specific totals and positions.
await page.getByRole('link', { name: 'My Pokédexes' }).click();
await page
.locator('.card')
.filter({ hasText: scoped.name })
.first()
.getByRole('button', { name: 'View', exact: true })
.click();
await page.waitForSelector('[data-grid-interactive]');
assert.ok((await page.locator('body').innerText()).includes('Showing 439 of 439'));
await page.goBack();
await page
.locator('.card')
.filter({ hasText: national.name })
.first()
.getByRole('button', { name: 'View', exact: true })
.click();
await page.waitForSelector('[data-grid-interactive]');
// Wait for the existing worker's full snapshot, then read an uncached detail without a network.
await page.waitForFunction(
async () => {
const meta = await (
await caches.open('livingdex-offline-meta-v1')
).match('/__offline/current');
return !!(await meta?.json())?.dataCache;
},
{ timeout: 15000 }
);
await context.setOffline(true);
await page.locator('[data-entry-index="5"]').click();
await page.waitForFunction(() =>
document.querySelector('[role="dialog"]')?.textContent.includes('Where to catch:')
);
assert.equal(await page.getByRole('dialog').locator('textarea').count(), 0);
await page.getByRole('dialog').getByRole('button', { name: 'Close', exact: true }).click();
// A mismatched cache owner is never used as fallback.
await page.evaluate(async () => {
const cache = await caches.open('livingdex-offline-meta-v1');
const response = await cache.match('/__offline/current');
const meta = await response.json();
await cache.put(
'/__offline/current',
new Response(JSON.stringify({ ...meta, userId: 'other-account' }))
);
});
await page.locator('[data-entry-index="6"]').click();
await page.getByRole('alert').filter({ hasText: 'not saved for offline use' }).waitFor();
await page.getByRole('dialog').getByRole('button', { name: 'Close', exact: true }).click();
assert.deepEqual(errors, []);
await writeFile(`${dir}/behavior.json`, JSON.stringify(results, null, 2));
console.log(
'Passed density/mobile geometry, filtered placement, virtual boundaries, modal races, client navigation and isolated offline details.'
);
console.log(JSON.stringify(results, null, 2));
} finally {
await browser.close();
}
+129
View File
@@ -0,0 +1,129 @@
import { chromium } from '@playwright/test';
import { readFile, writeFile } from 'node:fs/promises';
import assert from 'node:assert/strict';
const directory = process.env.PERF_FIXTURE_DIR ?? '/tmp/livingdex-grid-performance';
const fixture = JSON.parse(await readFile(`${directory}/fixture.json`, 'utf8'));
const baseURL = process.env.PERF_BASE_URL ?? 'http://127.0.0.1:4173';
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({
baseURL,
storageState: `${directory}/storage-state.json`,
viewport: { width: 1350, height: 940 }
});
await context.addInitScript(() => {
window.__layoutShifts = [];
window.__firstVisible = null;
new PerformanceObserver((list) => {
for (const entry of list.getEntries())
if (!entry.hadRecentInput) window.__layoutShifts.push(entry.value);
}).observe({ type: 'layout-shift', buffered: true });
function visible() {
const cell = document.querySelector('[data-entry-index]');
if (
cell &&
cell.getBoundingClientRect().height > 0 &&
cell.getBoundingClientRect().top < innerHeight
)
window.__firstVisible ??= performance.now();
if (window.__firstVisible === null) requestAnimationFrame(visible);
}
requestAnimationFrame(visible);
});
const page = await context.newPage();
const readJson = (path) =>
page.evaluate(async (path) => {
const response = await fetch(path);
if (!response.ok) throw new Error(`Fixture API failed: ${response.status}`);
return response.json();
}, path);
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
const requests = [];
page.on('request', (request) => requests.push(new URL(request.url()).pathname));
const results = [];
try {
for (const dex of fixture.dexes) {
requests.length = 0;
const response = await page.goto(`/pokedex/${dex.id}`);
assert.equal(response.status(), 200);
const html = await response.text();
assert.ok(/data-entry-index=["']?0["'\s>]/.test(html), 'Initial cells must be server rendered');
await page.waitForSelector('[data-grid-interactive]');
await page.waitForTimeout(1000);
const stats = await page.evaluate(() => ({
cells: document.querySelectorAll('[data-entry-index]').length,
dom: document.querySelectorAll('*').length,
cls: window.__layoutShifts.reduce((sum, value) => sum + value, 0),
firstVisible: window.__firstVisible,
interactive: performance.getEntriesByName('pokedex:first-interactive').at(-1)?.startTime
}));
assert.ok(stats.cells <= 180, `Mounted cells: ${stats.cells}`);
assert.ok(stats.dom < 2500, `DOM elements: ${stats.dom}`);
assert.ok(stats.cls <= 0.1, `CLS: ${stats.cls}`);
assert.equal(
requests.filter((path) => /\/api\/pokedexes\/[^/]+\/(grid|combined-data)$/.test(path)).length,
0
);
assert.equal(await page.locator('button button').count(), 0);
await page.screenshot({ path: `${directory}/${dex.gameScope ? 'scoped' : 'national'}.png` });
const first = page.locator('[data-entry-index="0"]');
const entryId = await first.getAttribute('data-entry-id');
const notes = await readJson(`/api/pokedexes/${dex.id}/entries/${entryId}`);
await first.click();
const modal = page.getByRole('dialog', { name: 'Pokémon details' });
await modal.getByLabel('Notes:', { exact: true }).waitFor();
assert.equal(
await modal.getByLabel('Notes:', { exact: true }).inputValue(),
notes.catchRecord.personalNotes
);
const image = modal.locator('img').first();
await image.waitFor();
await page.waitForFunction(
() => document.querySelector('[role="dialog"] img')?.naturalWidth > 0
);
assert.equal(await image.evaluate((node) => node.naturalWidth), 512);
assert.ok(!(await image.getAttribute('src')).includes('sprites-grid'));
await modal.getByRole('button', { name: 'Close', exact: true }).click();
assert.equal(await first.evaluate((node) => document.activeElement === node), true);
// Reopening uses cached details; bulk edits must retain the unloaded personal notes.
const detailCalls = () =>
requests.filter((path) => path.endsWith(`/entries/${entryId}`)).length;
const before = detailCalls();
await first.click();
await modal.getByLabel('Notes:', { exact: true }).waitFor();
assert.equal(detailCalls(), before);
await modal.getByRole('button', { name: 'Close', exact: true }).click();
await page.getByRole('button', { name: 'Open bulk actions menu' }).first().click();
await page.getByRole('button', { name: 'Mark box as In HOME', exact: true }).click();
await page.waitForResponse(
(r) =>
r.url().endsWith(`/pokedexes/${dex.id}/catch-records`) && r.request().method() === 'POST'
);
const after = await readJson(`/api/pokedexes/${dex.id}/entries/${entryId}`);
assert.equal(after.catchRecord.personalNotes, notes.catchRecord.personalNotes);
assert.equal(after.catchRecord.inHome, true);
// Focus navigation must reach entries that were not initially mounted.
await page.locator('[data-entry-index="29"]').focus();
for (let index = 0; index < 22; index++) await page.keyboard.press('ArrowDown');
assert.equal(
await page.evaluate(() => document.activeElement?.getAttribute('data-entry-index')),
'161'
);
await page.getByLabel('Render all boxes').check();
const grid = await readJson(`/api/pokedexes/${dex.id}/grid`);
assert.equal(await page.locator('[data-entry-index]').count(), grid.grid.length);
await page.getByLabel('Render all boxes').uncheck();
results.push({
fixture: dex.gameScope ? 'scoped-forms' : 'national',
...stats,
documentBytes: Buffer.byteLength(html),
gridBytes: Buffer.byteLength(JSON.stringify(grid))
});
}
assert.deepEqual(errors, [], 'Browser errors');
await writeFile(`${directory}/verification.json`, JSON.stringify(results, null, 2));
console.log(JSON.stringify(results, null, 2));
} finally {
await browser.close();
}
+3
View File
@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
+1
View File
@@ -13,6 +13,7 @@ declare global {
// interface Error {}
interface Locals {
supabase: SupabaseClient;
pokedexAuthMs?: number;
safeGetSession(): Promise<{ session: Session | null; user: User | null }>;
userid: string;
buildDate: string;
-1
View File
@@ -18,7 +18,6 @@
})();
</script>
%sveltekit.head%
<link rel="stylesheet" href="%sveltekit.assets%/output.css" />
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
+24 -13
View File
@@ -1,6 +1,7 @@
import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public';
import { createServerClient } from '@supabase/ssr';
import type { Handle } from '@sveltejs/kit';
import { compressResponse } from '$lib/server/compression';
export const handle: Handle = async ({ event, resolve }) => {
event.locals.supabase = createServerClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY, {
@@ -24,24 +25,34 @@ export const handle: Handle = async ({ event, resolve }) => {
* doesn't validate the JWT, this function validates the JWT by first calling
* `getUser` and aborts early if the JWT signature is invalid.
*/
event.locals.safeGetSession = async () => {
const {
data: { user },
error
} = await event.locals.supabase.auth.getUser();
if (error) {
return { session: null, user: null };
}
// getUser is a network round trip to Supabase Auth. Layout and page loads (and API routes) all
// ask for the session, so validate once per request and share the result.
let sessionPromise: ReturnType<App.Locals['safeGetSession']> | null = null;
event.locals.safeGetSession = () => {
sessionPromise ??= (async () => {
const authStarted = performance.now();
const {
data: { user },
error
} = await event.locals.supabase.auth.getUser();
if (error) {
event.locals.pokedexAuthMs = performance.now() - authStarted;
return { session: null, user: null };
}
const {
data: { session }
} = await event.locals.supabase.auth.getSession();
return { session, user };
const {
data: { session }
} = await event.locals.supabase.auth.getSession();
event.locals.pokedexAuthMs = performance.now() - authStarted;
return { session, user };
})();
return sessionPromise;
};
return resolve(event, {
const response = await resolve(event, {
filterSerializedResponseHeaders(name) {
return name === 'content-range';
}
});
return compressResponse(event.request, response);
};
+39 -10
View File
@@ -1,7 +1,40 @@
<script lang="ts">
import { PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER } from '$env/static/public';
import { inView } from '$lib/actions/inView';
import { resolveSpriteUrl } from '$lib/utils/spriteUrl';
import { resolveSpriteUrl, resolveGridSpriteUrl } from '$lib/utils/spriteUrl';
export let variant: 'detail' | 'grid' = 'detail';
let failedPaths = new Set<string>();
let fallbackIndex = 0;
let candidates: string[] = [];
$: {
const entry = { pokedexNumber: Number(pokedexNumber), form, spriteKey };
const full = resolveSpriteUrl(
entry,
!!shiny,
PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER === 'true'
);
candidates = [
...new Set([
...(variant === 'grid' ? [resolveGridSpriteUrl(entry, !!shiny)] : []),
full,
resolveSpriteUrl(
{ ...entry, form: form?.replace(/^female[-\s]*/i, '') },
!!shiny,
PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER === 'true'
),
resolveSpriteUrl(
{ pokedexNumber: Number(pokedexNumber) },
!!shiny,
PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER === 'true'
)
])
];
fallbackIndex = candidates.findIndex((url) => !failedPaths.has(url));
}
function imageFailed() {
failedPaths = new Set([...failedPaths, imagePath!]);
}
export let pokemonName: string;
export let pokedexNumber: string | number;
@@ -21,14 +54,9 @@
form
});
}
imagePath = resolveSpriteUrl(
{ pokedexNumber: Number(pokedexNumber), form, spriteKey },
!!shiny,
PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER === 'true'
);
}
$: imagePath = candidates[fallbackIndex] ?? null;
$: if (loadingStrategy !== 'inView') {
isInView = true;
}
@@ -50,16 +78,17 @@
}}
>
{#if loadingStrategy === 'inView' && !isInView}
<span class="loading loading-spinner loading-xs"></span>
<span class="inline-block w-full h-full" aria-hidden="true"></span>
{:else}
<img
src={imagePath}
alt="sprite"
alt=""
on:error={imageFailed}
loading={loadingStrategy === 'lazy' ? 'lazy' : 'eager'}
decoding="async"
/>
{/if}
</span>
{:else}
<span class="loading loading-spinner loading-xs"></span>
<span class="inline-block w-full h-full" aria-hidden="true"></span>
{/if}
@@ -38,9 +38,9 @@
value: string | CatchInformationItem
): value is CatchInformationItem => typeof value !== 'string';
function updateCatchRecord(source: UpdateCatchSource) {
function updateCatchRecord(source: UpdateCatchSource, changes?: Partial<CatchRecord>) {
if (readOnly) return;
dispatch('updateCatch', { pokedexEntry, catchRecord, source });
dispatch('updateCatch', { pokedexEntry, catchRecord, source, changes });
}
function onCaughtChange() {
@@ -50,7 +50,10 @@
if (catchRecord.caught) {
catchRecord.haveToEvolve = false;
}
updateCatchRecord('toggle');
updateCatchRecord('toggle', {
caught: catchRecord.caught,
haveToEvolve: catchRecord.haveToEvolve
});
}
function onNeedsToEvolveChange() {
@@ -60,7 +63,10 @@
if (catchRecord.haveToEvolve) {
catchRecord.caught = false;
}
updateCatchRecord('toggle');
updateCatchRecord('toggle', {
caught: catchRecord.caught,
haveToEvolve: catchRecord.haveToEvolve
});
}
</script>
@@ -154,7 +160,7 @@
type="checkbox"
bind:checked={catchRecord.inHome}
class="checkbox checkbox-primary"
on:change={() => updateCatchRecord('toggle')}
on:change={() => updateCatchRecord('toggle', { inHome: catchRecord?.inHome })}
/>
</label>
</div>
@@ -168,7 +174,8 @@
type="checkbox"
bind:checked={catchRecord.hasGigantamaxed}
class="checkbox checkbox-primary"
on:change={() => updateCatchRecord('toggle')}
on:change={() =>
updateCatchRecord('toggle', { hasGigantamaxed: catchRecord?.hasGigantamaxed })}
/>
</label>
</div>
+39 -8
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { onMount } from 'svelte';
export let isOpen: boolean;
export let onClose: () => void;
@@ -14,24 +14,55 @@
}
}
let dialog: HTMLDivElement;
onMount(() => {
window.addEventListener('keydown', handleKeyDown);
});
onDestroy(() => {
window.removeEventListener('keydown', handleKeyDown);
const previous = document.activeElement as HTMLElement | null;
const close = dialog.querySelector<HTMLButtonElement>('.close-button');
close?.focus();
const trapFocus = (event: KeyboardEvent) => {
handleKeyDown(event);
if (event.key !== 'Tab') return;
const nodes = Array.from(
dialog.querySelectorAll<HTMLElement>(
'button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href]'
)
).filter((node) => node.getClientRects().length);
const first = nodes[0],
last = nodes.at(-1);
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last?.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first?.focus();
}
};
window.addEventListener('keydown', trapFocus);
return () => {
window.removeEventListener('keydown', trapFocus);
if (previous?.isConnected) previous.focus();
};
});
</script>
{#if isOpen}
<div class="modal modal-open" role="dialog" aria-modal="true">
<div
bind:this={dialog}
class="modal modal-open"
role="dialog"
aria-label="Pokémon details"
aria-modal="true"
>
<div class="modal-box-custom bg-primary text-primary-content">
<button class="close-button" on:click={onClose} aria-label="Close"></button>
<button data-offline-action class="close-button" on:click={onClose} aria-label="Close">
</button>
<div class="modal-content">
<slot />
</div>
</div>
<button
data-offline-action
type="button"
class="modal-backdrop bg-black/50"
aria-label="Close modal"
+399 -232
View File
@@ -1,15 +1,109 @@
<script lang="ts">
import { onMount } from 'svelte';
import type { CatchRecord } from '$lib/models/CatchRecord';
import type { CombinedData } from '$lib/models/CombinedData';
import type { SharedCatchStatus, SharedCombinedData } from '$lib/models/SharedPokedex';
import { onMount, tick } from 'svelte';
import { calculateBoxPlacement } from '$lib/utils/boxPlacement';
import PokemonSprite from '$lib/components/PokemonSprite.svelte';
import Tooltip from '$lib/components/Tooltip.svelte';
import type { SharedCombinedData } from '$lib/models/SharedPokedex';
import type { PokedexGridRow } from '$lib/models/PokedexGridRow';
import { markGridInteractive } from '$lib/utils/criticalPageWork';
export let virtualize = false;
export let retryLoad: (() => void) | null = null;
let renderAll = false;
let visibleBoxes = new Set([1, 2, 3, 4]);
let focusedBox: number | null = null;
let grid: HTMLDivElement;
const shells = new Map<number, HTMLElement>();
let viewportFrame = 0;
let mounted = false;
export let gridKey = '';
let markedKey: string | null = null;
let scrollAnchor: { number: number; top: number } | null = null;
function measureViewport() {
viewportFrame = 0;
const next = new Set<number>();
scrollAnchor = null;
for (const [number, node] of shells) {
const rect = node.getBoundingClientRect();
if (!scrollAnchor && rect.bottom > 0) scrollAnchor = { number, top: rect.top };
const overscan = rect.height + 16;
if (rect.bottom >= -overscan && rect.top <= window.innerHeight + overscan) next.add(number);
}
visibleBoxes = next;
}
function resizeViewport() {
if (scrollAnchor && window.scrollY > 0) {
const node = shells.get(scrollAnchor.number);
if (node) window.scrollBy(0, node.getBoundingClientRect().top - scrollAnchor.top);
}
scheduleViewport();
}
function trackFocus(event: FocusEvent) {
const target = event.target instanceof Element ? event.target : null;
if (!target?.closest('[data-box-number], [role="dialog"]')) focusedBox = null;
}
function scheduleViewport() {
if (!viewportFrame) viewportFrame = requestAnimationFrame(measureViewport);
}
function boxShell(node: HTMLElement, number: number) {
shells.set(number, node);
scheduleViewport();
return {
destroy() {
shells.delete(number);
}
};
}
async function focusEntry(index: number) {
if (!combinedData || index < 0 || index >= combinedData.length) return;
focusedBox = Math.floor(index / 30) + 1;
await tick();
grid.querySelector<HTMLElement>(`[data-entry-index="${index}"]`)?.focus();
}
function navigateEntry(event: KeyboardEvent, index: number) {
const offset = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -6, ArrowDown: 6 }[event.key];
if (offset !== undefined) {
event.preventDefault();
void focusEntry(index + offset);
} else if (event.key === 'Tab') {
const next = index + (event.shiftKey ? -1 : 1);
if (
next >= 0 &&
next < (combinedData?.length ?? 0) &&
!grid.querySelector(`[data-entry-index="${next}"]`)
) {
event.preventDefault();
void focusEntry(next);
}
}
}
$: if (mounted && combinedData && gridKey !== markedKey) {
markedKey = gridKey;
grid?.removeAttribute('data-grid-interactive');
void tick().then(() => {
if (virtualize) markGridInteractive();
});
}
onMount(() => {
mounted = true;
const observer = new ResizeObserver(resizeViewport);
if (grid) observer.observe(grid);
window.addEventListener('scroll', scheduleViewport, { passive: true });
window.addEventListener('resize', resizeViewport);
window.addEventListener('focusin', trackFocus);
measureViewport();
return () => {
observer.disconnect();
cancelAnimationFrame(viewportFrame);
window.removeEventListener('scroll', scheduleViewport);
window.removeEventListener('resize', resizeViewport);
window.removeEventListener('focusin', trackFocus);
};
});
export let showShiny = false;
type DisplayData = CombinedData | SharedCombinedData;
type DisplayStatus = CatchRecord | SharedCatchStatus | null;
type DisplayData = PokedexGridRow | SharedCombinedData;
type DisplayStatus = DisplayData['catchRecord'];
export let combinedData: DisplayData[] | null;
export let readOnly = false;
@@ -119,21 +213,21 @@
const BOX_VIEW_LAYOUT_STORAGE_KEY = 'livingdex:boxViewLayout:v1';
type BoxViewLayout = 'comfortable' | 'compact' | 'ultra';
let boxViewLayout: BoxViewLayout = 'comfortable';
onMount(() => {
try {
const stored = localStorage.getItem(BOX_VIEW_LAYOUT_STORAGE_KEY);
if (stored === 'comfortable' || stored === 'compact' || stored === 'ultra') {
boxViewLayout = stored;
}
} catch {
// ignore (privacy mode / disabled storage)
}
});
export let initialLayout: BoxViewLayout = 'comfortable';
let boxViewLayout: BoxViewLayout = initialLayout;
function persistBoxViewLayout(next: BoxViewLayout) {
const anchor = [...shells.entries()].find(
([, node]) => node.getBoundingClientRect().bottom > 0
);
const top = anchor?.[1].getBoundingClientRect().top;
boxViewLayout = next;
document.cookie = `boxViewLayout=${next};path=/;max-age=31536000;SameSite=Lax`;
void tick().then(() => {
if (anchor && top !== undefined && window.scrollY > 0)
window.scrollBy(0, anchor[1].getBoundingClientRect().top - top);
measureViewport();
});
try {
localStorage.setItem(BOX_VIEW_LAYOUT_STORAGE_KEY, next);
} catch {
@@ -202,7 +296,7 @@
</script>
<main class="flex-1 p-4 w-full">
<div class="max-w-fit mx-auto">
<div class="max-w-[1440px] w-full mx-auto">
{#if combinedData && combinedData.length > 0}
<div class="container mx-auto">
<div class="card bg-base-100 shadow mb-4">
@@ -212,6 +306,7 @@
<span class="label-text font-semibold">Box view layout</span>
</label>
<select
data-offline-action
id="box-view-layout"
class="select select-bordered select-sm"
bind:value={boxViewLayout}
@@ -222,6 +317,16 @@
<option value="compact">Compact (3 boxes/row)</option>
<option value="ultra">Ultra (4 boxes/row)</option>
</select>
{#if virtualize}
<label class="label cursor-pointer gap-2"
><input
data-offline-action
type="checkbox"
class="checkbox checkbox-sm"
bind:checked={renderAll}
/>Render all boxes</label
>
{/if}
<div class="flex flex-wrap items-center gap-2 text-sm">
<span class="font-semibold">Legend:</span>
@@ -288,6 +393,7 @@
<span class="font-semibold">Filters:</span>
<label class="label cursor-pointer gap-2 p-0">
<input
data-offline-action
type="checkbox"
class="checkbox checkbox-sm"
bind:checked={filterNotCaught}
@@ -296,6 +402,7 @@
</label>
<label class="label cursor-pointer gap-2 p-0">
<input
data-offline-action
type="checkbox"
class="checkbox checkbox-sm"
bind:checked={filterNeedsToEvolve}
@@ -304,6 +411,7 @@
</label>
<label class="label cursor-pointer gap-2 p-0">
<input
data-offline-action
type="checkbox"
class="checkbox checkbox-sm"
bind:checked={filterInHome}
@@ -313,6 +421,7 @@
</label>
<label class="label cursor-pointer gap-2 p-0">
<input
data-offline-action
type="checkbox"
class="checkbox checkbox-sm"
bind:checked={filterNotInHome}
@@ -350,233 +459,252 @@
</div>
<div
bind:this={grid}
class="boxes-grid"
style="--boxes-per-row: {boxesPerRow}; --cell-padding: {cellPaddingRem}rem; --sprite-size: {spriteSizePx}px;"
>
{#each boxNumbers as boxNumber}
{#each boxNumbers as boxNumber (boxNumber)}
{@const bulkMenuId = `box-${boxNumber}-bulk-menu`}
<div class="mb-8">
<div class="flex flex-wrap items-center justify-between gap-3 mb-4 relative z-20">
<h2 class="text-xl font-bold">Box {boxNumber}</h2>
{#if !readOnly}<div class="relative">
<button
type="button"
class="btn btn-sm btn-outline relative z-[210]"
aria-label="Open bulk actions menu"
aria-haspopup="menu"
aria-controls={bulkMenuId}
aria-expanded={openBulkMenuForBox === boxNumber}
on:click={(event) => {
event.stopPropagation();
openBulkMenuForBox = openBulkMenuForBox === boxNumber ? null : boxNumber;
}}
on:keydown={(event) => {
if (event.key === 'Escape') openBulkMenuForBox = null;
}}
>
</button>
<div class="box-shell" use:boxShell={boxNumber} data-box-number={boxNumber}>
{#if !virtualize || renderAll || visibleBoxes.has(boxNumber) || focusedBox === boxNumber}
<div class="box-content">
<div
class="box-heading flex items-center justify-between gap-3 mb-4 relative z-20"
>
<h2 class="text-xl font-bold">Box {boxNumber}</h2>
{#if !readOnly}<div class="relative">
<button
type="button"
class="btn btn-sm btn-outline relative z-[210]"
aria-label="Open bulk actions menu"
aria-haspopup="menu"
aria-controls={bulkMenuId}
aria-expanded={openBulkMenuForBox === boxNumber}
on:click={(event) => {
event.stopPropagation();
openBulkMenuForBox =
openBulkMenuForBox === boxNumber ? null : boxNumber;
}}
on:keydown={(event) => {
if (event.key === 'Escape') openBulkMenuForBox = null;
}}
>
</button>
{#if openBulkMenuForBox === boxNumber}
<ul
id={bulkMenuId}
class="menu bg-base-100 rounded-box absolute right-0 mt-2 z-[220] w-56 p-2 shadow border border-base-300"
>
<li>
<button
type="button"
on:click|stopPropagation={() => {
markBoxAsNotCaught(boxNumber);
openBulkMenuForBox = null;
}}
{#if openBulkMenuForBox === boxNumber}
<ul
id={bulkMenuId}
class="menu bg-base-100 rounded-box absolute right-0 mt-2 z-[220] w-56 p-2 shadow border border-base-300"
>
Mark box as Not caught
</button>
</li>
<li>
<button
type="button"
on:click|stopPropagation={() => {
markBoxAsCaught(boxNumber);
openBulkMenuForBox = null;
}}
>
Mark box as Caught
</button>
</li>
<li>
<button
type="button"
on:click|stopPropagation={() => {
markBoxAsNeedsToEvolve(boxNumber);
openBulkMenuForBox = null;
}}
>
Mark box as Needs to evolve
</button>
</li>
<li>
<button
type="button"
on:click|stopPropagation={() => {
markBoxAsInHome(boxNumber);
openBulkMenuForBox = null;
}}
>
Mark box as In HOME
</button>
</li>
<li>
<button
type="button"
on:click|stopPropagation={() => {
markBoxAsNotInHome(boxNumber);
openBulkMenuForBox = null;
}}
>
Mark box as Not in HOME
</button>
</li>
</ul>
{/if}
</div>{/if}
</div>
<div class="grid grid-cols-6">
{#each BOX_POSITIONS as positionInBox}
{@const globalIndex = (boxNumber - 1) * POKEMON_PER_BOX + positionInBox}
{@const placement = calculateBoxPlacement(globalIndex)}
{@const entry = combinedData?.[globalIndex]}
{@const pokedexEntry = entry?.pokedexEntry}
{@const catchRecord = entry?.catchRecord ?? null}
{@const isFilteredOut =
!!entry && filtersActive && !!filtersKey && !matchesFilters(catchRecord)}
{#if entry && pokedexEntry}
<button
type="button"
class="pokemon-box {cellStatusClasses(catchRecord)} {isFilteredOut
? 'pokemon-box--filtered-out'
: 'hover:scale-105 hover:shadow-lg hover:z-50'} transition-all cursor-pointer relative"
style="grid-column-start: {placement.column}; grid-row-start: {placement.row};
<li>
<button
type="button"
on:click|stopPropagation={() => {
markBoxAsNotCaught(boxNumber);
openBulkMenuForBox = null;
}}
>
Mark box as Not caught
</button>
</li>
<li>
<button
type="button"
on:click|stopPropagation={() => {
markBoxAsCaught(boxNumber);
openBulkMenuForBox = null;
}}
>
Mark box as Caught
</button>
</li>
<li>
<button
type="button"
on:click|stopPropagation={() => {
markBoxAsNeedsToEvolve(boxNumber);
openBulkMenuForBox = null;
}}
>
Mark box as Needs to evolve
</button>
</li>
<li>
<button
type="button"
on:click|stopPropagation={() => {
markBoxAsInHome(boxNumber);
openBulkMenuForBox = null;
}}
>
Mark box as In HOME
</button>
</li>
<li>
<button
type="button"
on:click|stopPropagation={() => {
markBoxAsNotInHome(boxNumber);
openBulkMenuForBox = null;
}}
>
Mark box as Not in HOME
</button>
</li>
</ul>
{/if}
</div>{/if}
</div>
<div class="grid grid-cols-6">
{#each BOX_POSITIONS as positionInBox}
{@const globalIndex = (boxNumber - 1) * POKEMON_PER_BOX + positionInBox}
{@const placement = calculateBoxPlacement(globalIndex)}
{@const entry = combinedData?.[globalIndex]}
{@const pokedexEntry = entry?.pokedexEntry}
{@const catchRecord = entry?.catchRecord ?? null}
{@const isFilteredOut =
!!entry && filtersActive && !!filtersKey && !matchesFilters(catchRecord)}
{#if entry && pokedexEntry}
<button
type="button"
class="pokemon-box {cellStatusClasses(catchRecord)} {isFilteredOut
? 'pokemon-box--filtered-out'
: 'hover:scale-105 hover:shadow-lg hover:z-50'} transition-all cursor-pointer relative"
style="grid-column-start: {placement.column}; grid-row-start: {placement.row};
{cellBackgroundColourStyle(globalIndex, catchRecord)}"
aria-disabled={isFilteredOut}
on:click={() => {
if (!isFilteredOut) onPokemonClick({ pokedexEntry, catchRecord });
}}
aria-label="View details for {pokedexEntry.pokemon}. Status: {statusLabel(
catchRecord
)}"
>
<Tooltip>
<div slot="hover-target" class="w-full h-full">
{#if catchRecord?.caught}
<span
class="status-badge status-badge--caught absolute left-0.5 status-badge-top z-10"
title="Caught"
>
<svg
class="status-icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="3"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M5 13l4 4L19 7" />
</svg>
<span class="sr-only">Caught</span>
</span>
{:else if catchRecord?.haveToEvolve}
<span
class="status-badge status-badge--evolve absolute left-0.5 status-badge-top z-10"
title="Caught but needs to evolve"
>
<svg
class="status-icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="3"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M12 19V5" />
<path d="M5 12l7-7 7 7" />
</svg>
<span class="sr-only">Caught but needs to evolve</span>
</span>
{/if}
{#if catchRecord?.inHome}
<span
class="status-badge status-badge--home absolute right-0.5 status-badge-top z-10"
title="In Pokémon HOME"
>
<svg
class="status-icon"
viewBox="0 0 24 24"
fill="currentColor"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path
d="M12 3 3 10.5V21a1 1 0 0 0 1 1h5v-6h6v6h5a1 1 0 0 0 1-1V10.5L12 3Z"
data-offline-action
data-entry-index={globalIndex}
data-entry-id={pokedexEntry._id}
on:focus={() => (focusedBox = boxNumber)}
on:keydown={(event) => navigateEntry(event, globalIndex)}
aria-disabled={isFilteredOut}
on:click={() => {
if (!isFilteredOut) onPokemonClick(entry);
}}
aria-label="View details for {pokedexEntry.pokemon}{pokedexEntry.form
? ` (${pokedexEntry.form})`
: ''}. Status: {statusLabel(catchRecord)}"
>
<span class="cell-tooltip">
<span class="block w-full h-full">
{#if catchRecord?.caught}
<span
class="status-badge status-badge--caught absolute left-0.5 status-badge-top z-10"
title="Caught"
>
<svg
class="status-icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="3"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M5 13l4 4L19 7" />
</svg>
<span class="sr-only">Caught</span>
</span>
{:else if catchRecord?.haveToEvolve}
<span
class="status-badge status-badge--evolve absolute left-0.5 status-badge-top z-10"
title="Caught but needs to evolve"
>
<svg
class="status-icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="3"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M12 19V5" />
<path d="M5 12l7-7 7 7" />
</svg>
<span class="sr-only">Caught but needs to evolve</span>
</span>
{/if}
{#if catchRecord?.inHome}
<span
class="status-badge status-badge--home absolute right-0.5 status-badge-top z-10"
title="In Pokémon HOME"
>
<svg
class="status-icon"
viewBox="0 0 24 24"
fill="currentColor"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path
d="M12 3 3 10.5V21a1 1 0 0 0 1 1h5v-6h6v6h5a1 1 0 0 0 1-1V10.5L12 3Z"
/>
</svg>
<span class="sr-only">In HOME</span>
</span>
{/if}
<div class="pokemon-box-inner">
<PokemonSprite
pokemonName={pokedexEntry.pokemon}
pokedexNumber={pokedexEntry.pokedexNumber}
form={pokedexEntry.form}
spriteKey={pokedexEntry.spriteKey}
shiny={showShiny}
variant="grid"
/>
</svg>
<span class="sr-only">In HOME</span>
</div>
</span>
{/if}
<div class="pokemon-box-inner">
<PokemonSprite
pokemonName={pokedexEntry.pokemon}
pokedexNumber={pokedexEntry.pokedexNumber}
form={pokedexEntry.form}
spriteKey={pokedexEntry.spriteKey}
shiny={showShiny}
/>
</div>
</div>
<div slot="tooltip">
<div class="font-bold">
{pokedexEntry.pokemon}
{pokedexEntry.form ? `(${pokedexEntry.form})` : ''}
</div>
<div>{pokedexEntry.pokedexNumber.toString().padStart(3, '0')}</div>
<div>
Caught: {catchRecord?.caught ? 'Yes' : 'No'} <br />
Caught but needs to Evolve: {catchRecord?.haveToEvolve ? 'Yes' : 'No'}
<br />
In Home: {catchRecord?.inHome ? 'Yes' : 'No'}
</div>
</div>
</Tooltip>
</button>
{:else}
<button
type="button"
class="pokemon-box pokemon-box--empty"
disabled
style="grid-column-start: {placement.column}; grid-row-start: {placement.row};
<span class="cell-tooltip-text" role="tooltip">
<div class="font-bold">
{pokedexEntry.pokemon}
{pokedexEntry.form ? `(${pokedexEntry.form})` : ''}
</div>
<div>{pokedexEntry.pokedexNumber.toString().padStart(3, '0')}</div>
<div>
Caught: {catchRecord?.caught ? 'Yes' : 'No'} <br />
Caught but needs to Evolve: {catchRecord?.haveToEvolve
? 'Yes'
: 'No'}
<br />
In Home: {catchRecord?.inHome ? 'Yes' : 'No'}
</div>
</span>
</span>
</button>
{:else}
<button
type="button"
class="pokemon-box pokemon-box--empty"
disabled
style="grid-column-start: {placement.column}; grid-row-start: {placement.row};
{cellBackgroundColourStyle(globalIndex, null)}"
aria-label="Empty box slot"
>
<div class="pokemon-box-inner" aria-hidden="true">
<span class="sprite-placeholder" />
</div>
</button>
{/if}
{/each}
</div>
aria-label="Empty box slot"
>
<div class="pokemon-box-inner" aria-hidden="true">
<span class="sprite-placeholder" />
</div>
</button>
{/if}
{/each}
</div>
</div>
{/if}
</div>
{/each}
</div>
</div>
{:else if failedToLoad}
{#if creatingRecords && totalRecordsCreated > 0}
{#if retryLoad}
<p role="alert">Unable to load Pokédex.</p>
<button class="btn" on:click={retryLoad}>Retry loading Pokédex</button>
{:else if creatingRecords && totalRecordsCreated > 0}
<p>Processed {totalRecordsCreated} Pokédex entries so far...</p>
<p>Please be patient, this may take some time.</p>
{:else if creatingRecords}
@@ -592,6 +720,8 @@
<button class="btn" on:click={createCatchRecords}>Create Pokédex data</button>
{/if}
{/if}
{:else if combinedData}
<p>No entries match this Pokédex.</p>
{:else}
<div class="min-w-max mx-auto">
<h1>Loading Pokédex</h1>
@@ -602,6 +732,43 @@
</main>
<style>
.box-shell {
position: relative;
min-width: 0;
}
.box-shell::before {
content: '';
display: block;
padding-top: calc(83.333333% + 80px);
}
.box-content {
position: absolute;
inset: 0 0 32px;
}
.box-heading {
height: 32px;
}
.cell-tooltip {
display: block;
width: 100%;
height: 100%;
}
.cell-tooltip-text {
display: none;
position: absolute;
z-index: 100;
pointer-events: none;
background: #1f2937;
color: white;
border-radius: 4px;
padding: 8px;
width: 13rem;
}
.pokemon-box:hover .cell-tooltip-text,
.pokemon-box:focus-visible .cell-tooltip-text {
display: block;
}
/*
Theme-aware backgrounds for non-caught box slots.
- Light mode (`pokeball`) keeps the original exact colors.
@@ -15,6 +15,8 @@ export interface PokedexExportIntegration {
metadata: Record<string, unknown> | null;
lastExportedAt: string | null;
lastError: string | null;
/** Set by a database trigger on every write, so it doubles as the row's version. */
updatedAt: string | null;
}
export interface PokedexExportIntegrationDB {
@@ -32,4 +34,5 @@ export interface PokedexExportIntegrationDB {
metadata: Record<string, unknown> | null;
lastExportedAt: string | null;
lastError: string | null;
updatedAt: string | null;
}
+58
View File
@@ -0,0 +1,58 @@
import type { PokedexEntry } from './PokedexEntry';
import type { CatchRecord } from './CatchRecord';
/** Complete ordering/status data, without detail text or repeated ownership fields. */
export type PokedexGridRow = {
pokedexEntry: Pick<
PokedexEntry,
'_id' | 'pokemon' | 'pokedexNumber' | 'form' | 'spriteKey' | 'canGigantamax'
>;
catchRecord: Pick<
CatchRecord,
'_id' | 'caught' | 'haveToEvolve' | 'inHome' | 'hasGigantamaxed'
> | null;
};
export type CatchRecordPatch = Partial<CatchRecord> &
Pick<CatchRecord, 'userId' | 'pokedexId' | 'pokemonId'>;
/** Version 1 transport rows: avoid repeating field names 1,000+ times. IDs remain available. */
export type PackedGridRow = [
entryId: string,
number: number,
name: string,
form: string,
spriteKey: string,
canGigantamax: boolean,
catchId: string | null,
status: number
];
export function packGrid(rows: PokedexGridRow[]): PackedGridRow[] {
return rows.map(({ pokedexEntry: e, catchRecord: c }) => [
e._id,
e.pokedexNumber,
e.pokemon,
e.form,
e.spriteKey,
e.canGigantamax,
c?._id ?? null,
(c?.caught ? 1 : 0) |
(c?.haveToEvolve ? 2 : 0) |
(c?.inHome ? 4 : 0) |
(c?.hasGigantamaxed ? 8 : 0)
]);
}
export function unpackGrid(rows: PackedGridRow[]): PokedexGridRow[] {
return rows.map(([id, number, name, form, spriteKey, canGigantamax, catchId, status]) => ({
pokedexEntry: { _id: id, pokedexNumber: number, pokemon: name, form, spriteKey, canGigantamax },
catchRecord:
catchId === null
? null
: {
_id: catchId,
caught: !!(status & 1),
haveToEvolve: !!(status & 2),
inHome: !!(status & 4),
hasGigantamaxed: !!(status & 8)
}
}));
}
+20 -12
View File
@@ -90,19 +90,27 @@ class CatchRecordRepository {
return mapped;
});
const { data: result, error } = await this.supabase
.from('catch_records')
.upsert(dbRows, {
onConflict: '"userId","pokedexId","pokemonId"'
})
.select();
if (error) {
console.error('Supabase error bulk upserting catch records:', error);
throw new Error(`Failed to bulk upsert catch records: ${error.message}`);
const groups = new Map<string, Partial<CatchRecordDB>[]>();
for (const row of dbRows) {
const key = Object.keys(row).sort().join(',');
const group = groups.get(key) ?? [];
group.push(row);
groups.set(key, group);
}
return (result ?? []).map((row) => this.transformCatchRecord(row));
const saved: CatchRecord[] = [];
for (const group of groups.values()) {
const { data, error } = await this.supabase
.from('catch_records')
.upsert(group, {
onConflict: '"userId","pokedexId","pokemonId"',
defaultToNull: false
})
.select();
if (error) throw new Error(`Failed to bulk upsert catch records: ${error.message}`);
saved.push(...(data ?? []).map((row) => this.transformCatchRecord(row)));
}
const byPokemon = new Map(saved.map((row) => [row.pokemonId, row]));
return records.map((row) => byPokemon.get(row.pokemonId)!);
}
async findById(id: string): Promise<CatchRecord | null> {
+101 -25
View File
@@ -1,3 +1,4 @@
import type { PokedexGridRow } from '$lib/models/PokedexGridRow';
import { type PokedexEntry, type PokedexEntryDB } from '$lib/models/PokedexEntry';
import { type CatchRecord, type CatchRecordDB } from '$lib/models/CatchRecord';
import { type CombinedData } from '$lib/models/CombinedData';
@@ -20,9 +21,17 @@ class CombinedDataRepository {
constructor(
private supabase: SupabaseClient,
private userId: string | null,
private pokedexId: string | null
private pokedexId: string | null,
private compact = false
) {}
private scopedEntries = new Map<string, Promise<PokedexEntryDB[]>>();
private get entryColumns() {
return this.compact
? 'id,pokedexNumber,pokemon,form,spriteKey,canGigantamax,unownSortOrder,formSortBucket,formSortRegionOrder,formSortRegionalSub,formSortLabel'
: '*';
}
// Transform Supabase data to match frontend expectations (minimal transformation)
private transformPokedexEntry(entry: PokedexEntryDB): PokedexEntry {
return {
@@ -57,7 +66,7 @@ class CombinedDataRepository {
}
private buildEntriesQuery(enableForms: boolean, region: string, game: string) {
let query = this.supabase.from('pokedex_entries').select('*');
let query = this.supabase.from('pokedex_entries').select(this.entryColumns);
if (!enableForms) {
// Filter to base forms only. Gendered species (form='male') and Unown ('A') are
@@ -86,7 +95,10 @@ class CombinedDataRepository {
}
private buildDexEntriesQuery(dexScopes: string[], enableForms: boolean, region: string) {
let query = this.supabase.from('game_pokedex_entry_details').select('*').in('dexId', dexScopes);
let query = this.supabase
.from('game_pokedex_entry_details')
.select(this.compact ? `${this.entryColumns},dexNumber,dexSortOrder` : '*')
.in('dexId', dexScopes);
if (!enableForms) {
// Filter to base forms only. Gendered species (form='male') and Unown ('A') are
@@ -128,7 +140,10 @@ class CombinedDataRepository {
for (;;) {
const end = start + maxRows - 1;
let query = this.supabase.from('pokedex_entries').select('*').not('form', 'is', null);
let query = this.supabase
.from('pokedex_entries')
.select(this.entryColumns)
.not('form', 'is', null);
if (game) {
query = query.contains('gamesToCatchIn', [game]);
@@ -140,13 +155,12 @@ class CombinedDataRepository {
const { data, error } = await query.order('id', { ascending: true }).range(start, end);
if (error) {
console.error('Error fetching forms for game:', error);
return [];
throw new Error('Unable to load form entries');
}
if (!data || data.length === 0) break;
allForms.push(...(data as PokedexEntryDB[]).filter((e) => !excludeIds.has(e.id)));
allForms.push(...(data as unknown as PokedexEntryDB[]).filter((e) => !excludeIds.has(e.id)));
if (data.length < maxRows) break;
start = end + 1;
@@ -155,7 +169,17 @@ class CombinedDataRepository {
return allForms;
}
private async fetchAllDexEntries(
private fetchAllDexEntries(dexScopes: string[], enableForms: boolean, region: string, game = '') {
const key = JSON.stringify([dexScopes, enableForms, region, game]);
let entries = this.scopedEntries.get(key);
if (!entries) {
entries = this.readAllDexEntries(dexScopes, enableForms, region, game);
this.scopedEntries.set(key, entries);
}
return entries;
}
private async readAllDexEntries(
dexScopes: string[],
enableForms: boolean,
region: string,
@@ -175,15 +199,14 @@ class CombinedDataRepository {
);
if (error) {
console.error('Error finding dex-scoped combined data:', error);
return [];
throw new Error('Unable to load dex entries');
}
if (!data || data.length === 0) {
break;
}
entries.push(...(data as RawDexEntry[]));
entries.push(...(data as unknown as RawDexEntry[]));
if (data.length < maxRows) {
break;
@@ -283,15 +306,14 @@ class CombinedDataRepository {
);
if (error) {
console.error('Error finding paginated combined data:', error);
return [];
throw new Error('Unable to load dex entries');
}
if (!data || data.length === 0) {
break;
}
entries.push(...data);
entries.push(...(data as unknown as PokedexEntryDB[]));
if (data.length < end - start + 1) {
break;
@@ -320,15 +342,14 @@ class CombinedDataRepository {
);
if (error) {
console.error('Error finding combined data:', error);
return [];
throw new Error('Unable to load dex entries');
}
if (!data || data.length === 0) {
break;
}
entries.push(...data);
entries.push(...(data as unknown as PokedexEntryDB[]));
if (data.length < maxRows) {
break;
@@ -351,24 +372,79 @@ class CombinedDataRepository {
const chunk = entryIds.slice(i, i + chunkSize);
const { data, error } = await this.supabase
.from('catch_records')
.select('*')
.select(this.compact ? 'id,pokemonId,caught,haveToEvolve,inHome,hasGigantamaxed' : '*')
.eq('userId', userId)
.eq('pokedexId', this.pokedexId)
.in('pokemonId', chunk);
if (error) {
console.error('Error loading catch records:', error);
continue;
throw new Error('Unable to load catch records');
}
if (data) {
records.push(...data);
records.push(...(data as unknown as CatchRecordDB[]));
}
}
return records;
}
async findGridEntries(enableForms: boolean, game: string, dexScopes: string[]) {
if (!this.compact) throw new Error('Grid reads require a compact repository');
const entries = dexScopes.length
? this.dedupeEntries(await this.fetchAllDexEntries(dexScopes, enableForms, '', game))
: await this.fetchAllEntries(enableForms, '', game);
return entries;
}
async joinGridCatches(entries: PokedexEntryDB[]): Promise<PokedexGridRow[]> {
const catches = new Map(
(
await this.fetchCatchRecords(
entries.map((e) => e.id),
this.userId!
)
).map((r) => [r.pokemonId, r])
);
return entries.map((e) => {
const c = catches.get(e.id);
return {
pokedexEntry: {
_id: String(e.id),
pokemon: e.pokemon,
pokedexNumber: e.pokedexNumber,
form: e.form || '',
spriteKey: e.spriteKey || '',
canGigantamax: e.canGigantamax
},
catchRecord: c
? {
_id: c.id,
caught: c.caught,
haveToEvolve: c.haveToEvolve,
inHome: c.inHome,
hasGigantamaxed: c.hasGigantamaxed
}
: null
};
});
}
async findEntryDetail(entryId: number): Promise<CombinedData | null> {
const { data, error } = await this.supabase
.from('pokedex_entries')
.select('*')
.eq('id', entryId)
.maybeSingle();
if (error) throw new Error('Unable to load entry details');
if (!data) return null;
const catches = await this.fetchCatchRecords([entryId], this.userId!);
return {
pokedexEntry: this.transformPokedexEntry(data),
catchRecord: catches[0] ? this.transformCatchRecord(catches[0]) : null
};
}
async findAllCombinedData(
userId: string,
enableForms: boolean = true,
@@ -392,9 +468,9 @@ class CombinedDataRepository {
catchRecords = await this.fetchCatchRecords(entryIds, userId);
}
// Combine the data exactly like master branch
const catchesById = new Map(catchRecords.map((record) => [record.pokemonId, record]));
const combinedData = entries.map((entry) => {
const userCatchRecord = catchRecords.find((record) => record.pokemonId === entry.id) || null;
const userCatchRecord = catchesById.get(entry.id) || null;
const transformedEntry = this.transformPokedexEntry(entry);
const transformedCatchRecord = userCatchRecord
@@ -440,9 +516,9 @@ class CombinedDataRepository {
catchRecords = await this.fetchCatchRecords(entryIds, userId);
}
// Combine the data exactly like master branch
const catchesById = new Map(catchRecords.map((record) => [record.pokemonId, record]));
const combinedData = entries.map((entry) => {
const userCatchRecord = catchRecords.find((record) => record.pokemonId === entry.id) || null;
const userCatchRecord = catchesById.get(entry.id) || null;
const transformedEntry = this.transformPokedexEntry(entry);
const transformedCatchRecord = userCatchRecord
@@ -30,7 +30,8 @@ class PokedexExportIntegrationRepository {
accessTokenExpiresAt: db.accessTokenExpiresAt,
metadata: db.metadata,
lastExportedAt: db.lastExportedAt,
lastError: db.lastError
lastError: db.lastError,
updatedAt: db.updatedAt ?? null
};
}
@@ -136,28 +137,38 @@ class PokedexExportIntegrationRepository {
}
}
/**
* Returns whether a row was updated. With `ifUpdatedAt`, the write only applies if the row is
* unchanged since it was read, so a stale export can't overwrite credentials a reconnect saved.
*/
async updateExportStatus(
id: string,
patch: {
enabled?: boolean;
lastExportedAt?: string | null;
lastError?: string | null;
metadata?: Record<string, unknown> | null;
folderId?: string | null;
path?: string | null;
}
): Promise<void> {
const query = this.supabase
},
ifUpdatedAt?: string
): Promise<boolean> {
let query = this.supabase
.from('pokedex_export_integrations')
.update(patch)
.eq('id', id)
.eq('userId', this.userId);
const { error } = this.pokedexId
? await query.eq('pokedexId', this.pokedexId)
: await query.is('pokedexId', null);
if (ifUpdatedAt) query = query.eq('updatedAt', ifUpdatedAt);
const scoped = this.pokedexId
? query.eq('pokedexId', this.pokedexId)
: query.is('pokedexId', null);
const { data, error } = await scoped.select('id');
if (error) {
console.error('Failed to update export integration status:', error);
return false;
}
return (data?.length ?? 0) > 0;
}
}
+5 -3
View File
@@ -55,14 +55,16 @@ class PokedexRepository {
async findById(id: string): Promise<Pokedex | null> {
const { data, error } = await this.supabase
.from('pokedexes')
.select('*')
.select('*, pokedex_dex_scopes(dexId)')
.eq('id', id)
.eq('userId', this.userId)
.single();
if (error || !data) return null;
const dexScopesMap = await this.fetchDexScopesMap([data.id]);
return this.transform(data, dexScopesMap.get(data.id) || []);
return this.transform(
data,
(data.pokedex_dex_scopes ?? []).map((scope: { dexId: string }) => scope.dexId)
);
}
async findAll(): Promise<Pokedex[]> {
+4
View File
@@ -0,0 +1,4 @@
/** Cloudflare performs transport compression; preserve the streaming Response body. */
export function compressResponse(_request: Request, response: Response): Response {
return response;
}
+73
View File
@@ -0,0 +1,73 @@
import { Readable } from 'node:stream';
import type { ReadableStream as NodeReadableStream } from 'node:stream/web';
import { constants, createBrotliCompress, createGzip } from 'node:zlib';
export type Encoding = 'br' | 'gzip';
// Text responses the app renders or returns from API routes. Images, fonts and other binary
// content is already compressed, so re-compressing it only costs CPU.
const COMPRESSIBLE = /^(text\/|application\/(json|javascript|xml|manifest\+json)|image\/svg\+xml)/i;
/** Picks the best encoding the client accepts, preferring brotli. Honours `q=0` refusals. */
export function pickEncoding(acceptEncoding: string | null): Encoding | null {
if (!acceptEncoding) return null;
const accepted = new Map<string, number>();
for (const part of acceptEncoding.split(',')) {
const [name, ...params] = part.trim().toLowerCase().split(';');
const q = params.map((p) => p.trim()).find((p) => p.startsWith('q='));
accepted.set(name, q ? Number(q.slice(2)) : 1);
}
const allows = (name: Encoding) => (accepted.get(name) ?? accepted.get('*') ?? 0) > 0;
if (allows('br')) return 'br';
if (allows('gzip')) return 'gzip';
return null;
}
// adapter-netlify's Lambda handler serialises text responses with `response.text()`, which would
// corrupt a compressed body. Netlify compresses function responses itself, so skip it there.
// Everywhere else (the Node build, local preview, CI) the app compresses its own responses.
const serialisesBodiesAsText = () => Boolean(process.env.AWS_LAMBDA_FUNCTION_NAME);
function shouldCompress(request: Request, response: Response): boolean {
if (serialisesBodiesAsText()) return false;
if (!response.body || request.method === 'HEAD') return false;
if (response.status < 200 || response.status === 204 || response.status === 304) return false;
if (response.headers.has('content-encoding')) return false;
return COMPRESSIBLE.test(response.headers.get('content-type') ?? '');
}
/**
* Compresses a rendered page or API response so its transfer size doesn't depend on the host.
* Every chunk is flushed as soon as it is written, so SvelteKit's streamed load data still reaches
* the browser progressively instead of waiting for the whole body.
*/
export function compressResponse(request: Request, response: Response): Response {
if (!shouldCompress(request, response)) return response;
const encoding = pickEncoding(request.headers.get('accept-encoding'));
const headers = new Headers(response.headers);
// Caches must key on the request encoding even when this response isn't compressed.
headers.append('vary', 'Accept-Encoding');
if (!encoding) return new Response(response.body, { status: response.status, headers });
const compressor =
encoding === 'br'
? createBrotliCompress({
flush: constants.BROTLI_OPERATION_FLUSH,
// Quality 11 is for build-time precompression; 5 is fast enough per request.
params: { [constants.BROTLI_PARAM_QUALITY]: 5 }
})
: createGzip({ flush: constants.Z_SYNC_FLUSH, level: 6 });
const source = Readable.fromWeb(response.body as unknown as NodeReadableStream);
source.on('error', (error) => compressor.destroy(error));
source.pipe(compressor);
headers.set('content-encoding', encoding);
headers.delete('content-length');
return new Response(Readable.toWeb(compressor) as unknown as ReadableStream, {
status: response.status,
statusText: response.statusText,
headers
});
}
+37
View File
@@ -0,0 +1,37 @@
import { env } from '$env/dynamic/private';
/** Opt-in, fixed labels only: never log IDs, query strings, cookies or entry content. */
export class PokedexPerformance {
private started = performance.now();
private durations: Record<string, number> = {};
readonly enabled = env.POKEDEX_PERFORMANCE === 'true';
async measure<T>(
stage: 'auth' | 'ownership' | 'scopes' | 'entries' | 'catches',
run: () => Promise<T>
): Promise<T> {
const start = performance.now();
try {
return await run();
} finally {
if (this.enabled) this.durations[stage] = performance.now() - start;
}
}
recordAuth(duration: number | undefined) {
if (this.enabled && duration !== undefined) this.durations.auth = duration;
}
prepare<T>(run: () => T): T {
const start = performance.now();
try {
return run();
} finally {
if (this.enabled) this.durations.prepare = performance.now() - start;
}
}
finish(): string | undefined {
if (!this.enabled) return undefined;
this.durations.total = performance.now() - this.started;
return Object.entries(this.durations)
.map(([name, duration]) => `${name};dur=${duration.toFixed(1)}`)
.join(', ');
}
}
+42
View File
@@ -0,0 +1,42 @@
import type { SupabaseClient } from '@supabase/supabase-js';
import CombinedDataRepository from '$lib/repositories/CombinedDataRepository';
import { resolveDexScopes } from '$lib/services/PokedexDexScopeService';
import type { Pokedex } from '$lib/models/Pokedex';
export type CombinedDataQuery = {
page: number;
limit: number;
enableForms: boolean;
region?: string;
game?: string;
};
/**
* Loads one page of a Pokédex's entries joined with the owner's catch records. Shared by the
* combined-data API and the Pokédex page's server load so both return exactly the same data.
* The caller must already have checked that `userId` owns `pokedex`.
*/
export async function loadCombinedDataPage(
supabase: SupabaseClient,
userId: string,
pokedex: Pokedex,
{ page, limit, enableForms, region = '', game = '' }: CombinedDataQuery
) {
// Use the pokédex's gameScope as the default filter if no manual game filter is set.
const effectiveGame = game || pokedex.gameScope || '';
const dexScopes = await resolveDexScopes(supabase, pokedex);
const repo = new CombinedDataRepository(supabase, userId, pokedex._id);
// The rows and the count are independent queries, so run them together.
const [combinedData, totalCount] = await Promise.all([
repo.findCombinedData(userId, page, limit, enableForms, region, effectiveGame, dexScopes),
repo.countCombinedData(enableForms, region, effectiveGame, dexScopes)
]);
return {
combinedData,
totalPages: Math.ceil(totalCount / limit),
currentPage: page,
totalCount
};
}
@@ -54,6 +54,17 @@ export function buildCsv(combinedData: CombinedData[]): string {
return lines.join('\r\n');
}
/** OAuth providers answer a revoked or expired refresh token with `invalid_grant`. */
export function isRevokedGrant(status: number, body: string): boolean {
if (status !== 400 && status !== 401) return false;
try {
const parsed = JSON.parse(body) as { error?: unknown } | null;
return parsed?.error === 'invalid_grant';
} catch {
return false;
}
}
export function shouldRefreshToken(expiresAt: string | null): boolean {
if (!expiresAt) return false;
const expiry = new Date(expiresAt).getTime();
+34 -6
View File
@@ -13,6 +13,7 @@ import { getEnv } from '$lib/utils/env';
import { getProviderEndpoints } from '$lib/services/providerEndpoints';
import {
buildCsv,
isRevokedGrant,
sanitizeFileName,
shouldRefreshToken
} from '$lib/services/PokedexExportFormatting';
@@ -21,6 +22,7 @@ type ExportFailure = {
integrationId: string;
provider: ExportProvider;
error: string;
reconnectRequired: boolean;
};
export type PokedexExportResult = {
@@ -29,12 +31,21 @@ export type PokedexExportResult = {
failed: ExportFailure[];
};
const RECONNECT_MESSAGES: Record<ExportProvider, string> = {
google_drive:
'Google Drive access has expired or was revoked. Reconnect Google Drive to resume backups.',
dropbox: 'Dropbox access has expired or was revoked. Reconnect Dropbox to resume backups.'
};
/** The provider rejected the stored grant, so only a fresh OAuth connection can resume exports. */
class ReconnectRequiredError extends Error {}
async function refreshGoogleToken(
integration: PokedexExportIntegration,
repo: PokedexExportIntegrationRepository
): Promise<PokedexExportIntegration> {
if (!integration.refreshToken) {
throw new Error('Missing Google refresh token');
throw new ReconnectRequiredError(RECONNECT_MESSAGES.google_drive);
}
const env = getEnv();
@@ -59,6 +70,9 @@ async function refreshGoogleToken(
if (!response.ok) {
const text = await response.text();
if (isRevokedGrant(response.status, text)) {
throw new ReconnectRequiredError(RECONNECT_MESSAGES.google_drive);
}
throw new Error(`Google token refresh failed: ${response.status} ${text}`);
}
@@ -88,7 +102,7 @@ async function refreshDropboxToken(
repo: PokedexExportIntegrationRepository
): Promise<PokedexExportIntegration> {
if (!integration.refreshToken) {
throw new Error('Missing Dropbox refresh token');
throw new ReconnectRequiredError(RECONNECT_MESSAGES.dropbox);
}
const env = getEnv();
@@ -113,6 +127,9 @@ async function refreshDropboxToken(
if (!response.ok) {
const text = await response.text();
if (isRevokedGrant(response.status, text)) {
throw new ReconnectRequiredError(RECONNECT_MESSAGES.dropbox);
}
throw new Error(`Dropbox token refresh failed: ${response.status} ${text}`);
}
@@ -418,13 +435,24 @@ export async function exportPokedexIfConfigured(
successes++;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
let reconnectRequired = false;
if (error instanceof ReconnectRequiredError) {
// A revoked grant never succeeds on retry, so pause this integration until the user
// reconnects - but only if its row is unchanged since this export read it. A reconnect
// in the meantime saved new credentials, which this stale failure must not disable.
reconnectRequired = await scopedRepo.updateExportStatus(
integration._id,
{ lastError: message, enabled: false },
integration.updatedAt ?? undefined
);
} else {
await scopedRepo.updateExportStatus(integration._id, { lastError: message });
}
failures.push({
integrationId: integration._id,
provider: integration.provider,
error: message
});
await scopedRepo.updateExportStatus(integration._id, {
lastError: message
error: message,
reconnectRequired
});
console.error('Failed to export pokedex:', integration.provider, message);
}
+38
View File
@@ -0,0 +1,38 @@
import type { SupabaseClient } from '@supabase/supabase-js';
import type { Pokedex } from '$lib/models/Pokedex';
import CombinedDataRepository from '$lib/repositories/CombinedDataRepository';
import { resolveDexScopes } from './PokedexDexScopeService';
import type { PokedexPerformance } from '$lib/server/pokedexPerformance';
export async function loadPokedexGrid(
supabase: SupabaseClient,
userId: string,
pokedex: Pokedex,
timings?: PokedexPerformance
) {
const measure = <T>(stage: 'scopes' | 'entries' | 'catches', run: () => Promise<T>) =>
timings ? timings.measure(stage, run) : run();
const scopes = await measure('scopes', () => resolveDexScopes(supabase, pokedex));
const repo = new CombinedDataRepository(supabase, userId, pokedex._id, true);
const entries = await measure('entries', () =>
repo.findGridEntries(pokedex.isFormDex, pokedex.gameScope || '', scopes)
);
return measure('catches', () => repo.joinGridCatches(entries));
}
export async function loadPokedexEntryDetail(
supabase: SupabaseClient,
userId: string,
pokedex: Pokedex,
entryId: number
) {
const scopes = await resolveDexScopes(supabase, pokedex);
const membership = new CombinedDataRepository(supabase, userId, pokedex._id, true);
const entries = await membership.findGridEntries(
pokedex.isFormDex,
pokedex.gameScope || '',
scopes
);
if (!entries.some((entry) => entry.id === entryId)) return null;
return new CombinedDataRepository(supabase, userId, pokedex._id).findEntryDetail(entryId);
}
+62
View File
@@ -0,0 +1,62 @@
import { writable } from 'svelte/store';
import type { ExportProvider } from '$lib/models/PokedexExportIntegration';
export const PROVIDER_LABELS: Record<ExportProvider, string> = {
google_drive: 'Google Drive',
dropbox: 'Dropbox'
};
/**
* Backup providers whose access has lapsed. Exports switch an integration off when the provider
* revokes its grant, so these stay paused until the user reconnects.
*/
export const backupsNeedingReconnect = writable<ExportProvider[]>([]);
type IntegrationSummary = { provider: ExportProvider; enabled: boolean };
// A response is only applied if no newer refresh has started and nothing has changed the status
// since it was requested, so a slow response can't overwrite newer or cleared state.
let refreshSequence = 0;
let mutationGeneration = 0;
export function setBackupStatus(integrations: IntegrationSummary[]): void {
mutationGeneration++;
backupsNeedingReconnect.set(integrations.filter((i) => !i.enabled).map((i) => i.provider));
}
let refreshInFlight: { generation: number; promise: Promise<void> } | null = null;
export function refreshBackupStatus(): Promise<void> {
if (refreshInFlight?.generation === mutationGeneration) return refreshInFlight.promise;
const generation = mutationGeneration;
const promise = performRefresh().finally(() => {
if (refreshInFlight?.promise === promise) refreshInFlight = null;
});
refreshInFlight = { generation, promise };
return promise;
}
async function performRefresh(): Promise<void> {
if (typeof window === 'undefined' || !navigator.onLine) return;
const sequence = ++refreshSequence;
const generation = mutationGeneration;
try {
const response = await fetch('/api/export-integrations', { credentials: 'include' });
if (!response.ok) return;
const integrations = (await response.json()) as IntegrationSummary[];
if (sequence !== refreshSequence || generation !== mutationGeneration) return;
setBackupStatus(integrations);
} catch (error) {
console.error('Unable to check backup status', error);
}
}
export function markReconnectNeeded(providers: ExportProvider[]): void {
mutationGeneration++;
backupsNeedingReconnect.update((current) => [...new Set([...current, ...providers])]);
}
export function clearBackupStatus(): void {
mutationGeneration++;
backupsNeedingReconnect.set([]);
}
+31 -2
View File
@@ -1,3 +1,4 @@
import { afterCriticalPageWork } from '$lib/utils/criticalPageWork';
import { writable } from 'svelte/store';
import { PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER } from '$env/static/public';
import type { OfflineSnapshot } from '$lib/models/OfflineSnapshot';
@@ -246,17 +247,45 @@ export function startOfflineSync(getUserId: () => string | null): () => void {
}, 1_000);
};
// Explicit requests (edits, Retry, a new sign-in) and reconnecting always fetch a new copy.
const schedule = () => scheduleSync(false);
const schedule = () => {
cancelStartup();
scheduleSync(false);
};
// Best effort: ask the browser not to evict the offline artwork cache under storage pressure.
void navigator.storage?.persist?.().catch(() => undefined);
window.addEventListener(SYNC_EVENT, schedule);
window.addEventListener('online', schedule);
scheduleSync(true);
const cancelStartup = afterCriticalPageWork(() => scheduleSync(true));
return () => {
stopped = true;
cancelStartup();
if (timer !== null) window.clearTimeout(timer);
window.removeEventListener(SYNC_EVENT, schedule);
window.removeEventListener('online', schedule);
};
}
/** Read details only from the snapshot currently claimed by this account. */
export async function readOfflineEntry(userId: string, pokedexId: string, entryId: string) {
if (typeof window === 'undefined' || !('caches' in window)) return null;
const meta = (await readOfflineMeta()) as (OfflineMeta & { dataCache?: string }) | null;
if (
meta?.userId !== userId ||
meta.format !== OFFLINE_META_FORMAT ||
!meta.dataCache?.startsWith(`${OFFLINE_CACHE_PREFIX}data-v1-${userId}-`)
)
return null;
const response = await (
await caches.open(meta.dataCache)
).match(`/__offline/snapshot/${encodeURIComponent(userId)}`);
const snapshot = (await response?.json()) as OfflineSnapshot | undefined;
const current = await readOfflineMeta();
if (current?.userId !== userId || snapshot?.userId !== userId || snapshot.version !== 1)
return null;
return (
snapshot.pokedexes
.find((dex) => dex.pokedex._id === pokedexId)
?.entries.find((row) => row.pokedexEntry._id === entryId) ?? null
);
}
+19 -8
View File
@@ -1,5 +1,5 @@
import { writable, type Readable } from 'svelte/store';
import type { CatchRecord } from '$lib/models/CatchRecord';
import type { CatchRecordPatch } from '$lib/models/PokedexGridRow';
export type CatchRecordWriteQueueStatus = {
pending: number;
@@ -10,7 +10,7 @@ export type CatchRecordWriteQueueStatus = {
};
type QueueItem = {
record: CatchRecord;
record: CatchRecordPatch;
attempts: number;
notBefore: number; // unix ms
debounceTimer: ReturnType<typeof setTimeout> | null;
@@ -31,6 +31,8 @@ export type CreateCatchRecordWriteQueueOptions = {
batchSize?: number;
/** Max number of concurrent in-flight requests. */
concurrency?: number;
/** Prevent queued work from crossing an account change. */
isCurrentUser?: () => boolean;
};
export type EnqueueCatchRecordWriteOptions = {
@@ -53,7 +55,7 @@ export type FlushOptions = {
limit?: number;
};
function keyFor(record: CatchRecord): string {
function keyFor(record: CatchRecordPatch): string {
return `${record.userId}:${record.pokedexId}:${record.pokemonId}`;
}
@@ -66,11 +68,12 @@ function backoffMs(attempts: number): number {
}
export function createCatchRecordWriteQueue(options: CreateCatchRecordWriteQueueOptions): {
enqueue: (record: CatchRecord, opts?: EnqueueCatchRecordWriteOptions) => void;
enqueue: (record: CatchRecordPatch, opts?: EnqueueCatchRecordWriteOptions) => void;
flushNow: (opts?: FlushOptions) => Promise<void>;
getStatus: Readable<CatchRecordWriteQueueStatus>;
getPendingCount: () => number;
clearError: () => void;
getPendingPatch: (pokemonId: string) => CatchRecordPatch | undefined;
} {
const { endpointUrl, fetchFn, batchSize = 100, concurrency = 1 } = options;
@@ -109,7 +112,7 @@ export function createCatchRecordWriteQueue(options: CreateCatchRecordWriteQueue
}
function scheduleFlush() {
if (scheduled) return;
if (scheduled || (typeof navigator !== 'undefined' && navigator.onLine === false)) return;
const next = computeNextWakeup();
if (next === null) return;
const delay = Math.max(0, next - Date.now());
@@ -120,6 +123,12 @@ export function createCatchRecordWriteQueue(options: CreateCatchRecordWriteQueue
}
async function flushBatch(opts?: FlushOptions): Promise<void> {
if (options.isCurrentUser && !options.isCurrentUser()) {
for (const item of items.values()) if (item.debounceTimer) clearTimeout(item.debounceTimer);
items.clear();
updateStatus({ lastError: null });
return;
}
if (typeof navigator !== 'undefined' && navigator.onLine === false) {
// Stay queued; caller can retry when online.
return;
@@ -206,7 +215,7 @@ export function createCatchRecordWriteQueue(options: CreateCatchRecordWriteQueue
scheduleFlush();
}
function enqueue(record: CatchRecord, opts?: EnqueueCatchRecordWriteOptions) {
function enqueue(record: CatchRecordPatch, opts?: EnqueueCatchRecordWriteOptions) {
const k = keyFor(record);
const now = Date.now();
const existing = items.get(k);
@@ -232,7 +241,7 @@ export function createCatchRecordWriteQueue(options: CreateCatchRecordWriteQueue
}
items.set(k, {
record,
record: { ...existing?.record, ...record },
attempts: existing?.attempts ?? 0,
notBefore,
debounceTimer,
@@ -255,6 +264,8 @@ export function createCatchRecordWriteQueue(options: CreateCatchRecordWriteQueue
flushNow,
getStatus: { subscribe: statusStore.subscribe },
getPendingCount,
clearError
clearError,
getPendingPatch: (pokemonId: string) =>
[...items.values()].find((item) => item.record.pokemonId === pokemonId)?.record
};
}
+50
View File
@@ -0,0 +1,50 @@
/** Shared scheduling boundary for optional page-start work. Explicit refreshes bypass it. */
const READY_EVENT = 'livingdex:grid-interactive';
export function markGridInteractive() {
if (typeof window === 'undefined') return;
if (!document.querySelector('[data-entry-index]')) return;
if (!document.querySelector('[data-grid-interactive]')) {
performance.mark('pokedex:first-interactive');
}
document
.querySelector('[data-entry-index]')
?.closest('.boxes-grid')
?.setAttribute('data-grid-interactive', 'true');
window.dispatchEvent(new Event(READY_EVENT));
}
export function afterCriticalPageWork(run: () => void): () => void {
let cancelled = false;
let scheduled = false;
let idle: number | undefined;
let frame: number | undefined;
const perform = () => {
if (cancelled) return;
cancel();
run();
};
const schedule = () => {
if (scheduled || cancelled) return;
scheduled = true;
frame = requestAnimationFrame(() => {
if ('requestIdleCallback' in window)
idle = window.requestIdleCallback(perform, { timeout: 5000 });
else frame = requestAnimationFrame(perform);
});
};
const fallback = window.setTimeout(perform, 5000);
const cancel = () => {
cancelled = true;
window.clearTimeout(fallback);
window.removeEventListener(READY_EVENT, schedule);
if (idle !== undefined) window.cancelIdleCallback(idle);
if (frame !== undefined) cancelAnimationFrame(frame);
};
window.addEventListener(READY_EVENT, schedule);
if (
!location.pathname.startsWith('/pokedex/') ||
document.querySelector('[data-grid-interactive]')
)
schedule();
return cancel;
}
+11
View File
@@ -46,3 +46,14 @@ export function resolveSpriteUrl(
if (/^female\b/i.test(form)) root += '/female';
return `${root}/${key}.webp`;
}
/** Grid assets use a separate immutable URL space; detail resolution is unchanged. */
export function resolveGridSpriteUrl(
entry: { pokedexNumber: number; form?: string; spriteKey?: string },
shiny: boolean
): string {
return resolveSpriteUrl(entry, shiny, true).replace(
'/sprites-small/home/',
'/sprites-grid/v1/home/'
);
}
+61 -49
View File
@@ -1,19 +1,22 @@
<script lang="ts">
import 'tailwindcss/tailwind.css';
// The only app stylesheet: Vite bundles, minifies and content-hashes it so it is cached for good.
// static/output.css is built separately for the credential-free offline.html page only.
import '../app.css';
import { afterCriticalPageWork } from '$lib/utils/criticalPageWork';
import { onDestroy, onMount } from 'svelte';
import { user } from '$lib/stores/user.js';
import { type User } from '@supabase/auth-js';
import SignIn from '$lib/components/SignIn.svelte';
import SignOut from '$lib/components/SignOut.svelte';
import ThemeToggle from '$lib/components/ThemeToggle.svelte';
import { page } from '$app/stores';
import { claimOfflineData, requestOfflineSync, startOfflineSync } from '$lib/stores/offlineSync';
import {
artworkDownloadStatus,
claimOfflineData,
downloadAllArtwork,
offlineSyncStatus,
requestOfflineSync,
startOfflineSync
} from '$lib/stores/offlineSync';
PROVIDER_LABELS,
backupsNeedingReconnect,
clearBackupStatus,
refreshBackupStatus
} from '$lib/stores/backupStatus';
import { pwaInfo } from 'virtual:pwa-info';
import { pwaAssetsHead } from 'virtual:pwa-assets/head';
@@ -25,18 +28,21 @@
let { supabase } = data;
$: ({ supabase } = data);
let localUser = null as User | null;
let localUser: User | null = data.user ?? null;
let userStoreReady = false;
const unsubscribe = user.subscribe((value) => {
localUser = value;
if (userStoreReady) localUser = value;
});
onDestroy(unsubscribe);
let authSubscription: { unsubscribe: () => void } | null = null;
let cancelBackupStartup: (() => void) | null = null;
let stopOfflineSync: (() => void) | null = null;
let isOnline = true;
let signOutError = '';
onMount(() => {
userStoreReady = true;
isOnline = navigator.onLine;
const updateOnlineState = () => {
isOnline = navigator.onLine;
@@ -46,6 +52,7 @@
if (navigator.onLine) return;
const target = event.target instanceof Element ? event.target : null;
if (!target?.closest('button, input, textarea, select, form')) return;
if (target.closest('[data-offline-action]')) return;
event.preventDefault();
event.stopImmediatePropagation();
};
@@ -57,7 +64,12 @@
updateOnlineState();
void getUser()
.then(async () => {
if (localUser) await claimOfflineData(localUser.id);
if (localUser) {
cancelBackupStartup = afterCriticalPageWork(() => {
if (localUser) void refreshBackupStatus();
});
await claimOfflineData(localUser.id);
}
stopOfflineSync = startOfflineSync(() => localUser?.id ?? null);
})
.catch((error) => console.error('Unable to claim offline data', error));
@@ -72,15 +84,19 @@
// SIGNED_IN also fires when a tab regains focus, so only a change of account fetches a new
// offline copy. Page loads and token refreshes reuse the saved one while it is fresh.
if (event === 'SIGNED_IN' && session.user.id !== previousUserId) {
cancelBackupStartup?.();
clearBackupStatus();
void claimOfflineData(session.user.id)
.then(requestOfflineSync)
.catch((error) => console.error('Unable to claim offline data', error));
void refreshBackupStatus();
}
} else {
// Offline data is only cleared by the Sign Out button (or another account claiming it).
// An expired or rejected session must not throw away artwork that would then have to be
// downloaded again after signing back in.
localUser = null;
clearBackupStatus();
}
user.set(localUser);
});
@@ -89,6 +105,7 @@
return () => {
authSubscription?.unsubscribe();
stopOfflineSync?.();
cancelBackupStartup?.();
window.removeEventListener('online', updateOnlineState);
window.removeEventListener('offline', updateOnlineState);
for (const name of ['click', 'submit', 'input', 'change', 'keydown']) {
@@ -98,10 +115,7 @@
};
});
function formatMegabytes(bytes: number) {
const megabytes = bytes / 1048576;
return megabytes < 1 ? '<1 MB' : `≈${Math.round(megabytes)} MB`;
}
$: reconnectLabels = $backupsNeedingReconnect.map((provider) => PROVIDER_LABELS[provider]);
async function getUser() {
const {
@@ -178,7 +192,7 @@
{#if localUser}
<div tabindex="0" role="button" class="btn btn-ghost btn-circle avatar">
<div class="w-10 rounded-full">
<img alt="usericon" src="/OIG5.jpg" />
<img alt="Account menu" src="/avatar.webp" width="40" height="40" />
</div>
</div>
<ul
@@ -192,6 +206,9 @@
<li>
<a href="/backup-settings"> Backup Settings </a>
</li>
<li>
<a href="/offline-guide"> Using Offline </a>
</li>
<li>
<SignOut
{supabase}
@@ -222,34 +239,18 @@
<div class="alert rounded-none" role="status">
<span>Offline read-only mode: saved data remains available, but changes are disabled.</span>
</div>
{:else if localUser && $offlineSyncStatus.state === 'error'}
<div class="alert alert-warning rounded-none" role="status">
<span>Offline copy could not be refreshed: {$offlineSyncStatus.message}</span>
<button class="btn btn-sm" on:click={requestOfflineSync}>Retry</button>
</div>
{:else if localUser && $artworkDownloadStatus.state === 'error'}
<div class="alert alert-warning rounded-none" role="status">
<span
>Offline data is saved, but artwork could not be saved: {$artworkDownloadStatus.message}.</span
>
<button class="btn btn-sm" on:click={downloadAllArtwork}>Retry</button>
</div>
{/if}
{#if isOnline && localUser && $offlineSyncStatus.state === 'syncing'}
<p class="bg-base-200 px-4 py-1 text-center text-xs" role="status">Updating offline copy…</p>
{:else if isOnline && localUser && $offlineSyncStatus.generatedAt}
<p class="bg-base-200 px-4 py-1 text-center text-xs" role="status">
Offline copy updated {new Date($offlineSyncStatus.generatedAt).toLocaleString()}.
{#if $artworkDownloadStatus.state === 'downloading'}
Saving all artwork for offline…
{:else if $artworkDownloadStatus.state === 'missing'}
<button class="link" on:click={downloadAllArtwork}>
Save all artwork for offline{#if $artworkDownloadStatus.missingBytes}{' '}({formatMegabytes(
$artworkDownloadStatus.missingBytes
)}){/if}
</button>
{/if}
</p>
{#if localUser && reconnectLabels.length > 0 && $page.url.pathname !== '/backup-settings'}
<div
class="alert alert-warning rounded-none"
role="alert"
data-testid="backup-reconnect-banner"
>
<span>
Your {reconnectLabels.join(' and ')} backup has stopped because access expired or was revoked.
</span>
<a class="btn btn-sm" href="/backup-settings">Reconnect</a>
</div>
{/if}
<main class="flex-grow">
@@ -258,8 +259,14 @@
<footer class="footer items-center p-4 bg-neutral text-neutral-content bottom-0">
<aside class="items-center grid-flow-col">
<a href="https://github.com/jcreek/LivingDexTracker" target="_blank">
<a
href="https://github.com/jcreek/LivingDexTracker"
target="_blank"
rel="noopener noreferrer"
aria-label="Living Dex Tracker on GitHub"
>
<svg
aria-hidden="true"
width="36"
height="36"
fill-rule="evenodd"
@@ -280,8 +287,13 @@
</p>
</aside>
<nav class="grid-flow-col gap-4 md:place-self-center md:justify-self-end">
<a href="https://discord.gg/SQcJkaXDye" target="_blank"
<a
href="https://discord.gg/SQcJkaXDye"
target="_blank"
rel="noopener noreferrer"
aria-label="Living Dex Tracker Discord community"
><svg
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
@@ -302,10 +314,10 @@
</div>
<style>
:global(.offline-readonly button),
:global(.offline-readonly input),
:global(.offline-readonly textarea),
:global(.offline-readonly select) {
:global(.offline-readonly button:not([data-offline-action])),
:global(.offline-readonly input:not([data-offline-action])),
:global(.offline-readonly textarea:not([data-offline-action])),
:global(.offline-readonly select:not([data-offline-action])) {
pointer-events: none;
opacity: 0.65;
}
+1
View File
@@ -60,6 +60,7 @@ export const load: LayoutLoad = async ({ fetch, data, depends }) => {
return {
supabase,
session,
user: data.user,
recoveryIntent: !!session && (hashRecoveryCallback || recoveryExchangeSucceeded)
};
};
+20 -9
View File
@@ -1,17 +1,28 @@
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
export type PublicStats = {
pokemonCaught: number;
users: number;
livingDexesCompleted: number;
};
/**
* Server-side load function for the homepage
*
* Fetches public statistics from the database and passes them to the page component.
* Stats are cached for 24 hours to improve performance.
* Signed-in users go straight to their Pokédexes. For everyone else the page renders at once and
* the public statistics stream in afterwards, so a slow stats query never delays the first paint.
*/
export const load: PageServerLoad = async ({ fetch }) => {
// Fetch stats from database
const statsResponse = await fetch('/api/stats');
const statsData = await statsResponse.json();
export const load: PageServerLoad = async ({ fetch, locals }) => {
const { user } = await locals.safeGetSession();
if (user) {
throw redirect(303, '/my-pokedexes');
}
return {
stats: statsData.error ? null : statsData
};
const stats: Promise<PublicStats | null> = fetch('/api/stats')
.then((response) => response.json())
.then((statsData) => (statsData.error ? null : statsData))
.catch(() => null);
return { stats };
};
+302 -338
View File
@@ -1,35 +1,12 @@
<script lang="ts">
import { onMount } from 'svelte';
import SignUp from '$lib/components/SignUp.svelte';
import { goto } from '$app/navigation';
// Signed-in visitors are redirected by the server load, so the page renders straight away.
export let data;
let { supabase, stats } = data;
$: ({ supabase, stats } = data);
// Redirection is decided from the live session below, so the user store is not needed here.
let isCheckingSession = true;
onMount(() => {
checkSessionAndRedirect();
});
async function checkSessionAndRedirect() {
try {
const {
data: { session }
} = await supabase.auth.getSession();
if (session) {
await goto('/my-pokedexes');
}
} catch (error) {
console.error('Error checking session:', error);
} finally {
isCheckingSession = false;
}
}
async function handleSignedUp() {
await goto('/welcome');
}
@@ -44,16 +21,6 @@
}
return num.toString();
}
// Get formatted stats or fallback to 0
let pokemonCaught = '0';
let users = '0';
let livingDexesCompleted = '0';
$: {
pokemonCaught = formatNumber(stats?.pokemonCaught ?? 0);
users = formatNumber(stats?.users ?? 0);
livingDexesCompleted = formatNumber(stats?.livingDexesCompleted ?? 0);
}
</script>
<svelte:head>
@@ -72,322 +39,319 @@
/>
</svelte:head>
{#if isCheckingSession}
<!-- Loading placeholder while checking session -->
<div class="hero bg-base-100 my-36">
<div class="hero-content flex-col">
<span class="loading loading-spinner loading-lg"></span>
<!-- Hero Section -->
<div class="hero bg-base-100 my-36">
<div class="hero-content flex-col lg:flex-row-reverse">
<div class="text-center lg:text-left">
<div class="flex flex-wrap gap-2 mb-4">
<div class="badge badge-primary badge-lg gap-1">
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-4 w-4"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fill-rule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
clip-rule="evenodd"
/>
</svg>
Free
</div>
<div class="badge badge-secondary badge-lg gap-1">
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-4 w-4"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"
/>
</svg>
Open Source
</div>
<a href="/offline-guide" class="badge badge-accent badge-lg gap-1 hover:opacity-80">
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-4 w-4"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fill-rule="evenodd"
d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z"
clip-rule="evenodd"
/>
</svg>
Offline-friendly
</a>
</div>
<h1 class="text-5xl font-bold mb-6">Start Your Pokédex Journey!</h1>
<p class="text-xl mb-6 text-base-content/80">
Track your progress towards a complete Living Pokédex — one of every Pokémon, actively
maintained across your boxes. Join thousands of trainers worldwide.
</p>
<div class="flex flex-wrap gap-3 justify-center lg:justify-start">
<a
href="https://discord.gg/2ytj4pkUPY"
target="_blank"
rel="noopener noreferrer"
class="btn btn-primary btn-lg"
aria-label="Join the Living Dex Tracker Discord community"
>
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-5 w-5"
viewBox="0 0 24 24"
fill="currentColor"
>
<path
d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028 14.09 14.09 0 0 0 1.226-1.994.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"
/>
</svg>
Join Discord
</a>
<a
href="https://github.com/jcreek/LivingDexTracker"
target="_blank"
rel="noopener noreferrer"
class="btn btn-outline btn-lg"
aria-label="View the Living Dex Tracker project on GitHub"
>
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-5 w-5"
viewBox="0 0 24 24"
fill="currentColor"
>
<path
d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"
/>
</svg>
Contribute on GitHub
</a>
</div>
</div>
<div class="card shrink-0 w-full max-w-sm shadow-2xl bg-neutral">
<div class="card-body">
<h2 class="card-title text-2xl mb-4">Get Started Free</h2>
<SignUp {supabase} on:signedUp={handleSignedUp} />
</div>
</div>
</div>
{:else}
<!-- Hero Section -->
<div class="hero bg-base-100 my-36">
<div class="hero-content flex-col lg:flex-row-reverse">
<div class="text-center lg:text-left">
<div class="flex flex-wrap gap-2 mb-4">
<div class="badge badge-primary badge-lg gap-1">
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-4 w-4"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fill-rule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
clip-rule="evenodd"
/>
</svg>
Free
</div>
<div class="badge badge-secondary badge-lg gap-1">
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-4 w-4"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"
/>
</svg>
Open Source
</div>
<div class="badge badge-accent badge-lg gap-1">
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-4 w-4"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fill-rule="evenodd"
d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z"
clip-rule="evenodd"
/>
</svg>
Offline-friendly
</div>
</div>
<h1 class="text-5xl font-bold mb-6">Start Your Pokédex Journey!</h1>
<p class="text-xl mb-6 text-base-content/80">
Track your progress towards a complete Living Pokédex — one of every Pokémon, actively
maintained across your boxes. Join thousands of trainers worldwide.
</p>
<div class="flex flex-wrap gap-3 justify-center lg:justify-start">
<a
href="https://discord.gg/2ytj4pkUPY"
target="_blank"
rel="noopener noreferrer"
class="btn btn-primary btn-lg"
aria-label="Join the Living Dex Tracker Discord community"
>
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-5 w-5"
viewBox="0 0 24 24"
fill="currentColor"
>
<path
d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028 14.09 14.09 0 0 0 1.226-1.994.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"
/>
</svg>
Join Discord
</a>
<a
href="https://github.com/jcreek/LivingDexTracker"
target="_blank"
rel="noopener noreferrer"
class="btn btn-outline btn-lg"
aria-label="View the Living Dex Tracker project on GitHub"
>
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-5 w-5"
viewBox="0 0 24 24"
fill="currentColor"
>
<path
d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"
/>
</svg>
Contribute on GitHub
</a>
</div>
<!-- Stats Section -->
<div class="bg-base-200 py-16">
<div class="container mx-auto px-4">
<div class="stats stats-vertical lg:stats-horizontal shadow bg-neutral text-center w-full">
<div class="stat">
<div class="stat-title">Pokémon caught</div>
<div class="stat-value text-primary">
{#await stats}{:then value}{formatNumber(value?.pokemonCaught ?? 0)}{/await}
</div>
</div>
<div class="stat">
<div class="stat-title">Users</div>
<div class="stat-value text-primary">
{#await stats}{:then value}{formatNumber(value?.users ?? 0)}{/await}
</div>
</div>
<div class="stat">
<div class="stat-title">Living Dexes Completed</div>
<div class="stat-value text-primary">
{#await stats}{:then value}{formatNumber(value?.livingDexesCompleted ?? 0)}{/await}
</div>
</div>
</div>
</div>
</div>
<!-- What is a Living Dex Section -->
<div class="py-16 bg-base-100">
<div class="container mx-auto px-4 max-w-4xl">
<div class="card bg-base-100 shadow-xl">
<div class="card-body">
<h2 class="card-title text-3xl mb-4">What is a Living Dex?</h2>
<p class="text-lg text-base-content/80">
A Living Dex is a complete Pokédex where you keep one of every Pokémon in your boxes
(often including forms/variants). Living Dex Tracker helps you build and maintain that
collection with filters, notes, and progress tracking.
</p>
</div>
</div>
</div>
</div>
<!-- Features Section -->
<div class="py-16 bg-base-200">
<div class="container mx-auto px-4 max-w-6xl">
<h2 class="text-4xl font-bold mb-12 text-center">Why Choose Living Dex Tracker?</h2>
<div class="grid md:grid-cols-2 gap-6">
<div class="card bg-neutral shadow-xl">
<div class="card-body">
<div class="flex items-start gap-4">
<div class="flex-shrink-0">
<svg
class="w-10 h-10 text-green-500"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
></path>
</svg>
</div>
<div>
<h2 class="card-title text-xl mb-2">Social & Shareable</h2>
<p class="text-base-content/80">
Easily share your Pokédex journey with friends, or find theirs. If you'd rather go
it alone, that's okay too!
</p>
</div>
</div>
</div>
</div>
<div class="card bg-neutral shadow-xl">
<div class="card-body">
<div class="flex items-start gap-4">
<div class="flex-shrink-0">
<svg
class="w-10 h-10 text-green-500"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"
></path>
</svg>
</div>
<div>
<h2 class="card-title text-xl mb-2">Free & Open Source</h2>
<p class="text-base-content/80">
Completely open source and free to use, enabling the community to contribute updates
as soon as new Pokémon are released.
</p>
</div>
</div>
</div>
</div>
<div class="card bg-neutral shadow-xl">
<div class="card-body">
<div class="flex items-start gap-4">
<div class="flex-shrink-0">
<svg
class="w-10 h-10 text-green-500"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4"
></path>
</svg>
</div>
<div>
<h2 class="card-title text-xl mb-2">Advanced Filtering</h2>
<p class="text-base-content/80">
Track simple progress or tackle harder variants like a Living Origin Form Dex with
our powerful filtering options for targeted catching sessions.
</p>
</div>
</div>
</div>
</div>
<div class="card bg-neutral shadow-xl">
<div class="card-body">
<div class="flex items-start gap-4">
<div class="flex-shrink-0">
<svg
class="w-10 h-10 text-green-500"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
></path>
</svg>
</div>
<div>
<h2 class="card-title text-xl mb-2">100% free</h2>
<p class="text-base-content/80">
Did we mention it's completely free to use? Oh, we did? Good. Because it is.
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- CTA Section -->
<div class="py-16 bg-base-100">
<div class="container mx-auto px-4 text-center">
<h2 class="text-4xl font-bold mb-6">Ready to Start Your Journey?</h2>
<p class="text-xl mb-8 text-base-content/80 max-w-2xl mx-auto">
Get started today with tracking your Living Pokédex progress. It's free, open source, and
built with love for the Pokémon community.
</p>
<div class="flex flex-wrap gap-4 justify-center">
<div class="card shrink-0 w-full max-w-sm shadow-2xl bg-neutral">
<div class="card-body">
<h2 class="card-title text-2xl mb-4">Get Started Free</h2>
<h3 class="card-title text-xl mb-4">Sign Up Now</h3>
<SignUp {supabase} on:signedUp={handleSignedUp} />
</div>
</div>
</div>
</div>
</div>
<!-- Stats Section -->
<div class="bg-base-200 py-16">
<div class="container mx-auto px-4">
<div class="stats stats-vertical lg:stats-horizontal shadow bg-neutral text-center w-full">
<div class="stat">
<div class="stat-title">Pokémon caught</div>
<div class="stat-value text-primary">{pokemonCaught}</div>
</div>
<div class="stat">
<div class="stat-title">Users</div>
<div class="stat-value text-primary">{users}</div>
</div>
<div class="stat">
<div class="stat-title">Living Dexes Completed</div>
<div class="stat-value text-primary">{livingDexesCompleted}</div>
</div>
<!-- Legal Section -->
<div class="py-8 bg-base-200">
<div class="container mx-auto px-4 max-w-4xl">
<div class="card bg-base-100 shadow-xl">
<div class="card-body">
<h2 class="card-title text-lg mb-2">Legal Disclaimer</h2>
<p class="text-sm text-base-content/70">
Living Dex Tracker is a fan-made project. We do not claim ownership of any Pokémon
characters, images, or other content featured on this website. This project is not
affiliated with, endorsed, sponsored, or specifically approved by Nintendo, Game Freak, or
The Pokémon Company.
</p>
</div>
</div>
</div>
<!-- What is a Living Dex Section -->
<div class="py-16 bg-base-100">
<div class="container mx-auto px-4 max-w-4xl">
<div class="card bg-base-100 shadow-xl">
<div class="card-body">
<h2 class="card-title text-3xl mb-4">What is a Living Dex?</h2>
<p class="text-lg text-base-content/80">
A Living Dex is a complete Pokédex where you keep one of every Pokémon in your boxes
(often including forms/variants). Living Dex Tracker helps you build and maintain that
collection with filters, notes, and progress tracking.
</p>
</div>
</div>
</div>
</div>
<!-- Features Section -->
<div class="py-16 bg-base-200">
<div class="container mx-auto px-4 max-w-6xl">
<h2 class="text-4xl font-bold mb-12 text-center">Why Choose Living Dex Tracker?</h2>
<div class="grid md:grid-cols-2 gap-6">
<div class="card bg-neutral shadow-xl">
<div class="card-body">
<div class="flex items-start gap-4">
<div class="flex-shrink-0">
<svg
class="w-10 h-10 text-green-500"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
></path>
</svg>
</div>
<div>
<h2 class="card-title text-xl mb-2">Social & Shareable</h2>
<p class="text-base-content/80">
Easily share your Pokédex journey with friends, or find theirs. If you'd rather go
it alone, that's okay too!
</p>
</div>
</div>
</div>
</div>
<div class="card bg-neutral shadow-xl">
<div class="card-body">
<div class="flex items-start gap-4">
<div class="flex-shrink-0">
<svg
class="w-10 h-10 text-green-500"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"
></path>
</svg>
</div>
<div>
<h2 class="card-title text-xl mb-2">Free & Open Source</h2>
<p class="text-base-content/80">
Completely open source and free to use, enabling the community to contribute
updates as soon as new Pokémon are released.
</p>
</div>
</div>
</div>
</div>
<div class="card bg-neutral shadow-xl">
<div class="card-body">
<div class="flex items-start gap-4">
<div class="flex-shrink-0">
<svg
class="w-10 h-10 text-green-500"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4"
></path>
</svg>
</div>
<div>
<h2 class="card-title text-xl mb-2">Advanced Filtering</h2>
<p class="text-base-content/80">
Track simple progress or tackle harder variants like a Living Origin Form Dex with
our powerful filtering options for targeted catching sessions.
</p>
</div>
</div>
</div>
</div>
<div class="card bg-neutral shadow-xl">
<div class="card-body">
<div class="flex items-start gap-4">
<div class="flex-shrink-0">
<svg
class="w-10 h-10 text-green-500"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
></path>
</svg>
</div>
<div>
<h2 class="card-title text-xl mb-2">100% free</h2>
<p class="text-base-content/80">
Did we mention it's completely free to use? Oh, we did? Good. Because it is.
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- CTA Section -->
<div class="py-16 bg-base-100">
<div class="container mx-auto px-4 text-center">
<h2 class="text-4xl font-bold mb-6">Ready to Start Your Journey?</h2>
<p class="text-xl mb-8 text-base-content/80 max-w-2xl mx-auto">
Get started today with tracking your Living Pokédex progress. It's free, open source, and
built with love for the Pokémon community.
</p>
<div class="flex flex-wrap gap-4 justify-center">
<div class="card shrink-0 w-full max-w-sm shadow-2xl bg-neutral">
<div class="card-body">
<h3 class="card-title text-xl mb-4">Sign Up Now</h3>
<SignUp {supabase} on:signedUp={handleSignedUp} />
</div>
</div>
</div>
</div>
</div>
<!-- Legal Section -->
<div class="py-8 bg-base-200">
<div class="container mx-auto px-4 max-w-4xl">
<div class="card bg-base-100 shadow-xl">
<div class="card-body">
<h2 class="card-title text-lg mb-2">Legal Disclaimer</h2>
<p class="text-sm text-base-content/70">
Living Dex Tracker is a fan-made project. We do not claim ownership of any Pokémon
characters, images, or other content featured on this website. This project is not
affiliated with, endorsed, sponsored, or specifically approved by Nintendo, Game Freak,
or The Pokémon Company.
</p>
</div>
</div>
</div>
</div>
{/if}
</div>
@@ -7,11 +7,6 @@ export const GET = async (event: RequestEvent) => {
try {
const userId = await requireAuth(event);
const { session } = await event.locals.safeGetSession();
if (session) {
await event.locals.supabase.auth.setSession(session);
}
const repo = new PokedexExportIntegrationRepository(event.locals.supabase, userId, null);
const integrations = await repo.listAll();
@@ -98,7 +98,9 @@ export const GET = async (event: RequestEvent) => {
accessToken: tokenData.access_token,
refreshToken: tokenData.refresh_token ?? null,
accessTokenExpiresAt: expiresAt,
metadata: tokenData.scope ? { scope: tokenData.scope } : null
metadata: tokenData.scope ? { scope: tokenData.scope } : null,
// A reconnect replaces the tokens, so any error from the old ones no longer applies.
lastError: null
});
} catch (saveError) {
console.error('Dropbox integration save failed:', saveError);
@@ -99,7 +99,9 @@ export const GET = async (event: RequestEvent) => {
accessToken: tokenData.access_token,
refreshToken: tokenData.refresh_token ?? null,
accessTokenExpiresAt: expiresAt,
metadata: tokenData.scope ? { scope: tokenData.scope } : null
metadata: tokenData.scope ? { scope: tokenData.scope } : null,
// A reconnect replaces the tokens, so any error from the old ones no longer applies.
lastError: null
});
} catch (saveError) {
console.error('Google Drive integration save failed:', saveError);
@@ -1,9 +1,8 @@
import { json } from '@sveltejs/kit';
import CombinedDataRepository from '$lib/repositories/CombinedDataRepository';
import PokedexRepository from '$lib/repositories/PokedexRepository';
import { getOptionalUserId } from '$lib/utils/auth';
import type { RequestEvent } from '@sveltejs/kit';
import { resolveDexScopes } from '$lib/services/PokedexDexScopeService';
import { loadCombinedDataPage } from '$lib/services/CombinedDataService';
// GET: Get combined data (pokédex entries + catch records) for specific pokédex
export const GET = async (event: RequestEvent) => {
@@ -23,48 +22,29 @@ export const GET = async (event: RequestEvent) => {
const region = url.searchParams.get('region') || '';
const game = url.searchParams.get('game') || '';
// If authenticated, verify user owns this pokédex and get its gameScope
let pokedex;
if (userId) {
const pokedexRepo = new PokedexRepository(event.locals.supabase, userId);
pokedex = await pokedexRepo.findById(pokedexId);
if (!pokedex) {
// User is authenticated but doesn't own this pokédex (or it doesn't exist)
return json({ error: 'Pokedex not found' }, { status: 404 });
}
} else {
if (!userId) {
// Anonymous users cannot view pokédexes
return json({ error: 'Unauthorized' }, { status: 401 });
}
// Use pokédex's gameScope as default filter if no manual game filter is set
const effectiveGame = game || pokedex.gameScope || '';
const dexScopes = await resolveDexScopes(event.locals.supabase, pokedex);
// Verify the user owns this pokédex and get its gameScope
const pokedexRepo = new PokedexRepository(event.locals.supabase, userId);
const pokedex = await pokedexRepo.findById(pokedexId);
const repo = new CombinedDataRepository(event.locals.supabase, userId, pokedexId);
if (!pokedex) {
// User is authenticated but doesn't own this pokédex (or it doesn't exist)
return json({ error: 'Pokedex not found' }, { status: 404 });
}
// Get paginated combined data
const combinedData = await repo.findCombinedData(
userId!,
page,
limit,
enableForms,
region,
effectiveGame,
dexScopes
return json(
await loadCombinedDataPage(event.locals.supabase, userId, pokedex, {
page,
limit,
enableForms,
region,
game
})
);
// Get total count for pagination
const totalCount = await repo.countCombinedData(enableForms, region, effectiveGame, dexScopes);
const totalPages = Math.ceil(totalCount / limit);
return json({
combinedData,
totalPages,
currentPage: page,
totalCount
});
} catch (err) {
console.error(err);
if (err && typeof err === 'object' && 'status' in err) {
@@ -0,0 +1,18 @@
import { error, json } from '@sveltejs/kit';
import { requireAuth } from '$lib/utils/auth';
import PokedexRepository from '$lib/repositories/PokedexRepository';
import { loadPokedexEntryDetail } from '$lib/services/PokedexGridService';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async (event) => {
const userId = await requireAuth(event);
const entryId = Number(event.params.entryId);
if (!Number.isSafeInteger(entryId) || entryId < 1) throw error(400, 'Invalid entry');
const pokedex = await new PokedexRepository(event.locals.supabase, userId).findById(
event.params.id
);
if (!pokedex) throw error(404, 'Pokédex not found');
const detail = await loadPokedexEntryDetail(event.locals.supabase, userId, pokedex, entryId);
if (!detail) throw error(404, 'Entry not found');
return json(detail, { headers: { 'cache-control': 'private, no-store' } });
};
@@ -0,0 +1,29 @@
import { packGrid } from '$lib/models/PokedexGridRow';
import { error, json } from '@sveltejs/kit';
import { requireAuth } from '$lib/utils/auth';
import PokedexRepository from '$lib/repositories/PokedexRepository';
import { loadPokedexGrid } from '$lib/services/PokedexGridService';
import { PokedexPerformance } from '$lib/server/pokedexPerformance';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async (event) => {
const timings = new PokedexPerformance();
const userId = await timings.measure('auth', () => requireAuth(event));
const pokedex = await timings.measure('ownership', () =>
new PokedexRepository(event.locals.supabase, userId).findById(event.params.id)
);
if (!pokedex) throw error(404, 'Pokédex not found');
const grid = await loadPokedexGrid(event.locals.supabase, userId, pokedex, timings);
const packed = timings.prepare(() => packGrid(grid));
timings.recordAuth(event.locals.pokedexAuthMs);
const timing = timings.finish();
return json(
{ grid: packed },
{
headers: {
'cache-control': 'private, no-store',
...(timing ? { 'server-timing': timing } : {})
}
}
);
};
+4
View File
@@ -27,6 +27,10 @@ export const GET = async (event: RequestEvent) => {
}
const stats = data[0];
// The figures refresh at most daily, so let browsers and the CDN reuse them.
event.setHeaders({
'cache-control': 'public, max-age=300, s-maxage=3600, stale-while-revalidate=86400'
});
return json({
pokemonCaught: stats.pokemon_caught,
users: stats.total_users,
+23 -8
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import { onMount } from 'svelte';
import { browser } from '$app/environment';
import { setBackupStatus } from '$lib/stores/backupStatus';
type ExportIntegrationSummary = {
id: string;
@@ -40,6 +41,8 @@
exportIntegrations = (await response.json()) as ExportIntegrationSummary[];
googleIntegration = exportIntegrations.find((i) => i.provider === 'google_drive');
dropboxIntegration = exportIntegrations.find((i) => i.provider === 'dropbox');
// Keeps the sitewide banner in step, e.g. clearing it after the OAuth flow returns here.
setBackupStatus(exportIntegrations);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
exportError = message || 'Failed to load export settings';
@@ -48,6 +51,16 @@
}
}
function statusBadge(integration: ExportIntegrationSummary | undefined) {
if (!integration) return { label: 'Not Connected', className: 'badge-ghost' };
// Exports switch an integration off when the provider revokes its access.
if (!integration.enabled) return { label: 'Reconnect needed', className: 'badge-warning' };
return { label: 'Connected', className: 'badge-success' };
}
$: googleBadge = statusBadge(googleIntegration);
$: dropboxBadge = statusBadge(dropboxIntegration);
function getGoogleFolderUrl(folderId: string): string {
return `https://drive.google.com/drive/folders/${folderId}`;
}
@@ -106,13 +119,14 @@
<div class="border border-base-300 rounded-lg p-4 bg-base-100">
<div class="flex items-center justify-between">
<h2 class="font-semibold">Google Drive</h2>
<span class={`badge ${googleIntegration ? 'badge-success' : 'badge-ghost'}`}>
{googleIntegration ? 'Connected' : 'Not Connected'}
</span>
<span class={`badge ${googleBadge.className}`}>{googleBadge.label}</span>
</div>
<div class="mt-3 space-y-2">
<div class="flex items-center justify-end gap-2">
<button class="btn btn-sm btn-outline" on:click={connectGoogleDrive}>
<button
class={`btn btn-sm ${googleIntegration?.enabled === false ? 'btn-primary' : 'btn-outline'}`}
on:click={connectGoogleDrive}
>
{googleIntegration ? 'Reconnect' : 'Connect'}
</button>
</div>
@@ -142,13 +156,14 @@
<div class="border border-base-300 rounded-lg p-4 bg-base-100">
<div class="flex items-center justify-between">
<h2 class="font-semibold">Dropbox</h2>
<span class={`badge ${dropboxIntegration ? 'badge-success' : 'badge-ghost'}`}>
{dropboxIntegration ? 'Connected' : 'Not Connected'}
</span>
<span class={`badge ${dropboxBadge.className}`}>{dropboxBadge.label}</span>
</div>
<div class="mt-3 space-y-2">
<div class="flex items-center justify-end gap-2">
<button class="btn btn-sm btn-outline" on:click={connectDropbox}>
<button
class={`btn btn-sm ${dropboxIntegration?.enabled === false ? 'btn-primary' : 'btn-outline'}`}
on:click={connectDropbox}
>
{dropboxIntegration ? 'Reconnect' : 'Connect'}
</button>
</div>
+111
View File
@@ -0,0 +1,111 @@
<script lang="ts">
import { user } from '$lib/stores/user.js';
import {
artworkDownloadStatus,
downloadAllArtwork,
offlineSyncStatus,
requestOfflineSync
} from '$lib/stores/offlineSync';
function formatMegabytes(bytes: number) {
const megabytes = bytes / 1048576;
return megabytes < 1 ? '<1 MB' : `≈${Math.round(megabytes)} MB`;
}
</script>
<svelte:head>
<title>Using Offline - Living Dex Tracker</title>
<meta
name="description"
content="How Living Dex Tracker keeps your Pokédexes and artwork available offline, and how to save everything before you lose signal."
/>
</svelte:head>
<div class="container mx-auto p-4 max-w-screen-lg">
<h1 class="text-3xl font-bold mb-6">Using Living Dex Tracker offline</h1>
<div class="card bg-base-100 shadow-xl mb-6">
<div class="card-body">
<h2 class="card-title">Your offline copy</h2>
{#if !$user}
<p>
<a href="/signin" class="link link-primary">Sign in</a> to keep a copy of your pokédexes on
this device.
</p>
{:else}
<div data-testid="offline-copy-status" role="status">
{#if $offlineSyncStatus.state === 'syncing'}
<p>Updating your offline copy…</p>
{:else if $offlineSyncStatus.state === 'error'}
<div class="alert alert-warning">
<span>Your offline copy could not be refreshed: {$offlineSyncStatus.message}</span>
<button class="btn btn-sm" on:click={requestOfflineSync}>Retry</button>
</div>
{:else if $offlineSyncStatus.generatedAt}
<p>
Offline copy updated {new Date($offlineSyncStatus.generatedAt).toLocaleString()}.
</p>
{:else}
<p>
No offline copy is saved on this device yet. It saves automatically while you are
online.
</p>
{/if}
</div>
<h3 class="font-semibold mt-4">Artwork</h3>
{#if $artworkDownloadStatus.state === 'downloading'}
<p role="status">Saving all artwork for offline…</p>
{:else if $artworkDownloadStatus.state === 'error'}
<div class="alert alert-warning" role="status">
<span>Some artwork could not be saved: {$artworkDownloadStatus.message}.</span>
<button class="btn btn-sm" on:click={downloadAllArtwork}>Retry</button>
</div>
{:else if $artworkDownloadStatus.state === 'done'}
<p>All artwork is saved on this device.</p>
{:else}
<p>
Artwork is saved as you view it. To browse every Pokémon offline, including every form,
shiny and female variant, save it all now.
</p>
{#if $artworkDownloadStatus.state === 'missing'}
<div>
<button class="btn btn-primary btn-sm" on:click={downloadAllArtwork}>
Save all artwork for offline{#if $artworkDownloadStatus.missingBytes}{' '}({formatMegabytes(
$artworkDownloadStatus.missingBytes
)}){/if}
</button>
</div>
{/if}
{/if}
{/if}
</div>
</div>
<div class="card bg-base-100 shadow-xl">
<div class="card-body">
<h2 class="card-title">How it works</h2>
<ul class="list-disc pl-5 space-y-2">
<li>
<strong>Install the app.</strong> Use your browser's "Install app" or "Add to Home Screen"
option so Living Dex Tracker opens without a connection.
</li>
<li>
<strong>Stay signed in.</strong> Your offline copy updates automatically whenever you are online,
including after you make changes.
</li>
<li>
<strong>Offline is read-only.</strong> You can browse your pokédexes, but catches and edits
are disabled until you are back online.
</li>
<li>
<strong>Artwork.</strong> Sprites are saved as you view them. Use "Save all artwork for offline"
above to download the rest in one go.
</li>
<li>
<strong>Signing out</strong> removes the offline copy from this device.
</li>
</ul>
</div>
</div>
</div>
+27 -22
View File
@@ -1,28 +1,33 @@
import { packGrid } from '$lib/models/PokedexGridRow';
import { error, redirect } from '@sveltejs/kit';
import PokedexRepository from '$lib/repositories/PokedexRepository';
import { loadPokedexGrid } from '$lib/services/PokedexGridService';
import { PokedexPerformance } from '$lib/server/pokedexPerformance';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ locals, params }) => {
const { safeGetSession, supabase } = locals;
const { session, user } = await safeGetSession();
// Require authentication
if (!session || !user) {
throw redirect(303, '/signin');
export const load: PageServerLoad = async ({ locals, params, setHeaders, cookies }) => {
const timings = new PokedexPerformance();
const { session, user } = await timings.measure('auth', () => locals.safeGetSession());
if (!session || !user) throw redirect(303, '/signin');
const pokedex = await timings.measure('ownership', () =>
new PokedexRepository(locals.supabase, user.id).findById(params.id)
);
if (!pokedex) throw error(404, 'Pokédex not found');
let grid = null;
try {
grid = await loadPokedexGrid(locals.supabase, user.id, pokedex, timings);
} catch {
console.error('Unable to load Pokédex grid');
}
const { id } = params;
// Fetch pokédex to verify ownership (RLS will also block, but we want a proper 404)
const repo = new PokedexRepository(supabase, user.id);
const pokedex = await repo.findById(id);
if (!pokedex) {
// Either doesn't exist or user doesn't own it
throw error(404, 'Pokédex not found');
}
return {
pokedex
};
const packed = timings.prepare(() => (grid ? packGrid(grid) : null));
timings.recordAuth(locals.pokedexAuthMs);
const timing = timings.finish();
setHeaders({
'cache-control': 'private, no-store',
...(timing ? { 'server-timing': timing } : {})
});
const layout = cookies.get('boxViewLayout');
const boxViewLayout: 'comfortable' | 'compact' | 'ultra' =
layout === 'compact' || layout === 'ultra' ? layout : 'comfortable';
return { pokedex, grid: packed, boxViewLayout };
};
+314 -112
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { onDestroy, onMount } from 'svelte';
import { onDestroy, onMount, tick } from 'svelte';
import { user } from '$lib/stores/user.js';
import { type User } from '@supabase/auth-js';
import { type CombinedData } from '$lib/models/CombinedData';
@@ -16,8 +16,21 @@
import PokedexEntryCatchRecord from '$lib/components/pokedex/PokedexEntryCatchRecord.svelte';
import type { Pokedex } from '$lib/models/Pokedex';
import type { PageData } from './$types';
import { requestOfflineSync } from '$lib/stores/offlineSync';
import type { SharedCombinedData } from '$lib/models/SharedPokedex';
import { readOfflineEntry, requestOfflineSync } from '$lib/stores/offlineSync';
import { get } from 'svelte/store';
import {
PROVIDER_LABELS,
backupsNeedingReconnect,
markReconnectNeeded,
refreshBackupStatus
} from '$lib/stores/backupStatus';
import type { ExportProvider } from '$lib/models/PokedexExportIntegration';
import {
unpackGrid,
type PokedexGridRow,
type CatchRecordPatch
} from '$lib/models/PokedexGridRow';
import PokemonSprite from '$lib/components/PokemonSprite.svelte';
export let data: PageData;
@@ -34,19 +47,17 @@
}
}
let combinedData = null as CombinedData[] | null;
let currentPage = 1 as number;
// Box view requires the full dataset for correct box numbering/placement.
// If/when a paginated list view is introduced, this can be lowered and paired with UI controls.
let itemsPerPage = 9999 as number;
let combinedData: PokedexGridRow[] | null = null;
type CatchUpdateEvent = CustomEvent<{
catchRecord: CatchRecord;
source: 'toggle' | 'notes' | 'notes-blur';
changes?: Partial<CatchRecord>;
}>;
let creatingRecords = false;
let totalRecordsCreated = 0;
let failedToLoad = false;
let localUser: User | null;
let localUser: User | null = data.user ?? null;
let userStoreReady = false;
let boxNumbers: number[] = [];
let showModal = false;
let selectedPokemon: CombinedData | null = null;
@@ -54,6 +65,7 @@
let shareUrl = '';
let shareFeedback = '';
let nativeShareSupported = false;
let online = true;
let catchWriteQueue: ReturnType<typeof createCatchRecordWriteQueue> | null = null;
let catchWriteQueueKey: string | null = null;
@@ -66,6 +78,8 @@
lastSuccessfulFlushAt: null
};
let lastOfflineSyncFlush: number | null = null;
// Backup providers that just refused this page's export because their access was revoked.
let reconnectToastLabels: string[] = [];
let exportAfterFlush = false;
let exportInFlight = false;
let exportTimer: ReturnType<typeof setTimeout> | null = null;
@@ -110,6 +124,24 @@
console.error('Auto-export failed:', response.status, body);
return;
}
const result = (await response.json().catch(() => null)) as {
failed?: Array<{ provider: ExportProvider; reconnectRequired?: boolean }>;
} | null;
const revoked = (result?.failed ?? []).filter((failure) => failure.reconnectRequired);
const alreadyPaused = new Set(get(backupsNeedingReconnect));
if (revoked.length > 0) {
markReconnectNeeded(revoked.map((failure) => failure.provider));
} else {
// Saving a catch record also exports on the server, and that export may already have
// paused a provider, leaving this export nothing to report. Re-read the status to catch it.
await refreshBackupStatus();
}
const newlyPaused = get(backupsNeedingReconnect).filter(
(provider) => !alreadyPaused.has(provider)
);
if (newlyPaused.length > 0) {
reconnectToastLabels = newlyPaused.map((provider) => PROVIDER_LABELS[provider]);
}
if (exportGeneration === exportInFlightGeneration) {
exportAfterFlush = false;
}
@@ -142,9 +174,13 @@
$: showShiny = !!pokedex?.isShinyDex;
const unsubscribe = user.subscribe((value) => {
localUser = value;
if (userStoreReady) localUser = value;
});
onDestroy(unsubscribe);
onDestroy(() => {
detailRequest++;
detailAbort?.abort();
});
onDestroy(() => {
catchWriteQueueUnsubscribe?.();
catchWriteQueueUnsubscribe = null;
@@ -153,9 +189,74 @@
resetExportState();
});
function openPokemonModal(pokemon: CombinedData | SharedCombinedData) {
selectedPokemon = pokemon as CombinedData;
let selectedSummary: PokedexGridRow | null = null;
let detailError = '';
let detailRequest = 0;
let detailAbort: AbortController | null = null;
let returnFocus: HTMLElement | null = null;
const detailCache = new Map<string, CombinedData>();
let detailOwner = '';
$: if (localUser?.id !== detailOwner) {
detailOwner = localUser?.id ?? '';
detailCache.clear();
closePokemonModal();
}
async function openPokemonModal(pokemon: PokedexGridRow) {
if (!showModal) returnFocus = document.activeElement as HTMLElement;
selectedSummary = pokemon;
selectedPokemon = null;
detailError = '';
showModal = true;
const request = ++detailRequest;
detailAbort?.abort();
detailAbort = new AbortController();
const id = pokedexId;
const owner = localUser?.id || '';
const entryId = pokemon.pokedexEntry._id;
const key = `${owner}:${id}:${entryId}`;
try {
let detail = detailCache.get(key);
if (!detail) {
if (!navigator.onLine) detail = (await readOfflineEntry(owner, id, entryId)) ?? undefined;
else {
const response = await fetch(`/api/pokedexes/${id}/entries/${entryId}`, {
signal: detailAbort.signal
});
if (!response.ok) throw new Error('Unable to load details. Please retry.');
detail = await response.json();
}
}
if (request !== detailRequest || id !== pokedexId || owner !== localUser?.id) return;
if (!detail) throw new Error('These details are not saved for offline use.');
detailCache.set(key, detail);
// A detail response must not undo status changes made while it was in flight.
const current = combinedData?.find((row) => row.pokedexEntry._id === entryId)?.catchRecord;
const pending = catchWriteQueue?.getPendingPatch(entryId);
selectedPokemon = {
...detail,
catchRecord:
detail.catchRecord || current || pending
? {
_id: '',
userId: owner,
pokedexId: id,
pokemonId: entryId,
caught: false,
haveToEvolve: false,
inHome: false,
hasGigantamaxed: false,
personalNotes: '',
...detail.catchRecord,
...current,
...pending
}
: null
};
} catch (error) {
if (request !== detailRequest || id !== pokedexId || owner !== localUser?.id) return;
detailError = error instanceof Error ? error.message : 'Unable to load details.';
}
}
function openShareModal() {
@@ -195,15 +296,24 @@
}
function closePokemonModal() {
detailRequest++;
detailAbort?.abort();
showModal = false;
selectedPokemon = null;
selectedSummary = null;
if (browser && returnFocus) {
const target = returnFocus;
void tick().then(() => target.isConnected && target.focus());
}
returnFocus = null;
}
function ensureCatchWriteQueue() {
if (!browser) return;
if (!pokedexId) return;
if (!localUser?.id) return;
const desiredKey = `${localUser.id}:${pokedexId}`;
const ownerId = localUser.id;
const desiredKey = `${ownerId}:${pokedexId}`;
if (catchWriteQueue && catchWriteQueueKey === desiredKey) return;
resetExportState();
@@ -216,7 +326,8 @@
endpointUrl: `/api/pokedexes/${pokedexId}/catch-records`,
fetchFn: fetch,
batchSize: 200,
concurrency: 1
concurrency: 1,
isCurrentUser: () => get(user)?.id === ownerId
});
catchWriteQueueKey = desiredKey;
@@ -243,67 +354,93 @@
});
}
function applyOptimisticCatchRecordUpdate(next: CatchRecord) {
let editGeneration = 0;
function applyOptimisticCatchRecordUpdate(next: CatchRecordPatch) {
if (!combinedData) return;
const idx = combinedData.findIndex((cd) => cd.pokedexEntry._id === next.pokemonId);
if (idx === -1) return;
// Replace the catchRecord entry with the updated version.
const current = combinedData[idx];
const patched: CombinedData = {
...current,
catchRecord: {
...(current.catchRecord ?? next),
...next
}
};
combinedData = [...combinedData.slice(0, idx), patched, ...combinedData.slice(idx + 1)];
if (selectedPokemon?.pokedexEntry._id === next.pokemonId) {
selectedPokemon = patched;
}
editGeneration++;
combinedData = combinedData.map((row) =>
row.pokedexEntry._id === next.pokemonId
? {
...row,
catchRecord: {
_id: '',
caught: false,
haveToEvolve: false,
inHome: false,
hasGigantamaxed: false,
...row.catchRecord,
...next
}
}
: row
);
const key = `${next.userId}:${next.pokedexId}:${next.pokemonId}`;
const cached = detailCache.get(key);
if (cached)
detailCache.set(key, {
...cached,
catchRecord: {
_id: '',
caught: false,
haveToEvolve: false,
inHome: false,
hasGigantamaxed: false,
personalNotes: '',
...cached.catchRecord,
...next
}
});
if (selectedPokemon?.pokedexEntry._id === next.pokemonId)
selectedPokemon = {
...selectedPokemon,
catchRecord: {
_id: '',
caught: false,
haveToEvolve: false,
inHome: false,
hasGigantamaxed: false,
personalNotes: '',
...selectedPokemon.catchRecord,
...next
}
};
}
async function handleModalCatchUpdate(event: CatchUpdateEvent) {
await updateACatch(event);
}
type GetDataOptions = {
page?: number;
perPage?: number;
setCombinedDataToNull?: boolean;
};
async function getData({
page = currentPage,
perPage = itemsPerPage,
setCombinedDataToNull = true
}: GetDataOptions = {}) {
if (!pokedex || !pokedexId) return;
if (setCombinedDataToNull) {
combinedData = null;
}
const effectivePage = Math.max(1, page);
const effectivePerPage = Math.max(1, perPage);
// Use new pokédex-scoped endpoint
const endpoint = `/api/pokedexes/${pokedexId}/combined-data?page=${effectivePage}&limit=${effectivePerPage}&enableForms=${pokedex.isFormDex}`;
const response = await fetch(endpoint);
const fetchedData = await response.json();
if (fetchedData.error) {
failedToLoad = true;
return;
}
combinedData = fetchedData.combinedData;
// Always extract box numbers for box view
if (combinedData) {
boxNumbers = calculateBoxNumbers(combinedData.length);
let gridRequest = 0;
async function getData({ setCombinedDataToNull = true } = {}) {
const id = pokedexId;
const owner = localUser?.id;
const request = ++gridRequest;
const generation = editGeneration;
if (setCombinedDataToNull) combinedData = null;
failedToLoad = false;
try {
const response = await fetch(`/api/pokedexes/${id}/grid`);
if (!response.ok) throw new Error('Unable to load grid');
const result = await response.json();
if (
request !== gridRequest ||
id !== pokedexId ||
owner !== localUser?.id ||
generation !== editGeneration
)
return;
combinedData = unpackGrid(result.grid);
detailCache.clear();
} catch {
if (request === gridRequest && id === pokedexId && owner === localUser?.id)
failedToLoad = true;
}
}
async function updateACatch(event: CatchUpdateEvent) {
if (!pokedexId) return;
ensureCatchWriteQueue();
const { catchRecord, source } = event.detail;
const { catchRecord, source, changes } = event.detail;
// Enforce mutual exclusivity (should be impossible to have both true).
const sanitizedCatchRecord: CatchRecord = { ...catchRecord };
if (sanitizedCatchRecord.caught) {
@@ -318,11 +455,25 @@
}
// Optimistic UI: update local state immediately.
applyOptimisticCatchRecordUpdate(sanitizedCatchRecord);
const patch: CatchRecordPatch = {
userId: localUser.id,
pokedexId,
pokemonId: sanitizedCatchRecord.pokemonId,
...(changes ??
(source === 'toggle'
? {
caught: sanitizedCatchRecord.caught,
haveToEvolve: sanitizedCatchRecord.haveToEvolve,
inHome: sanitizedCatchRecord.inHome,
hasGigantamaxed: sanitizedCatchRecord.hasGigantamaxed
}
: { personalNotes: sanitizedCatchRecord.personalNotes }))
};
applyOptimisticCatchRecordUpdate(patch);
// Queue a background write with coalescing.
const debounceMs = source === 'notes' ? 650 : 0;
catchWriteQueue?.enqueue(sanitizedCatchRecord, {
catchWriteQueue?.enqueue(patch, {
debounceMs,
flushSoon: true
});
@@ -347,37 +498,14 @@
if (!pokedexId) return;
ensureCatchWriteQueue();
const catchRecordsToUpdate: CatchRecord[] = combinedData
const catchRecordsToUpdate: CatchRecordPatch[] = combinedData
.filter((_, index) => calculateBoxPlacement(index).box === boxNumber)
.map(({ pokedexEntry, catchRecord }) => {
// Create default record if null
const baseRecord: CatchRecord = catchRecord ?? {
_id: '',
userId: localUser?.id || '',
pokemonId: pokedexEntry._id,
pokedexId: pokedexId,
haveToEvolve: false,
caught: false,
inHome: false,
hasGigantamaxed: false,
personalNotes: ''
};
let updatedRecord: CatchRecord = { ...baseRecord };
if (inHome !== null) {
updatedRecord = {
...updatedRecord,
inHome
};
} else {
updatedRecord = {
...updatedRecord,
caught,
haveToEvolve: needsToEvolve
};
}
return updatedRecord;
});
.map(({ pokedexEntry }) => ({
userId: localUser?.id || '',
pokedexId,
pokemonId: pokedexEntry._id,
...(inHome !== null ? { inHome } : { caught, haveToEvolve: needsToEvolve })
}));
// Optimistic patch: apply locally first.
for (const record of catchRecordsToUpdate) {
@@ -470,15 +598,25 @@
creatingRecords = false;
failedToLoad = false;
await getData({ page: currentPage, perPage: itemsPerPage });
await getData();
});
}
// Fetch data whenever pagination controls change (client-side only)
$: if (browser && pokedexId) getData({ page: currentPage, perPage: itemsPerPage });
let shownData: PageData | undefined;
$: if (data !== shownData) {
shownData = data;
localUser = data.user ?? null;
gridRequest++;
closePokemonModal();
detailCache.clear();
combinedData = data.grid ? unpackGrid(data.grid) : null;
failedToLoad = data.grid === null;
}
$: boxNumbers = calculateBoxNumbers(combinedData?.length ?? 0);
onMount(() => {
if (!browser) return;
userStoreReady = true;
nativeShareSupported = typeof navigator.share === 'function';
const flushKeepalive = () => {
@@ -491,7 +629,15 @@
if (document.visibilityState === 'hidden') flushKeepalive();
};
const onOnline = () => void catchWriteQueue?.flushNow();
online = navigator.onLine;
const onOffline = () => {
online = false;
};
const onOnline = () => {
online = true;
void catchWriteQueue?.flushNow();
};
window.addEventListener('offline', onOffline);
window.addEventListener('pagehide', flushKeepalive);
document.addEventListener('visibilitychange', onVisibilityChange);
@@ -502,18 +648,37 @@
if (!pokedexId) return;
if (creatingRecords) return;
if (catchWriteStatus.pending > 0 || catchWriteStatus.inFlight > 0) return;
void getData({ page: currentPage, perPage: itemsPerPage, setCombinedDataToNull: false });
void getData({ setCombinedDataToNull: false });
}, 60_000);
return () => {
window.removeEventListener('pagehide', flushKeepalive);
document.removeEventListener('visibilitychange', onVisibilityChange);
window.removeEventListener('online', onOnline);
window.removeEventListener('offline', onOffline);
window.clearInterval(reconcileInterval);
};
});
</script>
{#if reconnectToastLabels.length > 0}
<!-- Above DaisyUI's modal (z-index 999) so the alert stays usable over an open Pokémon dialog. -->
<div class="toast toast-end z-[1000]">
<div class="alert alert-warning" role="alert" data-testid="backup-reconnect-toast">
<span>
Backups to {reconnectToastLabels.join(' and ')} have stopped because access expired or was revoked.
</span>
<a class="btn btn-sm" href="/backup-settings">Reconnect</a>
<button
type="button"
class="btn btn-sm btn-ghost"
aria-label="Dismiss"
on:click={() => (reconnectToastLabels = [])}>✕</button
>
</div>
</div>
{/if}
<svelte:head>
<title>{pokedex ? `${pokedex.name} - Living Dex Tracker` : 'Pokédex - Living Dex Tracker'}</title>
</svelte:head>
@@ -694,7 +859,7 @@
<!-- Box View -->
<PokedexViewBoxes
{showShiny}
bind:combinedData
{combinedData}
bind:boxNumbers
bind:creatingRecords
{totalRecordsCreated}
@@ -705,22 +870,59 @@
{markBoxAsInHome}
{markBoxAsNotInHome}
{createCatchRecords}
onPokemonClick={openPokemonModal}
retryLoad={() => getData()}
virtualize={true}
gridKey={pokedexId}
initialLayout={data.boxViewLayout}
onPokemonClick={(row) => {
const own = combinedData?.find((entry) => entry.pokedexEntry._id === row.pokedexEntry._id);
if (own) void openPokemonModal(own);
}}
/>
</div>
{#if showModal && selectedPokemon}
{#if showModal && selectedSummary}
<PokedexModal isOpen={showModal} onClose={closePokemonModal}>
<PokedexEntryCatchRecord
pokedexEntry={selectedPokemon.pokedexEntry}
bind:catchRecord={selectedPokemon.catchRecord}
{showOrigins}
showForms={pokedex.isFormDex}
{showShiny}
userId={localUser?.id}
{pokedexId}
on:updateCatch={handleModalCatchUpdate}
/>
{#if selectedPokemon}
<PokedexEntryCatchRecord
pokedexEntry={selectedPokemon.pokedexEntry}
bind:catchRecord={selectedPokemon.catchRecord}
{showOrigins}
showForms={pokedex.isFormDex}
{showShiny}
userId={localUser?.id}
{pokedexId}
on:updateCatch={handleModalCatchUpdate}
readOnly={!online}
sharedCatchStatus={selectedPokemon.catchRecord}
/>
{#if !online && selectedPokemon.catchRecord?.personalNotes}<p class="p-6">
Notes: {selectedPokemon.catchRecord.personalNotes}
</p>{/if}
{:else}
<div class="p-6" aria-busy={!detailError}>
<h2 class="text-xl font-bold">{selectedSummary.pokedexEntry.pokemon}</h2>
<div class="w-64 h-64">
<PokemonSprite
pokemonName={selectedSummary.pokedexEntry.pokemon}
pokedexNumber={selectedSummary.pokedexEntry.pokedexNumber}
form={selectedSummary.pokedexEntry.form}
spriteKey={selectedSummary.pokedexEntry.spriteKey}
shiny={showShiny}
loadingStrategy="eager"
/>
</div>
{#if detailError}
<p role="alert">{detailError}</p>
<button
class="btn"
data-offline-action
on:click={() => selectedSummary && openPokemonModal(selectedSummary)}
>Retry details</button
>
{:else}<p role="status">Loading details…</p>{/if}
</div>
{/if}
</PokedexModal>
{/if}
+6 -1
View File
@@ -83,7 +83,12 @@
showShiny={shared.isShinyDex}
combinedData={shared.combinedData}
{boxNumbers}
onPokemonClick={handlePokemonClick}
onPokemonClick={(row) => {
const full = shared.combinedData.find(
(entry) => entry.pokedexEntry._id === row.pokedexEntry._id
);
if (full) handlePokemonClick(full);
}}
/>
</div>
+8 -19
View File
@@ -22,8 +22,12 @@
<div class="min-h-[calc(100vh-16rem)] bg-base-100 py-8 md:py-16 px-4 sm:px-6 lg:px-8">
<div class="max-w-6xl mx-auto">
<!-- Success Badge -->
{#if showSuccess}
<div class="flex justify-center mb-8 animate-fade-in">
<!-- Always rendered (faded in) so the hero doesn't jump down when the badge appears. -->
<div
class="flex justify-center mb-8 transition-opacity duration-500"
class:opacity-0={!showSuccess}
>
<div class="flex justify-center">
<div class="badge badge-success badge-lg gap-2 p-6 shadow-lg">
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -42,7 +46,7 @@
<span class="text-lg font-semibold">Account Created Successfully!</span>
</div>
</div>
{/if}
</div>
<!-- Hero Content -->
<div class="hero">
@@ -306,6 +310,7 @@
</svg>
<h4 class="font-semibold">Works Offline</h4>
<p class="text-sm opacity-70">Track your catches even without an internet connection</p>
<a href="/offline-guide" class="link link-primary text-sm">How to use offline</a>
</div>
</div>
</div>
@@ -314,21 +319,6 @@
</div>
<style>
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.animate-fade-in {
animation: fade-in 0.5s ease-out forwards;
}
@keyframes pulse {
0%,
100% {
@@ -345,7 +335,6 @@
/* Respect user's motion preferences */
@media (prefers-reduced-motion: reduce) {
.animate-fade-in,
.animate-pulse {
animation: none;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

+1 -1
View File
@@ -74,7 +74,7 @@ async function missingSprites(cache, root) {
// Covers both the local `/sprites-small/...` folder and the GitHub-hosted copy of it.
function isSpriteUrl(url) {
return /\/sprites(-small)?\//.test(url.pathname) && url.pathname.endsWith('.webp');
return /\/sprites(?:-small|-grid\/v1)?\//.test(url.pathname) && url.pathname.endsWith('.webp');
}
async function currentOfflineMeta() {
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 14 KiB

+1 -1
View File
@@ -10,7 +10,7 @@ const config = {
preprocess: vitePreprocess(),
kit: {
// Netlify by default, or the node adapter when NODE_ADAPTER=true. See adapter.mjs.
// Netlify by default; DEPLOY_TARGET selects the Cloudflare preview or Node test build.
adapter,
serviceWorker: {
// VitePWA owns registration. Registering here as well requests SvelteKit's default
+9 -4
View File
@@ -1,9 +1,9 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
'./src/routes/**/*.{svelte,js,ts}',
'./src/routes/**/**/*.{svelte,js,ts}',
'./src/lib/components/**/*.{svelte,js,ts}'
'./src/**/*.{html,svelte,js,ts}',
'./static/offline.html',
'./static/offline-viewer.js'
],
theme: {
extend: {}
@@ -16,11 +16,16 @@ export default {
'dracula',
{
pokeball: {
primary: '#ee1515',
// A slightly deeper Poké Ball red: #ee1515 gave white text only 4.3:1 contrast, below
// the WCAG AA 4.5:1 minimum that the Lighthouse accessibility gate checks.
primary: '#d31111',
'primary-content': '#ffffff',
secondary: '#ffd700',
'secondary-content': '#ffffff',
accent: '#3b82c4',
// daisyUI's default info blue is too light for text on the base colours.
info: '#0369a1',
'info-content': '#ffffff',
neutral: '#ffffff',
'base-100': '#f0f0f0',
'base-content': '#222224'
+26
View File
@@ -40,3 +40,29 @@ Feature: Backup and export
When I update collection progress
Then the catch remains marked caught
And the provider failure is shown in backup settings
And "Google Drive" is not flagged for reconnection
Scenario Outline: Warn when a provider's access is revoked
Given "<provider>" is connected with a revoked refresh token
When I update collection progress
Then the Pokédex page tells me to reconnect "<provider>"
And I can dismiss the reconnect alert
And backup settings asks me to reconnect "<provider>"
And other pages warn that my "<provider>" backup has stopped
And later exports do not retry the revoked token
Examples:
| provider |
| Google Drive |
| Dropbox |
Scenario Outline: Reconnecting clears a previous backup error
Given "<provider>" previously lost access
When I connect the mocked "<provider>" provider
Then "<provider>" is shown as connected
And the previous backup error is cleared
Examples:
| provider |
| Google Drive |
| Dropbox |
+19
View File
@@ -0,0 +1,19 @@
Feature: Signed-in page speed
As a trainer
I want my Pokédexes to open and switch quickly
So that tracking catches never feels sluggish
Lighthouse CI covers the public pages; these budgets cover the signed-in ones it can't reach.
Background:
Given I am signed in
And I have a Living Dex named "Speed Check"
Scenario: A Pokédex opens without a second round trip for its entries
When I load the Pokédex page directly
Then its entries appear within 5 seconds
And the browser did not request the grid separately
Scenario: Moving between my Pokédex list and a Pokédex is quick
When I switch between my Pokédex list and the Pokédex
Then each switch finishes within 3 seconds
+14
View File
@@ -26,6 +26,20 @@ Feature: Offline-friendly application
When I go offline and reload the current Pokédex
Then the offline copy contains "Offline Collection"
Scenario: Explain offline use on the offline guide
Given I am signed in
When I open the offline guide
Then the offline guide shows my offline copy status
Scenario: Keep offline sync status off everyday pages
Given I am signed in
And I have a Living Dex named "Quiet Offline"
And my offline copy is synchronized
When I open the offline guide from the user menu
Then the offline guide shows when my offline copy was updated
When I return to my Pokédexes from the user menu
Then no offline sync status is shown
Scenario: Restore network access
Given I have opened the built application online
When I go offline and then return online
+2 -2
View File
@@ -81,7 +81,7 @@ When('I visit the public home page', async ({ page }) => {
});
When('I sign out', async ({ page }) => {
await page.getByRole('button', { name: 'usericon' }).click();
await page.getByRole('button', { name: 'Account menu' }).click();
await page.getByRole('button', { name: 'Sign Out', exact: true }).click();
});
@@ -93,7 +93,7 @@ When('the sign-out request fails', async ({ page }) => {
body: '{"message":"unavailable"}'
})
);
await page.getByRole('button', { name: 'usericon' }).click();
await page.getByRole('button', { name: 'Account menu' }).click();
await page.getByRole('button', { name: 'Sign Out', exact: true }).click();
});
+100 -1
View File
@@ -12,6 +12,17 @@ const SUPABASE_URL = requireLoopbackUrl(
type Provider = 'google_drive' | 'dropbox';
// Outside CI Playwright reuses an already-running mock, which may predate a new control route.
// Fail loudly then, rather than letting the scenario run against the wrong mock behaviour.
async function mockControl(route: string) {
const response = await fetch(`${MOCK_URL}/__mock/${route}`);
if (!response.ok) {
throw new Error(
`Mock provider rejected /__mock/${route} (${response.status}). Stop any stale mock on port 4199 and rerun.`
);
}
}
async function seedIntegration(
state: import('../fixtures').ScenarioState,
provider: Provider,
@@ -67,10 +78,36 @@ Given('Dropbox is connected with an expired token', async ({ page, state }) => {
Given('Google Drive is connected to a failing mocked provider', async ({ page, state }) => {
await seedIntegration(state, 'google_drive');
await fetch(`${MOCK_URL}/__mock/fail-uploads`);
await mockControl('fail-uploads');
await ensureExportDex(page, state);
});
const PROVIDERS: Record<string, Provider> = { 'Google Drive': 'google_drive', Dropbox: 'dropbox' };
function providerFor(label: string): Provider {
const provider = PROVIDERS[label];
if (!provider) throw new Error(`Unknown backup provider "${label}"`);
return provider;
}
Given(
'{string} is connected with a revoked refresh token',
async ({ page, state }, label: string) => {
await seedIntegration(state, providerFor(label), {
accessTokenExpiresAt: new Date(Date.now() - 60_000).toISOString()
});
await mockControl('revoke-refresh');
await ensureExportDex(page, state);
}
);
Given('{string} previously lost access', async ({ state }, label: string) => {
await seedIntegration(state, providerFor(label), {
enabled: false,
lastError: `${label} access has expired or was revoked. Reconnect ${label} to resume backups.`
});
});
When('I visit backup settings', async ({ page }) => {
await page.goto('/backup-settings');
});
@@ -182,3 +219,65 @@ Then('the provider failure is shown in backup settings', async ({ page }) => {
await page.goto('/backup-settings');
await expect(page.getByText(/mock upload failure/)).toBeVisible();
});
Then('the Pokédex page tells me to reconnect {string}', async ({ page }, label: string) => {
const toast = page.getByTestId('backup-reconnect-toast');
await expect(toast).toBeVisible({ timeout: 15_000 });
await expect(toast).toContainText(label);
await expect(toast.getByRole('link', { name: 'Reconnect' })).toHaveAttribute(
'href',
'/backup-settings'
);
});
Then('I can dismiss the reconnect alert', async ({ page }) => {
await page.getByTestId('backup-reconnect-toast').getByRole('button', { name: 'Dismiss' }).click();
await expect(page.getByTestId('backup-reconnect-toast')).toHaveCount(0);
// Dismissing the one-off alert must not hide the standing sitewide warning.
await expect(page.getByTestId('backup-reconnect-banner')).toBeVisible();
});
Then('backup settings asks me to reconnect {string}', async ({ page }, label: string) => {
await page.goto('/backup-settings');
const card = page.locator('.border').filter({ hasText: label });
await expect(card.getByText('Reconnect needed', { exact: true })).toBeVisible();
await expect(card.getByText(/access has expired or was revoked/)).toBeVisible();
// The settings page already explains the problem, so the sitewide banner stays out of the way.
await expect(page.getByTestId('backup-reconnect-banner')).toHaveCount(0);
});
Then('other pages warn that my {string} backup has stopped', async ({ page }, label: string) => {
await page.goto('/my-pokedexes');
const banner = page.getByTestId('backup-reconnect-banner');
await expect(banner).toBeVisible();
await expect(banner).toContainText(label);
await expect(banner.getByRole('link', { name: 'Reconnect' })).toHaveAttribute(
'href',
'/backup-settings'
);
});
Then('{string} is not flagged for reconnection', async ({ page, state }, label: string) => {
await page.goto('/backup-settings');
const card = page.locator('.border').filter({ hasText: label });
await expect(card.getByText('Connected', { exact: true })).toBeVisible();
await page.goto('/my-pokedexes');
await expect(page.getByTestId('backup-reconnect-banner')).toHaveCount(0);
// A transient upload failure leaves the integration enabled, so the next export still tries it.
const response = await page.request.post(`/api/pokedexes/${state.pokedexId}/export`);
expect(await response.json()).toMatchObject({ attempted: 1 });
});
Then('later exports do not retry the revoked token', async ({ page, state }) => {
const before = (await mockState()).refreshes;
const response = await page.request.post(`/api/pokedexes/${state.pokedexId}/export`);
expect(response.status()).toBe(200);
expect(await response.json()).toMatchObject({ attempted: 0 });
expect((await mockState()).refreshes).toBe(before);
});
Then('the previous backup error is cleared', async ({ page }) => {
await expect(page.getByText(/access has expired or was revoked/)).toHaveCount(0);
await page.goto('/my-pokedexes');
await expect(page.getByTestId('backup-reconnect-banner')).toHaveCount(0);
});
+78
View File
@@ -0,0 +1,78 @@
import { createBdd } from 'playwright-bdd';
import type { Page } from '@playwright/test';
import { test, expect } from '../fixtures';
const { When, Then } = createBdd(test);
// Per-page scratch values; scenarios run one at a time (workers: 1).
const timings = new WeakMap<
Page,
{ entriesMs?: number; switchMs: number[]; entryRequests: number }
>();
function entriesVisible(page: Page) {
return expect(page.getByRole('button', { name: /^View details for / }).first()).toBeVisible({
timeout: 30_000
});
}
When('I load the Pokédex page directly', async ({ page, state }) => {
if (!state.pokedexId) throw new Error('A Pokédex must exist before it can be opened');
const record = { switchMs: [], entryRequests: 0 };
timings.set(page, record);
// Only requests made while the page first loads matter; the page's 60s reconciliation refetch
// can't fire within this window.
const countEntryRequests = (request: { url(): string }) => {
if (/\/api\/pokedexes\/[^/]+\/(?:grid|combined-data)/.test(request.url()))
record.entryRequests++;
};
page.on('request', countEntryRequests);
const started = Date.now();
await page.goto(`/pokedex/${state.pokedexId}`);
await entriesVisible(page);
(record as { entriesMs?: number }).entriesMs = Date.now() - started;
page.off('request', countEntryRequests);
});
Then('its entries appear within {int} seconds', async ({ page }, seconds: number) => {
const entriesMs = timings.get(page)?.entriesMs;
expect(entriesMs, 'entries never became visible').toBeDefined();
expect(entriesMs!).toBeLessThan(seconds * 1000);
});
Then('the browser did not request the grid separately', async ({ page }) => {
// The server load includes the compact grid with the HTML, so the page must not make
// the old hydrate-then-fetch round trip.
expect(timings.get(page)?.entryRequests).toBe(0);
});
When('I switch between my Pokédex list and the Pokédex', async ({ page, state }) => {
if (!state.pokedexName) throw new Error('A Pokédex must exist before switching to it');
const record = { switchMs: [] as number[], entryRequests: 0 };
timings.set(page, record);
await page.goto('/my-pokedexes');
const card = page.locator('.card').filter({ hasText: state.pokedexName }).first();
await expect(card).toBeVisible();
for (let round = 0; round < 2; round++) {
// List -> Pokédex: a client-side navigation through the card's View button.
let started = Date.now();
await card.getByRole('button', { name: 'View', exact: true }).click();
await page.waitForURL('**/pokedex/**');
await entriesVisible(page);
record.switchMs.push(Date.now() - started);
// Pokédex -> list: back navigation is also handled by the client router.
started = Date.now();
await page.goBack();
await expect(card).toBeVisible();
record.switchMs.push(Date.now() - started);
}
});
Then('each switch finishes within {int} seconds', async ({ page }, seconds: number) => {
const switchMs = timings.get(page)?.switchMs ?? [];
expect(switchMs).toHaveLength(4);
for (const ms of switchMs) expect(ms).toBeLessThan(seconds * 1000);
});
+37
View File
@@ -104,6 +104,23 @@ When('I go offline and reload the current Pokédex', async ({ page, state }) =>
});
});
When('I open the offline guide', async ({ page }) => {
await page.goto('/offline-guide');
});
When('I open the offline guide from the user menu', async ({ page }) => {
await page.getByRole('button', { name: 'Account menu' }).click();
await page.getByRole('link', { name: 'Using Offline' }).click();
await page.waitForURL(/\/offline-guide$/);
});
// Client-side navigation keeps the sync status in memory, so the old layout would show it at once.
When('I return to my Pokédexes from the user menu', async ({ page }) => {
await page.getByRole('button', { name: 'Account menu' }).click();
await page.getByRole('link', { name: 'My Pokédexes' }).click();
await page.waitForURL(/\/my-pokedexes$/);
});
When('I go offline and then return online', async ({ page }) => {
await page.context().setOffline(true);
await page.reload({ waitUntil: 'domcontentloaded' });
@@ -167,6 +184,26 @@ Then('the application remains available', async ({ page }) => {
await expect(page.getByRole('heading', { name: /Start Your Pokédex Journey/ })).toBeVisible();
});
Then('the offline guide shows my offline copy status', async ({ page }) => {
await expect(
page.getByRole('heading', { name: 'Using Living Dex Tracker offline' })
).toBeVisible();
await expect(page.getByTestId('offline-copy-status')).toBeVisible();
});
Then('the offline guide shows when my offline copy was updated', async ({ page }) => {
await expect(page.getByTestId('offline-copy-status')).toContainText(/Offline copy updated/, {
timeout: 30_000
});
});
Then('no offline sync status is shown', async ({ page }) => {
await expect(page.getByRole('heading', { name: /My Pok/ }).first()).toBeVisible();
await expect(
page.getByText(/Offline copy updated|Updating offline copy|Save all artwork for offline/)
).toHaveCount(0);
});
Then('the read-only offline viewer is available', async ({ page }) => {
await expect(page.getByText(/offline.*read-only/i)).toBeVisible();
});
+42 -1
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import { existsSync, readFileSync } from 'node:fs';
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { gzipSync } from 'node:zlib';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { generateSW } from '../../pwa.mjs';
@@ -44,4 +45,44 @@ describe(`test-build: ${nodeAdapter ? 'node' : 'static'} adapter`, () => {
expect(match === null, 'found server/ entries in sw precache manifest').toBeTruthy();
}
});
const outputRoot = `./build/${nodeAdapter ? 'client/' : ''}`;
const nodesDir = './.svelte-kit/output/server/nodes/';
const gzippedSize = (path: string) => gzipSync(readFileSync(`${outputRoot}${path}`)).length;
/** The client files a route node makes the browser load (its imports and stylesheets). */
function assetsLoadedBy(node: string, extension: 'js' | 'css'): string[] {
const pattern = new RegExp(`_app/immutable/[^"']+\\.${extension}`, 'g');
return [...new Set(readFileSync(`${nodesDir}${node}`, 'utf-8').match(pattern) ?? [])];
}
it('ships the app stylesheet once, hashed and small', () => {
const referenced = new Set(
readdirSync(nodesDir).flatMap((node) => assetsLoadedBy(node, 'css'))
);
// Every page loads Tailwind's preflight; exactly one served stylesheet may contain it.
const withPreflight = [...referenced].filter((path) =>
readFileSync(`${outputRoot}${path}`, 'utf-8').includes('--tw-content')
);
expect(withPreflight, 'Tailwind is bundled more than once').toHaveLength(1);
// The un-hashed output.css exists only for offline.html; pages must not block on it.
const appHtml = readFileSync('./src/app.html', 'utf-8');
expect(appHtml).not.toMatch(/output\.css/);
});
// Regression budgets for what every page downloads before it can render: the root layout's
// scripts and stylesheets. Unlike Lighthouse timings these sizes don't vary between runs, so any
// growth past the budget fails the PR. Measured September 2026: 95.7 KB JS and 15.7 KB CSS
// gzipped. Raise a budget in the same PR only when the extra weight is deliberate.
it.each([
['js', 105 * 1024],
['css', 18 * 1024]
] as const)('keeps the layout %s loaded on every page within budget', (extension, budget) => {
const total = assetsLoadedBy('0.js', extension).reduce(
(sum, path) => sum + gzippedSize(path),
0
);
expect(total, `layout ${extension} is ${total} bytes gzipped`).toBeLessThan(budget);
});
});
@@ -0,0 +1,132 @@
import { packGrid, unpackGrid } from '$lib/models/PokedexGridRow';
import { createClient, type SupabaseClient } from '@supabase/supabase-js';
import { beforeAll, afterAll, describe, expect, it } from 'vitest';
import { requireLoopbackUrl } from '../support/loopback';
import PokedexRepository from '$lib/repositories/PokedexRepository';
import CombinedDataRepository from '$lib/repositories/CombinedDataRepository';
import CatchRecordRepository from '$lib/repositories/CatchRecordRepository';
import { loadPokedexGrid, loadPokedexEntryDetail } from '$lib/services/PokedexGridService';
import type { Pokedex } from '$lib/models/Pokedex';
const url = requireLoopbackUrl(
process.env.TEST_SUPABASE_URL ?? 'http://127.0.0.1:54321',
'TEST_SUPABASE_URL'
);
const serviceKey = process.env.E2E_SERVICE_ROLE_KEY ?? process.env.SUPABASE_SERVICE_ROLE_KEY;
const anonKey = process.env.TEST_SUPABASE_ANON_KEY;
describe('compact Pokédex and partial catch writes', () => {
let admin: SupabaseClient;
let client: SupabaseClient;
let owner = '';
let national: Pokedex;
let scoped: Pokedex;
let firstId: string;
let secondId: string;
beforeAll(async () => {
if (!serviceKey || !anonKey) throw new Error('Use npm run test:integration');
admin = createClient(url, serviceKey, { auth: { persistSession: false } });
const email = `grid-${crypto.randomUUID()}@example.test`;
const password = crypto.randomUUID();
const created = await admin.auth.admin.createUser({ email, password, email_confirm: true });
if (created.error) throw created.error;
owner = created.data.user.id;
client = createClient(url, anonKey, { auth: { persistSession: false } });
const signed = await client.auth.signInWithPassword({ email, password });
if (signed.error) throw signed.error;
const repo = new PokedexRepository(client, owner);
national = await repo.create({ name: 'Grid national', isFormDex: false });
scoped = await repo.create({ name: 'Grid forms', isFormDex: true, gameScope: 'Scarlet' });
const links = await client
.from('pokedex_dex_scopes')
.insert({ pokedexId: scoped._id, dexId: 'scarlet-paldea' });
if (links.error) throw links.error;
scoped = (await repo.findById(scoped._id))!;
const grid = await loadPokedexGrid(client, owner, national);
[firstId, secondId] = grid.slice(0, 2).map((row) => row.pokedexEntry._id);
});
afterAll(async () => {
if (owner) await admin.auth.admin.deleteUser(owner);
});
it('loads saved scopes with ownership and prevents cross-account reads', async () => {
expect(scoped.dexScopes).toEqual(['scarlet-paldea']);
const other = new PokedexRepository(client, crypto.randomUUID());
expect(await other.findById(scoped._id)).toBeNull();
});
it('matches full ordering and statuses while reducing serialized rows by at least 60%', async () => {
for (const dex of [national, scoped]) {
const initial = await loadPokedexGrid(client, owner, dex);
const catches = new CatchRecordRepository(client, owner, dex._id);
for (let offset = 0; offset < initial.length - 1; offset += 500)
await catches.bulkUpsert(
initial.slice(offset, Math.min(offset + 500, initial.length - 1)).map((row, index) => ({
pokemonId: row.pokedexEntry._id,
caught: index % 3 === 0,
inHome: index % 7 === 0,
personalNotes: ''
}))
);
const grid = await loadPokedexGrid(client, owner, dex);
const full = await new CombinedDataRepository(client, owner, dex._id).findAllCombinedData(
owner,
dex.isFormDex,
'',
dex.gameScope || '',
dex.dexScopes
);
expect(grid.map((row) => row.pokedexEntry._id)).toEqual(
full.map((row) => row.pokedexEntry._id)
);
expect(grid.length).toBeGreaterThan(400);
expect(unpackGrid(packGrid(grid))).toEqual(grid);
expect(JSON.stringify(packGrid(grid)).length).toBeLessThan(JSON.stringify(full).length * 0.4);
expect(JSON.stringify(grid)).not.toContain('personalNotes');
expect(JSON.stringify(grid)).not.toContain('catchInformation');
}
});
it('preserves omitted notes and statuses in mixed partial bulk writes, including new records', async () => {
const repo = new CatchRecordRepository(client, owner, national._id);
await repo.bulkUpsert([
{ pokemonId: firstId, personalNotes: 'Keep this note', caught: true, inHome: true }
]);
await repo.bulkUpsert([
{ pokemonId: firstId, haveToEvolve: true, caught: false },
{ pokemonId: secondId, personalNotes: 'New record' }
]);
expect(await repo.findByUserAndPokemon(owner, firstId, national._id)).toMatchObject({
personalNotes: 'Keep this note',
caught: false,
haveToEvolve: true,
inHome: true
});
expect(await repo.findByUserAndPokemon(owner, secondId, national._id)).toMatchObject({
personalNotes: 'New record',
caught: false
});
await repo.bulkUpsert([{ pokemonId: firstId, personalNotes: '' }]);
expect(await repo.findByUserAndPokemon(owner, firstId, national._id)).toMatchObject({
personalNotes: '',
inHome: true,
haveToEvolve: true
});
});
it('returns full details only for members of this dex', async () => {
const detail = await loadPokedexEntryDetail(client, owner, national, Number(firstId));
expect(detail?.pokedexEntry).toHaveProperty('catchInformation');
expect(detail?.catchRecord).toHaveProperty('personalNotes');
expect(await loadPokedexEntryDetail(client, owner, national, 999999)).toBeNull();
const forms = await loadPokedexGrid(client, owner, scoped);
const base = new Set(
(await loadPokedexGrid(client, owner, national)).map((row) => row.pokedexEntry._id)
);
const formOnly = forms.find((row) => !base.has(row.pokedexEntry._id));
expect(formOnly).toBeDefined();
expect(
await loadPokedexEntryDetail(client, owner, national, Number(formOnly!.pokedexEntry._id))
).toBeNull();
});
});
+187
View File
@@ -0,0 +1,187 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { get } from 'svelte/store';
import {
backupsNeedingReconnect,
clearBackupStatus,
markReconnectNeeded,
refreshBackupStatus,
setBackupStatus
} from '$lib/stores/backupStatus';
describe('backup reconnect status', () => {
beforeEach(() => clearBackupStatus());
it('lists only the providers that exports switched off', () => {
setBackupStatus([
{ provider: 'google_drive', enabled: false },
{ provider: 'dropbox', enabled: true }
]);
expect(get(backupsNeedingReconnect)).toEqual(['google_drive']);
});
it('adds newly revoked providers without duplicating known ones', () => {
markReconnectNeeded(['google_drive']);
markReconnectNeeded(['google_drive', 'dropbox']);
expect(get(backupsNeedingReconnect)).toEqual(['google_drive', 'dropbox']);
});
it('clears everything, e.g. on sign-out', () => {
markReconnectNeeded(['dropbox']);
clearBackupStatus();
expect(get(backupsNeedingReconnect)).toEqual([]);
});
});
describe('refreshBackupStatus', () => {
const fetchMock = vi.fn();
beforeEach(() => {
clearBackupStatus();
fetchMock.mockReset();
vi.stubGlobal('fetch', fetchMock);
vi.stubGlobal('window', {});
vi.stubGlobal('navigator', { onLine: true });
});
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
it('loads the paused providers from the integrations API', async () => {
fetchMock.mockResolvedValue(
new Response(
JSON.stringify([
{ provider: 'google_drive', enabled: true },
{ provider: 'dropbox', enabled: false }
])
)
);
await refreshBackupStatus();
expect(fetchMock).toHaveBeenCalledWith('/api/export-integrations', {
credentials: 'include'
});
expect(get(backupsNeedingReconnect)).toEqual(['dropbox']);
});
it('clears a stale warning once the provider has been reconnected', async () => {
markReconnectNeeded(['google_drive']);
fetchMock.mockResolvedValue(
new Response(JSON.stringify([{ provider: 'google_drive', enabled: true }]))
);
await refreshBackupStatus();
expect(get(backupsNeedingReconnect)).toEqual([]);
});
it('does nothing while offline', async () => {
vi.stubGlobal('navigator', { onLine: false });
markReconnectNeeded(['google_drive']);
await refreshBackupStatus();
expect(fetchMock).not.toHaveBeenCalled();
expect(get(backupsNeedingReconnect)).toEqual(['google_drive']);
});
it('does nothing during server rendering', async () => {
vi.stubGlobal('window', undefined);
await refreshBackupStatus();
expect(fetchMock).not.toHaveBeenCalled();
});
it('keeps the last known status when the API rejects the request', async () => {
markReconnectNeeded(['google_drive']);
fetchMock.mockResolvedValue(new Response('Unauthorized', { status: 401 }));
await refreshBackupStatus();
expect(get(backupsNeedingReconnect)).toEqual(['google_drive']);
});
function deferredResponse() {
let resolve!: (response: Response) => void;
const promise = new Promise<Response>((r) => (resolve = r));
return { promise, resolve };
}
const json = (body: unknown) => new Response(JSON.stringify(body));
it('coalesces concurrent refreshes for the same account state', async () => {
const slow = deferredResponse();
fetchMock.mockReturnValueOnce(slow.promise);
const first = refreshBackupStatus();
const second = refreshBackupStatus();
expect(second).toBe(first);
expect(fetchMock).toHaveBeenCalledTimes(1);
slow.resolve(json([]));
await Promise.all([first, second]);
});
it('ignores a response overtaken by a new account refresh', async () => {
const slow = deferredResponse();
fetchMock
.mockReturnValueOnce(slow.promise)
.mockResolvedValueOnce(json([{ provider: 'google_drive', enabled: true }]));
const first = refreshBackupStatus();
clearBackupStatus();
await refreshBackupStatus();
slow.resolve(json([{ provider: 'google_drive', enabled: false }]));
await first;
expect(get(backupsNeedingReconnect)).toEqual([]);
});
it('ignores a response that arrives after the status was flagged directly', async () => {
const slow = deferredResponse();
fetchMock.mockReturnValueOnce(slow.promise);
const pending = refreshBackupStatus();
markReconnectNeeded(['dropbox']);
slow.resolve(json([{ provider: 'dropbox', enabled: true }]));
await pending;
expect(get(backupsNeedingReconnect)).toEqual(['dropbox']);
});
it('ignores a response that arrives after the status was cleared', async () => {
const slow = deferredResponse();
fetchMock.mockReturnValueOnce(slow.promise);
const pending = refreshBackupStatus();
clearBackupStatus();
slow.resolve(json([{ provider: 'google_drive', enabled: false }]));
await pending;
expect(get(backupsNeedingReconnect)).toEqual([]);
});
it('ignores a response that arrives after the status was set from another source', async () => {
const slow = deferredResponse();
fetchMock.mockReturnValueOnce(slow.promise);
const pending = refreshBackupStatus();
setBackupStatus([{ provider: 'google_drive', enabled: true }]);
slow.resolve(json([{ provider: 'google_drive', enabled: false }]));
await pending;
expect(get(backupsNeedingReconnect)).toEqual([]);
});
it('keeps the last known status when the request fails', async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
markReconnectNeeded(['dropbox']);
fetchMock.mockRejectedValue(new TypeError('Failed to fetch'));
await refreshBackupStatus();
expect(get(backupsNeedingReconnect)).toEqual(['dropbox']);
expect(consoleError).toHaveBeenCalled();
});
});
+36
View File
@@ -28,6 +28,27 @@ describe('createCatchRecordWriteQueue()', () => {
vi.unstubAllGlobals();
});
it('merges partial notes/status patches without inventing omitted fields', async () => {
const fetchFn = vi.fn(async () => new Response('[]'));
const queue = createCatchRecordWriteQueue({ endpointUrl: '/api/catches', fetchFn });
const identity = { userId: 'u', pokedexId: 'd', pokemonId: '1' };
queue.enqueue({ ...identity, personalNotes: 'Keep' }, { flushSoon: false });
queue.enqueue({ ...identity, inHome: true }, { flushSoon: false });
expect(queue.getPendingPatch('1')).toEqual({
...identity,
personalNotes: 'Keep',
inHome: true
});
await queue.flushNow();
const payload = JSON.parse(
String((fetchFn.mock.calls[0] as unknown as [string, RequestInit])[1].body)
);
expect(payload).toEqual([{ ...identity, personalNotes: 'Keep', inHome: true }]);
queue.enqueue({ ...identity, personalNotes: '' }, { flushSoon: false });
expect(queue.getPendingPatch('1')?.personalNotes).toBe('');
await queue.flushNow();
});
it('coalesces multiple updates for the same key and flushes only the latest state', async () => {
const fetchFn = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
return new Response(init?.body as string, { status: 200 });
@@ -141,6 +162,21 @@ describe('createCatchRecordWriteQueue()', () => {
expect(queue.getPendingCount()).toBe(1);
});
it('discards queued edits after the owning account changes', async () => {
const fetchFn = vi.fn<typeof fetch>();
let current = true;
const queue = createCatchRecordWriteQueue({
endpointUrl: '/catch-records',
fetchFn,
isCurrentUser: () => current
});
queue.enqueue(mkRecord(), { debounceMs: 100, flushSoon: false });
current = false;
await queue.flushNow();
expect(fetchFn).not.toHaveBeenCalled();
expect(queue.getPendingCount()).toBe(0);
});
it('does not discard a newer version enqueued during an in-flight request', async () => {
let resolveFirst: ((response: Response) => void) | undefined;
const firstResponse = new Promise<Response>((resolve) => (resolveFirst = resolve));
+122 -3
View File
@@ -11,7 +11,9 @@ type TableQuery = { table: string; calls: Call[] };
* `await query` / `await query.range(...)` resolve like a real PostgREST response. Returning
* an empty data set keeps the repository's paging loops to a single iteration.
*/
function createSupabaseStub() {
function createSupabaseStub(
resultFor: (table: string) => unknown = () => ({ data: [], error: null, count: 0 })
) {
const queries: TableQuery[] = [];
const from = (table: string) => {
@@ -23,8 +25,7 @@ function createSupabaseStub() {
{
get(_target, prop: string) {
if (prop === 'then') {
return (resolve: (value: unknown) => unknown) =>
resolve({ data: [], error: null, count: 0 });
return (resolve: (value: unknown) => unknown) => resolve(resultFor(table));
}
return (...args: unknown[]) => {
record.calls.push({ method: prop, args });
@@ -115,3 +116,121 @@ describe('CombinedDataRepository base-form filtering', () => {
expect(mentionsIsDefaultForm(supplement)).toBe(false);
});
});
describe('compact grid reads', () => {
const entry = {
id: 1,
pokedexNumber: 1,
pokemon: 'Bulbasaur',
form: null,
spriteKey: '1',
canGigantamax: false
};
it('joins catch flags by ID and retains entries without catches', async () => {
const { supabase } = createSupabaseStub((table) => ({
data:
table === 'catch_records'
? [{ id: 'catch', pokemonId: 1, caught: true, personalNotes: 'private' }]
: [entry, { ...entry, id: 2 }],
error: null
}));
const repo = new CombinedDataRepository(supabase, 'owner', 'dex', true);
const rows = await repo.joinGridCatches(await repo.findGridEntries(false, '', []));
expect(rows[0].catchRecord).toMatchObject({ _id: 'catch', caught: true });
expect(rows[0].catchRecord).not.toHaveProperty('personalNotes');
expect(rows[1].catchRecord).toBeNull();
});
it('deduplicates overlapping scopes without dropping named form supplements', async () => {
const base = { ...entry, pokemon: 'Rotom', form: 'Lightbulb', dexNumber: 1, dexSortOrder: 1 };
const { supabase } = createSupabaseStub((table) => ({
data:
table === 'game_pokedex_entry_details' ? [base, base] : [{ ...base, id: 2, form: 'Heat' }],
error: null
}));
const repo = new CombinedDataRepository(supabase, 'owner', 'dex', true);
const rows = await repo.findGridEntries(true, 'Black', ['one', 'two']);
expect(rows.map((row) => [row.id, row.form])).toEqual([
[1, 'Lightbulb'],
[2, 'Heat']
]);
});
it.each([[[]], [['scope']]])(
'reports entry query failure instead of an empty grid (%j)',
async (scopes) => {
const { supabase } = createSupabaseStub(() => ({
data: null,
error: { message: 'unavailable' }
}));
const repo = new CombinedDataRepository(supabase, 'owner', 'dex', true);
await expect(repo.findGridEntries(false, '', scopes)).rejects.toThrow('Unable to load');
}
);
it('reports catch failure instead of displaying everything as uncaught', async () => {
const { supabase } = createSupabaseStub((table) =>
table === 'catch_records'
? { data: null, error: { message: 'unavailable' } }
: { data: [entry], error: null }
);
const repo = new CombinedDataRepository(supabase, 'owner', 'dex', true);
await expect(repo.joinGridCatches(await repo.findGridEntries(false, '', []))).rejects.toThrow(
'Unable to load catch records'
);
});
it('keeps a failed detail read distinct from a missing entry', async () => {
const missing = createSupabaseStub(() => ({ data: null, error: null }));
expect(
await new CombinedDataRepository(missing.supabase, 'owner', 'dex').findEntryDetail(1)
).toBeNull();
const failed = createSupabaseStub(() => ({ data: null, error: { message: 'unavailable' } }));
await expect(
new CombinedDataRepository(failed.supabase, 'owner', 'dex').findEntryDetail(1)
).rejects.toThrow('Unable to load entry details');
});
it.each([false, true])(
'returns full instructions with optional catch notes (caught: %s)',
async (caught) => {
const { supabase } = createSupabaseStub((table) => ({
data:
table === 'catch_records'
? caught
? [
{
id: 'catch',
pokemonId: 1,
userId: 'owner',
pokedexId: 'dex',
personalNotes: 'Saved note'
}
]
: []
: { ...entry, catchInformation: 'Full instructions' },
error: null
}));
const result = await new CombinedDataRepository(supabase, 'owner', 'dex').findEntryDetail(1);
expect(result?.pokedexEntry.catchInformation).toBe('Full instructions');
if (caught) expect(result?.catchRecord?.personalNotes).toBe('Saved note');
else expect(result?.catchRecord).toBeNull();
}
);
it('shares a scoped read between simultaneous rows and count requests', async () => {
const { supabase, queries } = createSupabaseStub();
const repo = new CombinedDataRepository(supabase, 'owner', 'dex');
await Promise.all([
repo.findCombinedData('owner', 1, 30, true, '', 'Scarlet', ['scarlet-paldea']),
repo.countCombinedData(true, '', 'Scarlet', ['scarlet-paldea'])
]);
expect(queryFor(queries, 'game_pokedex_entry_details')).toHaveLength(1);
expect(queryFor(queries, 'pokedex_entries')).toHaveLength(1);
});
it('selects compact columns and does not count the full grid', async () => {
const { supabase, queries } = createSupabaseStub();
const repo = new CombinedDataRepository(supabase, 'owner', 'dex', true);
await repo.joinGridCatches(await repo.findGridEntries(false, '', []));
expect(queries).toHaveLength(1);
const selection = queries[0].calls.find((call) => call.method === 'select');
expect(selection?.args[0]).not.toContain('*');
expect(selection?.args[0]).not.toContain('notes');
expect(selection?.args[0]).not.toContain('Information');
expect(selection?.args).toHaveLength(1);
});
});
+77
View File
@@ -0,0 +1,77 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { Pokedex } from '$lib/models/Pokedex';
const findCombinedData = vi.fn();
const countCombinedData = vi.fn();
const constructed: unknown[][] = [];
vi.mock('$lib/repositories/CombinedDataRepository', () => ({
default: class {
constructor(...args: unknown[]) {
constructed.push(args);
}
findCombinedData = findCombinedData;
countCombinedData = countCombinedData;
}
}));
vi.mock('$lib/services/PokedexDexScopeService', () => ({
resolveDexScopes: vi.fn(async () => ['national'])
}));
const { loadCombinedDataPage } = await import('$lib/services/CombinedDataService');
const supabase = {} as never;
const pokedex = { _id: 'dex-1', gameScope: 'Black' } as unknown as Pokedex;
describe('loadCombinedDataPage', () => {
beforeEach(() => {
constructed.length = 0;
findCombinedData.mockReset().mockResolvedValue([{ id: 'row' }]);
countCombinedData.mockReset().mockResolvedValue(45);
});
it("defaults to the Pokédex's game scope and reports pagination", async () => {
const result = await loadCombinedDataPage(supabase, 'user-1', pokedex, {
page: 2,
limit: 20,
enableForms: true
});
expect(constructed).toEqual([[supabase, 'user-1', 'dex-1']]);
expect(findCombinedData).toHaveBeenCalledWith('user-1', 2, 20, true, '', 'Black', ['national']);
expect(countCombinedData).toHaveBeenCalledWith(true, '', 'Black', ['national']);
expect(result).toEqual({
combinedData: [{ id: 'row' }],
totalPages: 3,
currentPage: 2,
totalCount: 45
});
});
it('prefers an explicit game and region filter', async () => {
await loadCombinedDataPage(supabase, 'user-1', pokedex, {
page: 1,
limit: 9999,
enableForms: false,
region: 'unova',
game: 'White'
});
expect(countCombinedData).toHaveBeenCalledWith(false, 'unova', 'White', ['national']);
});
it('runs the rows and count queries at the same time', async () => {
let releaseRows: (rows: unknown[]) => void = () => {};
findCombinedData.mockReturnValue(new Promise((resolve) => (releaseRows = resolve)));
const pending = loadCombinedDataPage(supabase, 'user-1', pokedex, {
page: 1,
limit: 10,
enableForms: false
});
// The count starts before the rows query has finished.
await vi.waitFor(() => expect(countCombinedData).toHaveBeenCalled());
releaseRows([]);
await expect(pending).resolves.toMatchObject({ totalCount: 45, totalPages: 5 });
});
});
+129
View File
@@ -0,0 +1,129 @@
import { describe, expect, it } from 'vitest';
import { brotliDecompressSync, gunzipSync } from 'node:zlib';
import { compressResponse, pickEncoding } from '$lib/server/compression';
const html = '<!doctype html><p>' + 'Living Dex '.repeat(500) + '</p>';
function request(acceptEncoding?: string, method = 'GET') {
return new Request('http://localhost/', {
method,
headers: acceptEncoding ? { 'accept-encoding': acceptEncoding } : {}
});
}
function page(body: BodyInit | null = html, init: ResponseInit = {}) {
return new Response(body, {
status: 200,
headers: { 'content-type': 'text/html; charset=utf-8', 'content-length': '999' },
...init
});
}
async function bytes(response: Response) {
return Buffer.from(await response.arrayBuffer());
}
describe('pickEncoding', () => {
it.each([
['gzip, deflate, br', 'br'],
['gzip', 'gzip'],
['br;q=0, gzip', 'gzip'],
['*', 'br'],
['identity', null],
['gzip;q=0', null]
])('%s -> %s', (header, expected) => {
expect(pickEncoding(header)).toBe(expected);
});
it('returns null when the client sends no Accept-Encoding', () => {
expect(pickEncoding(null)).toBeNull();
});
});
describe('compressResponse', () => {
it('brotli-compresses HTML and the body round-trips', async () => {
const response = compressResponse(request('gzip, br'), page());
expect(response.headers.get('content-encoding')).toBe('br');
expect(response.headers.get('content-length')).toBeNull();
expect(response.headers.get('vary')).toMatch(/Accept-Encoding/);
const body = await bytes(response);
expect(body.length).toBeLessThan(html.length / 4);
expect(brotliDecompressSync(body).toString()).toBe(html);
});
it('falls back to gzip for JSON', async () => {
const json = JSON.stringify({ rows: Array.from({ length: 200 }, (_, i) => ({ i })) });
const response = compressResponse(
request('gzip'),
new Response(json, { headers: { 'content-type': 'application/json' } })
);
expect(response.headers.get('content-encoding')).toBe('gzip');
expect(gunzipSync(await bytes(response)).toString()).toBe(json);
});
it('keeps set-cookie headers and the status', async () => {
const original = page(html, { status: 404 });
original.headers.append('set-cookie', 'a=1; Path=/');
original.headers.append('set-cookie', 'b=2; Path=/');
const response = compressResponse(request('br'), original);
expect(response.status).toBe(404);
expect(response.headers.getSetCookie()).toEqual(['a=1; Path=/', 'b=2; Path=/']);
});
it('flushes each streamed chunk rather than buffering the whole body', async () => {
let sendRest: () => void = () => {};
const stream = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new TextEncoder().encode('<p>shell</p>'));
sendRest = () => {
controller.enqueue(new TextEncoder().encode('<p>streamed data</p>'));
controller.close();
};
}
});
const response = compressResponse(request('gzip'), page(stream));
const reader = response.body!.getReader();
// The shell arrives while the stream is still open.
const first = await reader.read();
expect(gunzipSync(Buffer.from(first.value!), { finishFlush: 2 }).toString()).toBe(
'<p>shell</p>'
);
sendRest();
const rest: Uint8Array[] = [Buffer.from(first.value!)];
for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
rest.push(chunk.value);
}
expect(gunzipSync(Buffer.concat(rest)).toString()).toBe('<p>shell</p><p>streamed data</p>');
});
it('passes responses through inside a Netlify (Lambda) function', () => {
// adapter-netlify reads text bodies with response.text(), which would corrupt compressed bytes.
process.env.AWS_LAMBDA_FUNCTION_NAME = 'sveltekit-render';
try {
const original = page();
expect(compressResponse(request('br'), original)).toBe(original);
} finally {
delete process.env.AWS_LAMBDA_FUNCTION_NAME;
}
});
it.each([
['a client that accepts no encoding', request(), page()],
['a HEAD request', request('br', 'HEAD'), page(null)],
['an image', request('br'), new Response('png', { headers: { 'content-type': 'image/png' } })],
['a 304', request('br'), new Response(null, { status: 304 })],
[
'an already-encoded body',
request('br'),
new Response('x', { headers: { 'content-type': 'text/html', 'content-encoding': 'gzip' } })
]
])('leaves %s uncompressed', async (_label, req, res) => {
const response = compressResponse(req, res);
expect(response.headers.get('content-encoding')).toBe(res.headers.get('content-encoding'));
});
});
+103
View File
@@ -0,0 +1,103 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { afterCriticalPageWork, markGridInteractive } from '$lib/utils/criticalPageWork';
describe('optional work scheduling', () => {
let events: EventTarget & Record<string, unknown>;
let idle: (() => void) | undefined;
beforeEach(() => {
vi.useFakeTimers();
events = Object.assign(new EventTarget(), {
setTimeout,
clearTimeout,
requestIdleCallback: vi.fn((callback: () => void) => {
idle = callback;
return 1;
}),
cancelIdleCallback: vi.fn()
});
idle = undefined;
vi.stubGlobal('window', events);
vi.stubGlobal('location', { pathname: '/pokedex/example' });
vi.stubGlobal('document', { querySelector: () => null });
vi.stubGlobal('requestAnimationFrame', (callback: () => void) => setTimeout(callback, 16));
vi.stubGlobal('cancelAnimationFrame', clearTimeout);
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
it('waits for interactive cells, coalesces events, then runs at idle once', () => {
const run = vi.fn();
afterCriticalPageWork(run);
vi.advanceTimersByTime(1000);
expect(run).not.toHaveBeenCalled();
events.dispatchEvent(new Event('livingdex:grid-interactive'));
events.dispatchEvent(new Event('livingdex:grid-interactive'));
vi.advanceTimersByTime(16);
expect(events.requestIdleCallback).toHaveBeenCalledTimes(1);
expect(run).not.toHaveBeenCalled();
idle!();
vi.advanceTimersByTime(5000);
expect(run).toHaveBeenCalledTimes(1);
});
it('falls back after five seconds if no grid becomes interactive', () => {
const run = vi.fn();
afterCriticalPageWork(run);
vi.advanceTimersByTime(4999);
expect(run).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(run).toHaveBeenCalledTimes(1);
});
it('cancels work after navigation or an explicit refresh takes over', () => {
const run = vi.fn();
const cancel = afterCriticalPageWork(run);
events.dispatchEvent(new Event('livingdex:grid-interactive'));
vi.advanceTimersByTime(16);
cancel();
idle!();
vi.advanceTimersByTime(5000);
expect(run).not.toHaveBeenCalled();
});
it('does not announce a grid with no populated cells', () => {
const listener = vi.fn();
events.addEventListener('livingdex:grid-interactive', listener);
markGridInteractive();
expect(listener).not.toHaveBeenCalled();
});
it('schedules other pages without waiting for a grid, even without idle callbacks', () => {
vi.stubGlobal('location', { pathname: '/backup-settings' });
delete events.requestIdleCallback;
const run = vi.fn();
afterCriticalPageWork(run);
vi.advanceTimersByTime(32);
expect(run).toHaveBeenCalledTimes(1);
});
it('marks populated cells once and allows work registered after hydration', () => {
let ready = false;
const grid = {
setAttribute: () => {
ready = true;
}
};
const cell = { closest: () => grid };
vi.stubGlobal('document', {
querySelector: (selector: string) =>
selector === '[data-entry-index]' ? cell : ready ? grid : null
});
const mark = vi.fn();
vi.stubGlobal('performance', { mark });
markGridInteractive();
markGridInteractive();
expect(mark).toHaveBeenCalledTimes(1);
const run = vi.fn();
afterCriticalPageWork(run);
vi.advanceTimersByTime(16);
idle!();
expect(run).toHaveBeenCalledTimes(1);
});
it('does not access the DOM during SSR', () => {
vi.stubGlobal('window', undefined);
expect(() => markGridInteractive()).not.toThrow();
});
});
+24
View File
@@ -0,0 +1,24 @@
import { describe, expect, it } from 'vitest';
import { resolveGridSpriteUrl, resolveSpriteUrl } from '$lib/utils/spriteUrl';
describe('versioned grid artwork', () => {
it('separates grid and detail URLs for shiny, female and named forms', () => {
for (const form of ['', 'Female', 'Alolan', 'Female Mega']) {
for (const shiny of [false, true]) {
const entry = { pokedexNumber: 25, form, spriteKey: '25' };
const grid = resolveGridSpriteUrl(entry, shiny);
expect(grid).toBe(
resolveSpriteUrl(entry, shiny, true).replace(
'/sprites-small/home/',
'/sprites-grid/v1/home/'
)
);
expect(resolveSpriteUrl(entry, shiny, true)).not.toContain('sprites-grid');
}
}
});
// Source-to-output consistency is checked when artifacts are built, not required for a fresh unit-only checkout.
it('keeps the grid sprite URL version explicit', () => {
expect(resolveGridSpriteUrl({ pokedexNumber: 1 }, false)).toBe('/sprites-grid/v1/home/1.webp');
});
});
+27
View File
@@ -0,0 +1,27 @@
import { describe, it, expect } from 'vitest';
import { packGrid, unpackGrid, type PokedexGridRow } from '$lib/models/PokedexGridRow';
describe('grid transport', () => {
it('round-trips missing catches and every flag combination', () => {
const rows: PokedexGridRow[] = Array.from({ length: 17 }, (_, flags) => ({
pokedexEntry: {
_id: String(flags),
pokedexNumber: 25,
pokemon: 'Pikachu',
form: 'Female',
spriteKey: '25',
canGigantamax: true
},
catchRecord:
flags === 16
? null
: {
_id: `catch-${flags}`,
caught: !!(flags & 1),
haveToEvolve: !!(flags & 2),
inHome: !!(flags & 4),
hasGigantamaxed: !!(flags & 8)
}
}));
expect(unpackGrid(packGrid(rows))).toEqual(rows);
});
});
+57
View File
@@ -0,0 +1,57 @@
import { describe, expect, it, vi } from 'vitest';
const getUser = vi.fn();
const getSession = vi.fn();
vi.mock('$env/static/public', () => ({
PUBLIC_SUPABASE_URL: 'http://127.0.0.1:54321',
PUBLIC_SUPABASE_ANON_KEY: 'anon'
}));
vi.mock('@supabase/ssr', () => ({
createServerClient: () => ({ auth: { getUser, getSession } })
}));
const { handle } = await import('../../src/hooks.server');
async function runHandle() {
const event = {
cookies: { getAll: () => [], set: vi.fn() },
locals: {}
} as unknown as Parameters<typeof handle>[0]['event'];
await handle({ event, resolve: vi.fn(async () => new Response()) } as never);
return event.locals;
}
describe('safeGetSession', () => {
it('validates the session with Supabase Auth only once per request', async () => {
getUser.mockReset().mockResolvedValue({ data: { user: { id: 'user-1' } }, error: null });
getSession.mockReset().mockResolvedValue({ data: { session: { access_token: 't' } } });
const locals = await runHandle();
const [first, second] = await Promise.all([locals.safeGetSession(), locals.safeGetSession()]);
const third = await locals.safeGetSession();
expect(getUser).toHaveBeenCalledTimes(1);
expect(first.user?.id).toBe('user-1');
expect(second).toBe(first);
expect(third).toBe(first);
});
it('does not share a session between requests', async () => {
getUser.mockReset().mockResolvedValue({ data: { user: { id: 'user-1' } }, error: null });
getSession.mockReset().mockResolvedValue({ data: { session: {} } });
await (await runHandle()).safeGetSession();
await (await runHandle()).safeGetSession();
expect(getUser).toHaveBeenCalledTimes(2);
});
it('returns no session when the JWT is rejected', async () => {
getUser.mockReset().mockResolvedValue({ data: { user: null }, error: new Error('bad jwt') });
getSession.mockReset();
const locals = await runHandle();
await expect(locals.safeGetSession()).resolves.toEqual({ session: null, user: null });
expect(getSession).not.toHaveBeenCalled();
});
});
+58
View File
@@ -0,0 +1,58 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
vi.mock('$env/static/public', () => ({ PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER: 'true' }));
import { readOfflineEntry } from '$lib/stores/offlineSync';
describe('offline detail snapshots', () => {
const row = {
pokedexEntry: { _id: '1', catchInformation: 'Full instructions' },
catchRecord: { personalNotes: 'Saved note' }
};
function snapshot(owner = 'owner', ageMs = 0, includeEntry = true) {
const meta = {
userId: owner,
format: 2,
dataCache: `livingdex-offline-data-v1-${owner}-copy`,
generatedAt: new Date(Date.now() - ageMs).toISOString()
};
const cache = {
keys: async () => ['livingdex-offline-meta-v1', meta.dataCache],
open: async (name: string) => ({
match: async () =>
new Response(
JSON.stringify(
name === 'livingdex-offline-meta-v1'
? meta
: {
userId: owner,
version: 1,
pokedexes: [{ pokedex: { _id: 'dex' }, entries: includeEntry ? [row] : [] }]
}
)
)
})
};
vi.stubGlobal('window', { caches: cache });
vi.stubGlobal('caches', cache);
}
afterEach(() => vi.unstubAllGlobals());
it.each([0, 60 * 60 * 1000])(
'uses a matching full snapshot offline even when %i ms old',
async (age) => {
snapshot('owner', age);
expect(await readOfflineEntry('owner', 'dex', '1')).toEqual(row);
}
);
it('never reads another account snapshot', async () => {
snapshot('other');
expect(await readOfflineEntry('owner', 'dex', '1')).toBeNull();
});
it('reports missing entries and dexes without fabricating details', async () => {
snapshot('owner', 0, false);
expect(await readOfflineEntry('owner', 'dex', '1')).toBeNull();
expect(await readOfflineEntry('owner', 'missing', '1')).toBeNull();
});
it('works without Cache Storage', async () => {
vi.stubGlobal('window', {});
expect(await readOfflineEntry('owner', 'dex', '1')).toBeNull();
});
});
@@ -0,0 +1,257 @@
import { describe, expect, it, vi } from 'vitest';
import type { SupabaseClient } from '@supabase/supabase-js';
import PokedexExportIntegrationRepository from '$lib/repositories/PokedexExportIntegrationRepository';
type Result = { data: unknown; error: unknown };
/** A chainable stand-in for the Supabase query builder that records each call made on it. */
function fakeSupabase(result: Result) {
const calls: unknown[][] = [];
const builder: Record<string, unknown> = {};
for (const method of ['select', 'update', 'upsert', 'single', 'eq', 'is', 'or']) {
builder[method] = (...args: unknown[]) => {
calls.push([method, ...args]);
return builder;
};
}
// Awaiting the builder runs the query, as it does in supabase-js.
builder.then = (resolve: (value: Result) => unknown, reject?: (reason: unknown) => unknown) =>
Promise.resolve(result).then(resolve, reject);
const from = vi.fn(() => builder);
return { supabase: { from } as unknown as SupabaseClient, calls, from };
}
const VERSION = '2026-09-14T12:00:00.123456+00:00';
const WRITTEN: Result = { data: [{ id: 'int-1' }], error: null };
describe('PokedexExportIntegrationRepository.updateExportStatus', () => {
it('writes only while the row still has the version the caller read', async () => {
const { supabase, calls, from } = fakeSupabase(WRITTEN);
const repo = new PokedexExportIntegrationRepository(supabase, 'user-1', null);
const applied = await repo.updateExportStatus('int-1', { enabled: false }, VERSION);
expect(applied).toBe(true);
expect(from).toHaveBeenCalledWith('pokedex_export_integrations');
expect(calls).toEqual([
['update', { enabled: false }],
['eq', 'id', 'int-1'],
['eq', 'userId', 'user-1'],
['eq', 'updatedAt', VERSION],
['is', 'pokedexId', null],
['select', 'id']
]);
});
it('writes unconditionally without a version, scoped to the Pokédex', async () => {
const { supabase, calls } = fakeSupabase(WRITTEN);
const repo = new PokedexExportIntegrationRepository(supabase, 'user-1', 'dex-1');
expect(await repo.updateExportStatus('int-1', { lastError: null })).toBe(true);
expect(calls).toEqual([
['update', { lastError: null }],
['eq', 'id', 'int-1'],
['eq', 'userId', 'user-1'],
['eq', 'pokedexId', 'dex-1'],
['select', 'id']
]);
});
it.each([
['no row matched, e.g. after a reconnect changed it', { data: [], error: null }],
['the response carries no rows', { data: null, error: null }]
])('reports nothing written when %s', async (_label, result) => {
const { supabase } = fakeSupabase(result);
const repo = new PokedexExportIntegrationRepository(supabase, 'user-1', null);
expect(await repo.updateExportStatus('int-1', { enabled: false }, VERSION)).toBe(false);
});
it('logs and reports nothing written when the update fails', async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
const { supabase } = fakeSupabase({ data: null, error: { message: 'boom' } });
const repo = new PokedexExportIntegrationRepository(supabase, 'user-1', null);
expect(await repo.updateExportStatus('int-1', { enabled: false })).toBe(false);
expect(consoleError).toHaveBeenCalled();
consoleError.mockRestore();
});
});
describe('PokedexExportIntegrationRepository.listAll', () => {
it('maps each row version, defaulting a missing one to null', async () => {
const row = {
userId: 'user-1',
pokedexId: null,
provider: 'google_drive',
enabled: true,
fileName: null,
folderId: null,
path: null,
accessToken: 'access',
refreshToken: 'refresh',
accessTokenExpiresAt: null,
metadata: null,
lastExportedAt: null,
lastError: null
};
const { supabase } = fakeSupabase({
data: [
{ ...row, id: 'with-version', updatedAt: VERSION },
{ ...row, id: 'without-version' }
],
error: null
});
const repo = new PokedexExportIntegrationRepository(supabase, 'user-1', null);
const [withVersion, withoutVersion] = await repo.listAll();
expect(withVersion).toMatchObject({ _id: 'with-version', updatedAt: VERSION });
expect(withoutVersion).toMatchObject({ _id: 'without-version', updatedAt: null });
});
});
function dbRow(id: string) {
return {
id,
userId: 'user-1',
pokedexId: null,
provider: 'dropbox',
enabled: true,
fileName: null,
folderId: null,
path: '/Backups',
accessToken: 'access',
refreshToken: 'refresh',
accessTokenExpiresAt: null,
metadata: null,
lastExportedAt: null,
lastError: null,
updatedAt: VERSION
};
}
describe('PokedexExportIntegrationRepository queries', () => {
it('lists enabled integrations scoped to one Pokédex', async () => {
const { supabase, calls } = fakeSupabase({ data: [dbRow('int-1')], error: null });
const repo = new PokedexExportIntegrationRepository(supabase, 'user-1', 'dex-1');
const [integration] = await repo.listEnabled();
expect(integration).toMatchObject({ _id: 'int-1', provider: 'dropbox', path: '/Backups' });
expect(calls).toEqual([
['select', '*'],
['eq', 'userId', 'user-1'],
['eq', 'pokedexId', 'dex-1'],
['eq', 'enabled', true]
]);
});
it.each([
['dex-1', ['or', 'pokedexId.eq.dex-1,pokedexId.is.null']],
[null, ['is', 'pokedexId', null]]
])('lists enabled integrations for Pokédex %j or the whole account', async (pokedexId, scope) => {
const { supabase, calls } = fakeSupabase({ data: [dbRow('int-1')], error: null });
const repo = new PokedexExportIntegrationRepository(supabase, 'user-1', pokedexId);
expect(await repo.listEnabledForPokedexOrUser()).toHaveLength(1);
expect(calls).toEqual([
['select', '*'],
['eq', 'userId', 'user-1'],
['eq', 'enabled', true],
scope
]);
});
it.each(['listAll', 'listEnabled', 'listEnabledForPokedexOrUser'] as const)(
'%s returns nothing when no rows come back',
async (method) => {
const { supabase } = fakeSupabase({ data: null, error: null });
const repo = new PokedexExportIntegrationRepository(supabase, 'user-1', null);
expect(await repo[method]()).toEqual([]);
}
);
it.each(['listAll', 'listEnabled', 'listEnabledForPokedexOrUser'] as const)(
'%s throws when the query fails',
async (method) => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
const { supabase } = fakeSupabase({ data: null, error: { message: 'boom' } });
const repo = new PokedexExportIntegrationRepository(supabase, 'user-1', null);
await expect(repo[method]()).rejects.toThrow('Failed to load export integrations: boom');
consoleError.mockRestore();
}
);
});
describe('PokedexExportIntegrationRepository.upsert', () => {
it('saves one account-wide integration per provider', async () => {
const { supabase, calls } = fakeSupabase({ data: dbRow('int-1'), error: null });
const repo = new PokedexExportIntegrationRepository(supabase, 'user-1', 'dex-1');
const saved = await repo.upsert({ provider: 'dropbox', enabled: true, lastError: null });
expect(saved).toMatchObject({ _id: 'int-1', updatedAt: VERSION });
expect(calls).toEqual([
[
'upsert',
{
userId: 'user-1',
pokedexId: null,
provider: 'dropbox',
enabled: true,
lastError: null
},
{ onConflict: 'userId,provider' }
],
['select'],
['single']
]);
});
it.each([
['the save fails', { data: null, error: { message: 'boom' } }, 'boom'],
['nothing comes back', { data: null, error: null }, 'No result returned']
])('throws when %s', async (_label, result, message) => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
const { supabase } = fakeSupabase(result);
const repo = new PokedexExportIntegrationRepository(supabase, 'user-1', null);
await expect(repo.upsert({ provider: 'dropbox' })).rejects.toThrow(
`Failed to save export integration: ${message}`
);
consoleError.mockRestore();
});
});
describe('PokedexExportIntegrationRepository.updateTokens', () => {
it.each([
['dex-1', ['eq', 'pokedexId', 'dex-1']],
[null, ['is', 'pokedexId', null]]
])('stores refreshed tokens scoped to Pokédex %j', async (pokedexId, scope) => {
const { supabase, calls } = fakeSupabase({ data: null, error: null });
const repo = new PokedexExportIntegrationRepository(supabase, 'user-1', pokedexId);
const patch = { accessToken: 'new-access', accessTokenExpiresAt: null };
await repo.updateTokens('int-1', patch);
expect(calls).toEqual([
['update', patch],
['eq', 'id', 'int-1'],
['eq', 'userId', 'user-1'],
scope
]);
});
it('logs instead of throwing when the token update fails', async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
const { supabase } = fakeSupabase({ data: null, error: { message: 'boom' } });
const repo = new PokedexExportIntegrationRepository(supabase, 'user-1', null);
await expect(repo.updateTokens('int-1', { accessToken: 'x' })).resolves.toBeUndefined();
expect(consoleError).toHaveBeenCalled();
consoleError.mockRestore();
});
});
@@ -0,0 +1,519 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { SupabaseClient } from '@supabase/supabase-js';
import type { PokedexExportIntegration } from '$lib/models/PokedexExportIntegration';
const mocks = vi.hoisted(() => ({
env: {} as Record<string, string | undefined>,
pokedex: null as unknown,
integrations: [] as PokedexExportIntegration[],
updateExportStatus: vi.fn(),
updateTokens: vi.fn()
}));
vi.mock('$lib/utils/env', () => ({ getEnv: () => mocks.env }));
vi.mock('$lib/repositories/PokedexRepository', () => ({
default: vi.fn().mockImplementation(() => ({ findById: vi.fn(async () => mocks.pokedex) }))
}));
vi.mock('$lib/repositories/CombinedDataRepository', () => ({
default: vi.fn().mockImplementation(() => ({
findAllCombinedData: vi.fn().mockResolvedValue([])
}))
}));
vi.mock('$lib/services/PokedexDexScopeService', () => ({
resolveDexScopes: vi.fn().mockResolvedValue([])
}));
vi.mock('$lib/repositories/PokedexExportIntegrationRepository', () => ({
default: vi.fn().mockImplementation(() => ({
listEnabledForPokedexOrUser: vi.fn(async () => mocks.integrations),
updateExportStatus: mocks.updateExportStatus,
updateTokens: mocks.updateTokens
}))
}));
import { exportPokedexIfConfigured } from '$lib/services/PokedexExportService';
const supabase = {} as SupabaseClient;
const EXPIRED = () => new Date(Date.now() - 60_000).toISOString();
const FRESH = () => new Date(Date.now() + 3_600_000).toISOString();
/** The row version an export read; a guarded write only applies while it still matches. */
const VERSION = '2026-09-14T12:00:00.123456+00:00';
function integration(overrides: Partial<PokedexExportIntegration> = {}): PokedexExportIntegration {
return {
_id: 'google-1',
userId: 'user-1',
pokedexId: null,
provider: 'google_drive',
enabled: true,
fileName: null,
// A known folder skips the Drive folder lookup, keeping each test to token + upload calls.
folderId: 'folder-1',
path: null,
accessToken: 'old-access',
refreshToken: 'refresh',
accessTokenExpiresAt: EXPIRED(),
metadata: null,
lastExportedAt: null,
lastError: null,
updatedAt: VERSION,
...overrides
};
}
type Reply = { status: number; body: unknown };
const fetchMock = vi.fn();
/** Answers token requests with `token` and every other provider call with `upload`. */
function stubProvider(token: Reply, upload: Reply = { status: 200, body: { id: 'file-1' } }) {
fetchMock.mockImplementation(async (input: string) => {
const reply = input.includes('/token') ? token : upload;
const body = typeof reply.body === 'string' ? reply.body : JSON.stringify(reply.body);
return new Response(body, { status: reply.status });
});
}
const REVOKED: Reply = {
status: 400,
body: { error: 'invalid_grant', error_description: 'Bad Request' }
};
const REFRESHED: Reply = { status: 200, body: { access_token: 'new-access', expires_in: 3600 } };
function uploadCalls() {
return fetchMock.mock.calls.filter(([url]) => !String(url).includes('/token'));
}
/** Routes each provider call to a reply; returning a string or Error makes that fetch reject. */
function routeFetch(handler: (url: string, init?: RequestInit) => Reply | Error | string) {
fetchMock.mockImplementation(async (input: string, init?: RequestInit) => {
const reply = handler(input, init);
if (typeof reply === 'string' || reply instanceof Error) throw reply;
const body = typeof reply.body === 'string' ? reply.body : JSON.stringify(reply.body);
return new Response(body, { status: reply.status });
});
}
const FULL_ENV = {
GOOGLE_OAUTH_CLIENT_ID: 'google-id',
GOOGLE_OAUTH_CLIENT_SECRET: 'google-secret',
DROPBOX_OAUTH_CLIENT_ID: 'dropbox-id',
DROPBOX_OAUTH_CLIENT_SECRET: 'dropbox-secret'
};
const DEX = { _id: 'dex-1', name: 'My Dex', isFormDex: false, gameScope: '' };
let consoleError: ReturnType<typeof vi.spyOn>;
let consoleWarn: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
mocks.env = { ...FULL_ENV };
mocks.pokedex = DEX;
mocks.integrations = [];
mocks.updateExportStatus.mockReset();
// The repository reports whether a row was written; by default every write applies.
mocks.updateExportStatus.mockResolvedValue(true);
mocks.updateTokens.mockReset();
fetchMock.mockReset();
vi.stubGlobal('fetch', fetchMock);
consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
});
afterEach(() => {
vi.unstubAllGlobals();
// Only undo the spies: vi.restoreAllMocks() would also wipe the repository module mocks above.
consoleError.mockRestore();
consoleWarn.mockRestore();
});
describe('exportPokedexIfConfigured when a provider revokes access', () => {
it.each([
['google_drive', 'google-1', /Reconnect Google Drive/],
['dropbox', 'dropbox-1', /Reconnect Dropbox/]
] as const)('pauses %s when its refresh token is revoked', async (provider, id, message) => {
mocks.integrations = [integration({ _id: id, provider })];
stubProvider(REVOKED);
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result).toMatchObject({ attempted: 1, succeeded: 0 });
expect(result.failed).toEqual([
{
integrationId: id,
provider,
error: expect.stringMatching(message),
reconnectRequired: true
}
]);
expect(mocks.updateExportStatus).toHaveBeenCalledWith(
id,
{ lastError: expect.stringMatching(message), enabled: false },
VERSION
);
expect(uploadCalls()).toHaveLength(0);
expect(mocks.updateTokens).not.toHaveBeenCalled();
});
it('pauses an integration that has no refresh token without calling the provider', async () => {
mocks.integrations = [integration({ refreshToken: null })];
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result.failed[0]).toMatchObject({ reconnectRequired: true });
expect(mocks.updateExportStatus).toHaveBeenCalledWith(
'google-1',
{ lastError: expect.stringMatching(/Reconnect Google Drive/), enabled: false },
VERSION
);
expect(fetchMock).not.toHaveBeenCalled();
});
it('leaves a backup reconnected during the export enabled and unflagged', async () => {
mocks.integrations = [integration()];
stubProvider(REVOKED);
// The guarded pause matches no row: a reconnect changed it after this export read it.
mocks.updateExportStatus.mockResolvedValue(false);
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(mocks.updateExportStatus).toHaveBeenCalledTimes(1);
expect(mocks.updateExportStatus).toHaveBeenCalledWith(
'google-1',
{ lastError: expect.stringMatching(/Reconnect Google Drive/), enabled: false },
VERSION
);
// The client must not tell the user to reconnect a connection that is already fresh.
expect(result.failed[0]).toMatchObject({ reconnectRequired: false });
});
it.each([
['a server error', { status: 500, body: 'upstream down' }],
['a different OAuth error', { status: 400, body: { error: 'invalid_client' } }]
])('keeps the integration enabled when the refresh fails with %s', async (_label, token) => {
mocks.integrations = [integration()];
stubProvider(token);
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result.failed[0]).toMatchObject({
reconnectRequired: false,
error: expect.stringMatching(/^Google token refresh failed: /)
});
// Exactly this patch: no `enabled` key, so a transient failure is retried on the next export.
expect(mocks.updateExportStatus).toHaveBeenCalledWith('google-1', {
lastError: expect.stringMatching(/^Google token refresh failed: /)
});
});
it('keeps the integration enabled when only the upload fails', async () => {
mocks.integrations = [integration({ accessTokenExpiresAt: FRESH() })];
stubProvider(REFRESHED, { status: 503, body: { error: 'mock upload failure' } });
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result.failed[0]).toMatchObject({ reconnectRequired: false });
expect(mocks.updateExportStatus).toHaveBeenCalledWith('google-1', {
lastError: expect.stringMatching(/Google Drive upload failed: 503/)
});
});
it('refreshes an expired token, uploads, and clears the previous error', async () => {
mocks.integrations = [integration({ lastError: 'old failure' })];
stubProvider(REFRESHED);
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result).toEqual({ attempted: 1, succeeded: 1, failed: [] });
expect(mocks.updateTokens).toHaveBeenCalledWith('google-1', {
accessToken: 'new-access',
accessTokenExpiresAt: expect.any(String)
});
expect(uploadCalls()[0][1].headers.Authorization).toBe('Bearer new-access');
expect(mocks.updateExportStatus).toHaveBeenCalledWith('google-1', {
lastExportedAt: expect.any(String),
lastError: null
});
});
it('pauses only the revoked provider when another one still works', async () => {
mocks.integrations = [
integration(),
integration({ _id: 'dropbox-1', provider: 'dropbox', accessTokenExpiresAt: FRESH() })
];
fetchMock.mockImplementation(async (input: string) =>
input.includes('googleapis.com/token')
? new Response(JSON.stringify(REVOKED.body), { status: 400 })
: new Response(JSON.stringify({ id: 'file-1' }), { status: 200 })
);
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result).toMatchObject({ attempted: 2, succeeded: 1 });
expect(result.failed.map((failure) => failure.provider)).toEqual(['google_drive']);
const pausedIds = mocks.updateExportStatus.mock.calls
.filter(([, patch]) => patch.enabled === false)
.map(([integrationId]) => integrationId);
expect(pausedIds).toEqual(['google-1']);
});
});
const DRIVE_API = 'https://www.googleapis.com/drive/v3';
const DRIVE_UPLOAD = 'https://www.googleapis.com/upload/drive/v3';
function isDriveUpload(url: string) {
return url.startsWith(DRIVE_UPLOAD);
}
/** The JSON metadata part of a Drive multipart upload body. */
function driveUploadMetadata(init?: RequestInit) {
return JSON.parse(String(init?.body).split('\r\n')[3]) as Record<string, unknown>;
}
function statusPatches() {
return mocks.updateExportStatus.mock.calls.map(([, patch]) => patch as Record<string, unknown>);
}
describe('exportPokedexIfConfigured provider paths', () => {
it('does nothing when the Pokédex no longer exists', async () => {
mocks.pokedex = null;
mocks.integrations = [integration()];
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result).toEqual({ attempted: 0, succeeded: 0, failed: [] });
expect(fetchMock).not.toHaveBeenCalled();
expect(mocks.updateExportStatus).not.toHaveBeenCalled();
});
it('does nothing when no backup is connected', async () => {
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result).toEqual({ attempted: 0, succeeded: 0, failed: [] });
expect(fetchMock).not.toHaveBeenCalled();
});
it.each([
['google_drive', 'GOOGLE_OAUTH_CLIENT_SECRET', 'Missing Google OAuth client credentials'],
['dropbox', 'DROPBOX_OAUTH_CLIENT_ID', 'Missing Dropbox OAuth client credentials']
] as const)(
'reports missing %s OAuth credentials without pausing the backup',
async (provider, envKey, error) => {
delete mocks.env[envKey];
mocks.integrations = [integration({ provider })];
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result.failed[0]).toMatchObject({ error, reconnectRequired: false });
expect(fetchMock).not.toHaveBeenCalled();
}
);
it('pauses Dropbox when it has no refresh token', async () => {
mocks.integrations = [integration({ provider: 'dropbox', refreshToken: null })];
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result.failed[0]).toMatchObject({
error: expect.stringMatching(/Reconnect Dropbox/),
reconnectRequired: true
});
});
it('keeps Dropbox enabled when its token refresh fails for another reason', async () => {
mocks.integrations = [integration({ provider: 'dropbox' })];
stubProvider({ status: 500, body: 'upstream down' });
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result.failed[0]).toMatchObject({
error: 'Dropbox token refresh failed: 500 upstream down',
reconnectRequired: false
});
});
it('stores a refreshed token without an expiry when the provider omits one', async () => {
mocks.integrations = [integration({ _id: 'dropbox-1', provider: 'dropbox' })];
stubProvider({ status: 200, body: { access_token: 'new-access' } });
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result.succeeded).toBe(1);
expect(mocks.updateTokens).toHaveBeenCalledWith('dropbox-1', {
accessToken: 'new-access',
accessTokenExpiresAt: null
});
expect(uploadCalls()[0][1].headers.Authorization).toBe('Bearer new-access');
});
it.each([
[null, '/My Dex.csv'],
['/Backups/', '/Backups/My Dex.csv'],
['/Backups', '/Backups/My Dex.csv'],
[' /Backups/custom.CSV ', '/Backups/custom.CSV']
])('uploads to Dropbox path %j as %s', async (path, expected) => {
mocks.integrations = [
integration({ provider: 'dropbox', path, accessTokenExpiresAt: FRESH() })
];
stubProvider(REFRESHED);
await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
const headers = uploadCalls()[0][1].headers as Record<string, string>;
expect(JSON.parse(headers['Dropbox-API-Arg'])).toEqual({
path: expected,
mode: 'overwrite',
mute: true
});
});
it('reports a failed Dropbox upload', async () => {
mocks.integrations = [integration({ provider: 'dropbox', accessTokenExpiresAt: FRESH() })];
stubProvider(REFRESHED, { status: 500, body: 'boom' });
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result.failed[0]).toMatchObject({
error: 'Dropbox upload failed: 500 boom',
reconnectRequired: false
});
});
it('finds the existing Living Dex Tracker folder in Drive', async () => {
mocks.integrations = [integration({ folderId: null, accessTokenExpiresAt: FRESH() })];
routeFetch((url) => {
if (url.startsWith(`${DRIVE_API}/files?`))
return { status: 200, body: { files: [{ id: 'found' }] } };
if (isDriveUpload(url)) return { status: 200, body: { id: 'file-1' } };
return { status: 500, body: `unexpected ${url}` };
});
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result.succeeded).toBe(1);
const [, init] = uploadCalls().find(([url]) => isDriveUpload(String(url)))!;
expect(driveUploadMetadata(init).parents).toEqual(['found']);
expect(statusPatches()).toContainEqual({ folderId: 'found' });
expect(fetchMock.mock.calls.some(([url]) => url === `${DRIVE_API}/files`)).toBe(false);
});
it('creates the Living Dex Tracker folder when Drive has none', async () => {
mocks.integrations = [integration({ folderId: null, accessTokenExpiresAt: FRESH() })];
routeFetch((url) => {
if (url.startsWith(`${DRIVE_API}/files?`)) return { status: 200, body: { files: [] } };
if (url === `${DRIVE_API}/files`) return { status: 200, body: { id: 'created' } };
return { status: 200, body: { id: 'file-1' } };
});
await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
const [, init] = uploadCalls().find(([url]) => isDriveUpload(String(url)))!;
expect(driveUploadMetadata(init).parents).toEqual(['created']);
});
it.each([
['rejects the requests', { status: 500, body: 'nope' }],
['cannot be reached', new TypeError('Failed to fetch')]
])('uploads to the Drive root when the folder API %s', async (_label, folderReply) => {
mocks.integrations = [integration({ folderId: null, accessTokenExpiresAt: FRESH() })];
routeFetch((url) =>
isDriveUpload(url) ? { status: 200, body: { id: 'file-1' } } : folderReply
);
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result.succeeded).toBe(1);
const [, init] = uploadCalls().find(([url]) => isDriveUpload(String(url)))!;
expect(driveUploadMetadata(init).parents).toBeUndefined();
expect(statusPatches().some((patch) => 'folderId' in patch)).toBe(false);
expect(statusPatches()).toContainEqual({ metadata: { files: { 'dex-1': 'file-1' } } });
});
it('updates the existing Drive file in place', async () => {
mocks.integrations = [
integration({ accessTokenExpiresAt: FRESH(), metadata: { files: { 'dex-1': 'file-1' } } })
];
stubProvider(REFRESHED, { status: 200, body: { id: 'file-1' } });
await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
const [url, init] = uploadCalls()[0];
expect(url).toBe(`${DRIVE_UPLOAD}/files/file-1?uploadType=multipart&addParents=folder-1`);
expect(init.method).toBe('PATCH');
expect(driveUploadMetadata(init).parents).toBeUndefined();
expect(statusPatches().some((patch) => 'metadata' in patch)).toBe(false);
});
it.each([
[
'the only saved file',
{ scope: 's', files: { 'dex-1': 'stale' } },
{ scope: 's' },
{ scope: 's', files: { 'dex-1': 'new-file' } }
],
[
'one of several saved files',
{ files: { 'dex-1': 'stale', 'dex-2': 'other' } },
{ files: { 'dex-2': 'other' } },
{ files: { 'dex-1': 'new-file', 'dex-2': 'other' } }
]
])(
'recreates a Drive file deleted by the user when it was %s',
async (_label, metadata, cleared, saved) => {
mocks.integrations = [integration({ accessTokenExpiresAt: FRESH(), metadata })];
routeFetch((_url, init) =>
init?.method === 'PATCH'
? { status: 404, body: 'File not found' }
: { status: 200, body: { id: 'new-file' } }
);
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result.succeeded).toBe(1);
expect(uploadCalls().map(([, init]) => init.method)).toEqual(['PATCH', 'POST']);
expect(driveUploadMetadata(uploadCalls()[1][1]).parents).toEqual(['folder-1']);
const metadataPatches = statusPatches().filter((patch) => 'metadata' in patch);
expect(metadataPatches).toEqual([{ metadata: cleared }, { metadata: saved }]);
}
);
it('gives up when the recreated Drive file is also missing', async () => {
mocks.integrations = [
integration({ accessTokenExpiresAt: FRESH(), metadata: { files: { 'dex-1': 'stale' } } })
];
stubProvider(REFRESHED, { status: 404, body: 'File not found' });
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(uploadCalls()).toHaveLength(2);
expect(result.failed[0]).toMatchObject({
error: 'Google Drive upload failed: 404 File not found',
reconnectRequired: false
});
});
it('records the export even when Drive returns no file id', async () => {
mocks.integrations = [integration({ accessTokenExpiresAt: FRESH() })];
stubProvider(REFRESHED, { status: 200, body: {} });
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result.succeeded).toBe(1);
expect(statusPatches()).toEqual([{ lastExportedAt: expect.any(String), lastError: null }]);
});
it('reports a failure that is not an Error as text', async () => {
mocks.integrations = [integration({ accessTokenExpiresAt: FRESH() })];
routeFetch(() => 'network down');
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(result.failed[0]).toMatchObject({ error: 'network down', reconnectRequired: false });
});
it('does nothing for a provider it does not support', async () => {
mocks.integrations = [integration({ provider: 'onedrive' as never })];
const result = await exportPokedexIfConfigured(supabase, 'user-1', 'dex-1');
expect(fetchMock).not.toHaveBeenCalled();
expect(result).toMatchObject({ attempted: 1, failed: [] });
});
});
+12
View File
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import {
buildCsv,
csvEscape,
isRevokedGrant,
sanitizeFileName,
shouldRefreshToken
} from '$lib/services/PokedexExportFormatting';
@@ -59,6 +60,17 @@ describe('Pokédex export formatting', () => {
]);
});
it('recognises a revoked or expired refresh token', () => {
expect(isRevokedGrant(400, '{"error":"invalid_grant","error_description":"Bad Request"}')).toBe(
true
);
expect(isRevokedGrant(401, '{"error":"invalid_grant"}')).toBe(true);
expect(isRevokedGrant(400, '{"error":"invalid_client"}')).toBe(false);
expect(isRevokedGrant(500, '{"error":"invalid_grant"}')).toBe(false);
expect(isRevokedGrant(400, 'Bad Request')).toBe(false);
expect(isRevokedGrant(400, 'null')).toBe(false);
});
it('refreshes only finite expiries within the next minute', () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-09-13T12:00:00Z'));
+36
View File
@@ -0,0 +1,36 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { PokedexPerformance } from '$lib/server/pokedexPerformance';
afterEach(() => vi.unstubAllEnvs());
describe('opt-in stage timing', () => {
it('emits no timing header without explicit opt-in', async () => {
vi.stubEnv('POKEDEX_PERFORMANCE', 'false');
const timing = new PokedexPerformance();
expect(await timing.measure('entries', async () => 'result')).toBe('result');
expect(timing.prepare(() => 3)).toBe(3);
timing.recordAuth(10);
expect(timing.finish()).toBeUndefined();
});
it('records failed stages without exposing exception content', async () => {
vi.stubEnv('POKEDEX_PERFORMANCE', 'true');
const timing = new PokedexPerformance();
await expect(
timing.measure('catches', async () => {
throw new Error('private note');
})
).rejects.toThrow('private note');
expect(() =>
timing.prepare(() => {
throw new Error('private ID');
})
).toThrow('private ID');
timing.recordAuth(undefined);
timing.recordAuth(12.34);
const header = timing.finish()!;
expect(header).toContain('auth;dur=12.3');
expect(header).toMatch(/catches;dur=\d+\.\d/);
expect(header).toMatch(/prepare;dur=\d+\.\d/);
expect(header).toMatch(/total;dur=\d+\.\d/);
expect(header).not.toContain('private');
});
});
+13 -2
View File
@@ -1,10 +1,21 @@
import { sveltekit } from '@sveltejs/kit/vite';
import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vite';
import { SvelteKitPWA } from '@vite-pwa/sveltekit';
// you don't need to do this if you're using generateSW strategy in your app
import { generateSW } from './pwa.mjs';
export default defineConfig({
resolve: {
alias:
process.env.DEPLOY_TARGET === 'cloudflare'
? {
'$lib/server/compression': fileURLToPath(
new URL('./src/lib/server/compression.cloudflare.ts', import.meta.url)
)
}
: {}
},
plugins: [
sveltekit(),
SvelteKitPWA({
@@ -46,11 +57,11 @@ export default defineConfig({
},
injectManifest: {
globPatterns: ['client/**/*.{html,js,css,ico,png,svg,webp,woff,woff2,webmanifest}'],
globIgnores: ['**/sprites/**', '**/sprites-small/**']
globIgnores: ['**/sprites/**', '**/sprites-small/**', '**/sprites-grid/**']
},
workbox: {
globPatterns: ['client/**/*.{html,js,css,ico,png,svg,webp,woff,woff2,webmanifest}'],
globIgnores: ['**/sprites/**', '**/sprites-small/**'],
globIgnores: ['**/sprites/**', '**/sprites-small/**', '**/sprites-grid/**'],
// Shared message/fetch handling keeps generateSW and injectManifest behavior equal.
importScripts: ['/offline-worker.js']
},
+4 -4
View File
@@ -22,10 +22,10 @@ export default defineConfig({
exclude: ['src/lib/models/**', 'src/lib/stores/**', 'src/lib/actions/**'],
// Set to the measured baseline. Ratchet these up as coverage grows; never down.
thresholds: {
statements: 34.58,
functions: 73.68,
lines: 34.58,
branches: 79.79
statements: 59.73,
functions: 85.88,
lines: 59.73,
branches: 88.35
}
}
}
+13
View File
@@ -0,0 +1,13 @@
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "livingdextracker-preview",
"main": ".svelte-kit/cloudflare/_worker.js",
"compatibility_date": "2026-09-15",
"compatibility_flags": ["nodejs_compat"],
"assets": {
"directory": ".svelte-kit/cloudflare",
"binding": "ASSETS"
},
"observability": { "enabled": true },
"vars": { "POKEDEX_PERFORMANCE": "true" }
}